file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.8.6; //SPDX-License-Identifier: MIT Licensed //HJAELPCOIN - Pre-sale DApp interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external; function transfer(address to, uint256 value) external; function transferFrom( address from, address to, uint256 value ) external; event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); } interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } contract preSaleHJAELP { using SafeMath for uint256; IERC20 public token; AggregatorV3Interface public priceFeedeth; address payable public owner; uint256 public tokensPerEth; uint256 public minAmount; uint256 public maxAmount; uint256 public preSaleStartTime; uint256 public preSaleEndTime; uint256 public soldToken; uint256 public amountRaisedEth; uint256 public totalusers; modifier onlyOwner() { require(msg.sender == owner, "PRESALE: Not an owner"); _; } mapping(address => uint256) public coinBalance; event BuyToken(address indexed _user, uint256 indexed _amount); constructor(address payable _owner, IERC20 _token) { owner = _owner; token = _token; priceFeedeth = AggregatorV3Interface( 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 ); tokensPerEth = 333333; minAmount = 0.02 ether; maxAmount = 8 ether; preSaleStartTime = block.timestamp; preSaleEndTime = preSaleStartTime + 30 days; } receive() external payable {} // to get real time price of eth function getLatestPriceEth() public view returns (uint256) { (, int256 price, , , ) = priceFeedeth.latestRoundData(); return uint256(price); } // to buy token during preSale time => for web3 use function buyToken() public payable { require( block.timestamp >= preSaleStartTime && block.timestamp < preSaleEndTime, "PRESALE: PreSale time not met" ); require( coinBalance[msg.sender].add(msg.value) <= maxAmount, "PRESALE: Amount exceeds max limit" ); require( msg.value >= minAmount && msg.value <= maxAmount, "PRESALE: Amount not correct" ); if (token.balanceOf(msg.sender) == 0) { totalusers++; } uint256 numberOfTokens = ethToToken(msg.value); token.transferFrom(owner, msg.sender, numberOfTokens); soldToken = soldToken.add(numberOfTokens); amountRaisedEth = amountRaisedEth.add(msg.value); coinBalance[msg.sender] = coinBalance[msg.sender].add(msg.value); emit BuyToken(msg.sender, numberOfTokens); } // to check number of token for given eth function ethToToken(uint256 _amount) public view returns (uint256) { uint256 numberOfTokens = _amount.mul(tokensPerEth); return numberOfTokens; } // to change Price of the token function changePrice(uint256 _price) external onlyOwner { tokensPerEth = _price; } // to change preSale amount limits function setPreSaletLimits(uint256 _minAmount, uint256 _maxAmount) external onlyOwner { minAmount = _minAmount; maxAmount = _maxAmount; } // to change preSale time duration function setPreSaleTime(uint256 _startTime, uint256 _endTime) external onlyOwner { preSaleStartTime = _startTime; preSaleEndTime = _endTime; } // transfer ownership function changeOwner(address payable _newOwner) external onlyOwner { owner = _newOwner; } function changePriceFeed(address _newPriceFeed) external onlyOwner { priceFeedeth = AggregatorV3Interface(_newPriceFeed); } function changeToken(address _newToken) external onlyOwner { token = IERC20(_newToken); } // to draw funds for liquidity function transferFunds(uint256 _value) external onlyOwner { owner.transfer(_value); } // to draw out tokens function transferTokens(uint256 _value) external onlyOwner { token.transfer(owner, _value); } // to get current UTC time function getCurrentTime() external view returns (uint256) { return block.timestamp; } function contractBalanceEth() external view returns (uint256) { return address(this).balance; } function getContractTokenApproval() external view returns (uint256) { return token.allowance(owner, address(this)); } } 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) { // 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 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; } 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; } }
to get real time price of eth
function getLatestPriceEth() public view returns (uint256) { (, int256 price, , , ) = priceFeedeth.latestRoundData(); return uint256(price); }
6,173,135
//Address: 0xab37d7c4a2ae9ad4451aa796171dc8ac0fa429f4 //Contract name: IcoToken //Balance: 0 Ether //Verification Date: 2/2/2018 //Transacion Count: 95 // CODE STARTS HERE //File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } //File: node_modules/zeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } //File: node_modules/zeppelin-solidity/contracts/token/ERC20/BasicToken.sol pragma solidity ^0.4.18; /** * @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: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.18; /** * @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: node_modules/zeppelin-solidity/contracts/token/ERC20/StandardToken.sol pragma solidity ^0.4.18; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } //File: node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.18; /** * @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: node_modules/zeppelin-solidity/contracts/token/ERC20/MintableToken.sol pragma solidity ^0.4.18; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } //File: node_modules/zeppelin-solidity/contracts/crowdsale/Crowdsale.sol pragma solidity ^0.4.18; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } } //File: node_modules/zeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.4.18; /** * @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: node_modules/zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.4.18; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } //File: node_modules/zeppelin-solidity/contracts/token/ERC20/TokenVesting.sol pragma solidity ^0.4.18; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } //File: node_modules/zeppelin-solidity/contracts/token/ERC20/PausableToken.sol pragma solidity ^0.4.18; /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } //File: src/contracts/ico/DividendToken.sol /** * @title Dividend contract * * @version 1.0 * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.4.18; contract DividendToken is StandardToken, Ownable { using SafeMath for uint256; // time before dividendEndTime during which dividend cannot be claimed by token holders // instead the unclaimed dividend can be claimed by treasury in that time span uint256 public claimTimeout = 20 days; uint256 public dividendCycleTime = 350 days; uint256 public currentDividend; mapping(address => uint256) unclaimedDividend; // tracks when the dividend balance has been updated last time mapping(address => uint256) public lastUpdate; uint256 public lastDividendIncreaseDate; // allow payment of dividend only by special treasury account (treasury can be set and altered by owner, // multiple treasurer accounts are possible mapping(address => bool) public isTreasurer; uint256 public dividendEndTime = 0; event Payin(address _owner, uint256 _value, uint256 _endTime); event Payout(address _tokenHolder, uint256 _value); event Reclaimed(uint256 remainingBalance, uint256 _endTime, uint256 _now); event ChangedTreasurer(address treasurer, bool active); /** * @dev Deploy the DividendToken contract and set the owner of the contract */ function DividendToken() public { isTreasurer[owner] = true; } /** * @dev Request payout dividend (claim) (requested by tokenHolder -> pull) * dividends that have not been claimed within 330 days expire and cannot be claimed anymore by the token holder. */ function claimDividend() public returns (bool) { // unclaimed dividend fractions should expire after 330 days and the owner can reclaim that fraction require(dividendEndTime > 0 && dividendEndTime.sub(claimTimeout) > now); updateDividend(msg.sender); uint256 payment = unclaimedDividend[msg.sender]; unclaimedDividend[msg.sender] = 0; msg.sender.transfer(payment); // Trigger payout event Payout(msg.sender, payment); return true; } /** * @dev Transfer dividend (fraction) to new token holder * @param _from address The address of the old token holder * @param _to address The address of the new token holder * @param _value uint256 Number of tokens to transfer */ function transferDividend(address _from, address _to, uint256 _value) internal { updateDividend(_from); updateDividend(_to); uint256 transAmount = unclaimedDividend[_from].mul(_value).div(balanceOf(_from)); unclaimedDividend[_from] = unclaimedDividend[_from].sub(transAmount); unclaimedDividend[_to] = unclaimedDividend[_to].add(transAmount); } /** * @dev Update the dividend of hodler * @param _hodler address The Address of the hodler */ function updateDividend(address _hodler) internal { // last update in previous period -> reset claimable dividend if (lastUpdate[_hodler] < lastDividendIncreaseDate) { unclaimedDividend[_hodler] = calcDividend(_hodler, totalSupply_); lastUpdate[_hodler] = now; } } /** * @dev Get claimable dividend for the hodler * @param _hodler address The Address of the hodler */ function getClaimableDividend(address _hodler) public constant returns (uint256 claimableDividend) { if (lastUpdate[_hodler] < lastDividendIncreaseDate) { return calcDividend(_hodler, totalSupply_); } else { return (unclaimedDividend[_hodler]); } } /** * @dev Overrides transfer method from BasicToken * transfer token for a specified address * @param _to address The address to transfer to. * @param _value uint256 The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { transferDividend(msg.sender, _to, _value); // Return from inherited transfer method return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { // Prevent dividend to be claimed twice transferDividend(_from, _to, _value); // Return from inherited transferFrom method return super.transferFrom(_from, _to, _value); } /** * @dev Set / alter treasurer "account". This can be done from owner only * @param _treasurer address Address of the treasurer to create/alter * @param _active bool Flag that shows if the treasurer account is active */ function setTreasurer(address _treasurer, bool _active) public onlyOwner { isTreasurer[_treasurer] = _active; ChangedTreasurer(_treasurer, _active); } /** * @dev Request unclaimed ETH, payback to beneficiary (owner) wallet * dividend payment is possible every 330 days at the earliest - can be later, this allows for some flexibility, * e.g. board meeting had to happen a bit earlier this year than previous year. */ function requestUnclaimed() public onlyOwner { // Send remaining ETH to beneficiary (back to owner) if dividend round is over require(now >= dividendEndTime.sub(claimTimeout)); msg.sender.transfer(this.balance); Reclaimed(this.balance, dividendEndTime, now); } /** * @dev ETH Payin for Treasurer * Only owner or treasurer can do a payin for all token holder. * Owner / treasurer can also increase dividend by calling fallback function multiple times. */ function() public payable { require(isTreasurer[msg.sender]); require(dividendEndTime < now); // pay back unclaimed dividend that might not have been claimed by owner yet if (this.balance > msg.value) { uint256 payout = this.balance.sub(msg.value); owner.transfer(payout); Reclaimed(payout, dividendEndTime, now); } currentDividend = this.balance; // No active dividend cycle found, initialize new round dividendEndTime = now.add(dividendCycleTime); // Trigger payin event Payin(msg.sender, msg.value, dividendEndTime); lastDividendIncreaseDate = now; } /** * @dev calculate the dividend * @param _hodler address * @param _totalSupply uint256 */ function calcDividend(address _hodler, uint256 _totalSupply) public view returns(uint256) { return (currentDividend.mul(balanceOf(_hodler))).div(_totalSupply); } } //File: src/contracts/ico/IcoToken.sol /** * @title ICO token * @version 1.0 * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.4.18; contract IcoToken is MintableToken, PausableToken, DividendToken { string public constant name = "Tend Token"; string public constant symbol = "TND"; uint8 public constant decimals = 18; /** * @dev Constructor of IcoToken that instantiate a new DividendToken */ function IcoToken() public DividendToken() { // token should not be transferrable until after all tokens have been issued paused = true; } } //File: src/contracts/ico/IcoCrowdsale.sol /** * @title IcoCrowdsale * Simple time and capped based crowdsale. * * @version 1.0 * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.4.18; contract IcoCrowdsale is Crowdsale, Ownable { /*** CONSTANTS ***/ // Different levels of caps per allotment uint256 public constant MAX_TOKEN_CAP = 13e6 * 1e18; // 13 million * 1e18 // // Bottom three should add to above uint256 public constant ICO_ENABLERS_CAP = 15e5 * 1e18; // 1.5 million * 1e18 uint256 public constant DEVELOPMENT_TEAM_CAP = 2e6 * 1e18; // 2 million * 1e18 uint256 public constant ICO_TOKEN_CAP = 9.5e6 * 1e18; // 9.5 million * 1e18 uint256 public constant CHF_CENT_PER_TOKEN = 1000; // standard CHF per token rate - in cents - 10 CHF => 1000 CHF cents uint256 public constant MIN_CONTRIBUTION_CHF = 250; uint256 public constant VESTING_CLIFF = 1 years; uint256 public constant VESTING_DURATION = 3 years; // Amount of discounted tokens per discount stage (2 stages total; each being the same amount) uint256 public constant DISCOUNT_TOKEN_AMOUNT_T1 = 3e6 * 1e18; // 3 million * 1e18 uint256 public constant DISCOUNT_TOKEN_AMOUNT_T2 = DISCOUNT_TOKEN_AMOUNT_T1 * 2; // Track tokens depending which stage that the ICO is in uint256 public tokensToMint; // tokens to be minted after confirmation uint256 public tokensMinted; // already minted tokens (maximally = cap) uint256 public icoEnablersTokensMinted; uint256 public developmentTeamTokensMinted; uint256 public minContributionInWei; uint256 public tokenPerWei; uint256 public totalTokensPurchased; bool public capReached; bool public tier1Reached; bool public tier2Reached; address public underwriter; // allow managers to blacklist and confirm contributions by manager accounts // (managers can be set and altered by owner, multiple manager accounts are possible mapping(address => bool) public isManager; // true if addess is not allowed to invest mapping(address => bool) public isBlacklisted; uint256 public confirmationPeriod; bool public confirmationPeriodOver; // can be set by owner to finish confirmation in under 30 days // for convenience we store vesting wallets address[] public vestingWallets; uint256 public investmentIdLastAttemptedToSettle; struct Payment { address investor; address beneficiary; uint256 weiAmount; uint256 tokenAmount; bool confirmed; bool attemptedSettlement; bool completedSettlement; } Payment[] public investments; /*** EVENTS ***/ event ChangedInvestorBlacklisting(address investor, bool blacklisted); event ChangedManager(address manager, bool active); event ChangedInvestmentConfirmation(uint256 investmentId, address investor, bool confirmed); /*** MODIFIERS ***/ modifier onlyUnderwriter() { require(msg.sender == underwriter); _; } modifier onlyManager() { require(isManager[msg.sender]); _; } modifier onlyNoneZero(address _to, uint256 _amount) { require(_to != address(0)); require(_amount > 0); _; } modifier onlyConfirmPayment() { require(now > endTime && now <= endTime.add(confirmationPeriod)); require(!confirmationPeriodOver); _; } modifier onlyConfirmationOver() { require(confirmationPeriodOver || now > endTime.add(confirmationPeriod)); _; } /** * @dev Deploy capped ico crowdsale contract * @param _startTime uint256 Start time of the crowdsale * @param _endTime uint256 End time of the crowdsale * @param _rateChfPerEth uint256 CHF per ETH rate * @param _wallet address Wallet address of the crowdsale * @param _confirmationPeriodDays uint256 Confirmation period in days * @param _underwriter address of the underwriter */ function IcoCrowdsale( uint256 _startTime, uint256 _endTime, uint256 _rateChfPerEth, address _wallet, uint256 _confirmationPeriodDays, address _underwriter ) public Crowdsale(_startTime, _endTime, _rateChfPerEth, _wallet) { require(MAX_TOKEN_CAP == ICO_ENABLERS_CAP.add(ICO_TOKEN_CAP).add(DEVELOPMENT_TEAM_CAP)); require(_underwriter != address(0)); setManager(msg.sender, true); tokenPerWei = (_rateChfPerEth.mul(1e2)).div(CHF_CENT_PER_TOKEN); minContributionInWei = (MIN_CONTRIBUTION_CHF.mul(1e18)).div(_rateChfPerEth); confirmationPeriod = _confirmationPeriodDays * 1 days; underwriter = _underwriter; } /** * @dev Set / alter manager / blacklister account. This can be done from owner only * @param _manager address address of the manager to create/alter * @param _active bool flag that shows if the manager account is active */ function setManager(address _manager, bool _active) public onlyOwner { isManager[_manager] = _active; ChangedManager(_manager, _active); } /** * @dev blacklist investor from participating in the crowdsale * @param _investor address address of the investor to disallowed participation */ function blackListInvestor(address _investor, bool _active) public onlyManager { isBlacklisted[_investor] = _active; ChangedInvestorBlacklisting(_investor, _active); } /** * @dev override (not extend! because we only issues tokens after final KYC confirm phase) * core functionality by blacklist check and registration of payment * @param _beneficiary address address of the beneficiary to receive tokens after they have been confirmed */ function buyTokens(address _beneficiary) public payable { require(_beneficiary != address(0)); require(validPurchase()); require(!isBlacklisted[msg.sender]); uint256 weiAmount = msg.value; uint256 tokenAmount; uint256 purchasedTokens = weiAmount.mul(tokenPerWei); uint256 tempTotalTokensPurchased = totalTokensPurchased.add(purchasedTokens); uint256 overflowTokens; uint256 overflowTokens2; // 20% discount bonus amount uint256 tier1BonusTokens; // 10% discount bonus amount uint256 tier2BonusTokens; // tier 1 20% discount - 1st 3 million tokens purchased if (!tier1Reached) { // tx tokens overflowed into next tier 2 - 10% discount - mark tier1Reached! else all tokens are tier 1 discounted if (tempTotalTokensPurchased > DISCOUNT_TOKEN_AMOUNT_T1) { tier1Reached = true; overflowTokens = tempTotalTokensPurchased.sub(DISCOUNT_TOKEN_AMOUNT_T1); tier1BonusTokens = purchasedTokens.sub(overflowTokens); // tx tokens did not overflow into next tier 2 (10% discount) } else { tier1BonusTokens = purchasedTokens; } //apply discount tier1BonusTokens = tier1BonusTokens.mul(10).div(8); tokenAmount = tokenAmount.add(tier1BonusTokens); } // tier 2 10% discount - 2nd 3 million tokens purchased if (tier1Reached && !tier2Reached) { // tx tokens overflowed into next tier 3 - 0% - marked tier2Reached! else all tokens are tier 2 discounted if (tempTotalTokensPurchased > DISCOUNT_TOKEN_AMOUNT_T2) { tier2Reached = true; overflowTokens2 = tempTotalTokensPurchased.sub(DISCOUNT_TOKEN_AMOUNT_T2); tier2BonusTokens = purchasedTokens.sub(overflowTokens2); // tx tokens did not overflow into next tier 3 (tier 3 == no discount) } else { // tokens overflowed from tier1 else this tx started in tier2 if (overflowTokens > 0) { tier2BonusTokens = overflowTokens; } else { tier2BonusTokens = purchasedTokens; } } // apply discount for tier 2 tokens tier2BonusTokens = tier2BonusTokens.mul(10).div(9); tokenAmount = tokenAmount.add(tier2BonusTokens).add(overflowTokens2); } // this triggers when both tier 1 and tier 2 discounted tokens have be filled - but ONLY afterwards, not if the flags got set during the same tx // aka this is tier 3 if (tier2Reached && tier1Reached && tier2BonusTokens == 0) { tokenAmount = purchasedTokens; } /*** Record & update state variables ***/ // Tracks purchased tokens for 2 tiers of discounts totalTokensPurchased = totalTokensPurchased.add(purchasedTokens); // Tracks total tokens pending to be minted - this includes presale tokens tokensToMint = tokensToMint.add(tokenAmount); weiRaised = weiRaised.add(weiAmount); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount); // register payment so that later on it can be confirmed (and tokens issued and Ether paid out) Payment memory newPayment = Payment(msg.sender, _beneficiary, weiAmount, tokenAmount, false, false, false); investments.push(newPayment); } /** * @dev confirms payment * @param _investmentId uint256 uint256 of the investment id to confirm */ function confirmPayment(uint256 _investmentId) public onlyManager onlyConfirmPayment { investments[_investmentId].confirmed = true; ChangedInvestmentConfirmation(_investmentId, investments[_investmentId].investor, true); } /** * @dev confirms payments via a batch method * @param _investmentIds uint256[] array of uint256 of the investment ids to confirm */ function batchConfirmPayments(uint256[] _investmentIds) public onlyManager onlyConfirmPayment { uint256 investmentId; for (uint256 c; c < _investmentIds.length; c = c.add(1)) { investmentId = _investmentIds[c]; // gas optimization confirmPayment(investmentId); } } /** * @dev unconfirms payment made via investment id * @param _investmentId uint256 uint256 of the investment to unconfirm */ function unConfirmPayment(uint256 _investmentId) public onlyManager onlyConfirmPayment { investments[_investmentId].confirmed = false; ChangedInvestmentConfirmation(_investmentId, investments[_investmentId].investor, false); } /** * @dev allows contract owner to mint tokens for presale or non-ETH contributions in batches * @param _toList address[] array of the beneficiaries to receive tokens * @param _tokenList uint256[] array of the token amounts to mint for the corresponding users */ function batchMintTokenDirect(address[] _toList, uint256[] _tokenList) public onlyOwner { require(_toList.length == _tokenList.length); for (uint256 i; i < _toList.length; i = i.add(1)) { mintTokenDirect(_toList[i], _tokenList[i]); } } /** * @dev allows contract owner to mint tokens for presale or non-ETH contributions * @param _to address of the beneficiary to receive tokens * @param _tokens uint256 of the token amount to mint */ function mintTokenDirect(address _to, uint256 _tokens) public onlyOwner { require(tokensToMint.add(_tokens) <= ICO_TOKEN_CAP); tokensToMint = tokensToMint.add(_tokens); // register payment so that later on it can be confirmed (and tokens issued and Ether paid out) Payment memory newPayment = Payment(address(0), _to, 0, _tokens, false, false, false); investments.push(newPayment); TokenPurchase(msg.sender, _to, 0, _tokens); } /** * @dev allows contract owner to mint tokens for ICO enablers respecting the ICO_ENABLERS_CAP (no vesting) * @param _to address for beneficiary * @param _tokens uint256 token amount to mint */ function mintIcoEnablersTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) { require(icoEnablersTokensMinted.add(_tokens) <= ICO_ENABLERS_CAP); token.mint(_to, _tokens); icoEnablersTokensMinted = icoEnablersTokensMinted.add(_tokens); } /** * @dev allows contract owner to mint team tokens per DEVELOPMENT_TEAM_CAP and transfer to the development team's wallet (yes vesting) * @param _to address for beneficiary * @param _tokens uint256 token amount to mint */ function mintDevelopmentTeamTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) { require(developmentTeamTokensMinted.add(_tokens) <= DEVELOPMENT_TEAM_CAP); developmentTeamTokensMinted = developmentTeamTokensMinted.add(_tokens); TokenVesting newVault = new TokenVesting(_to, now, VESTING_CLIFF, VESTING_DURATION, false); vestingWallets.push(address(newVault)); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan token.mint(address(newVault), _tokens); } /** * @dev returns number of elements in the vestinWallets array */ function getVestingWalletLength() public view returns (uint256) { return vestingWallets.length; } /** * @dev set final the confirmation period */ function finalizeConfirmationPeriod() public onlyOwner onlyConfirmPayment { confirmationPeriodOver = true; } /** * @dev settlement of investment made via investment id * @param _investmentId uint256 uint256 being the investment id */ function settleInvestment(uint256 _investmentId) public onlyConfirmationOver { Payment storage p = investments[_investmentId]; // investment should not be settled already (prevent double token issueing or repayment) require(!p.completedSettlement); // investments have to be processed in right order // unless we're at first investment, the previous has needs to have undergone an attempted settlement require(_investmentId == 0 || investments[_investmentId.sub(1)].attemptedSettlement); p.attemptedSettlement = true; // just so that we can see which one we attempted last time and can continue with next investmentIdLastAttemptedToSettle = _investmentId; if (p.confirmed && !capReached) { // if confirmed -> issue tokens, send ETH to wallet and complete settlement // calculate number of tokens to be issued to investor uint256 tokens = p.tokenAmount; // check to see if this purchase sets it over the crowdsale token cap // if so, refund if (tokensMinted.add(tokens) > ICO_TOKEN_CAP) { capReached = true; if (p.weiAmount > 0) { p.investor.send(p.weiAmount); // does not throw (otherwise we'd block all further settlements) } } else { tokensToMint = tokensToMint.sub(tokens); tokensMinted = tokensMinted.add(tokens); // mint tokens for beneficiary token.mint(p.beneficiary, tokens); if (p.weiAmount > 0) { // send Ether to project wallet (throws if wallet throws) wallet.transfer(p.weiAmount); } } p.completedSettlement = true; } else { // if not confirmed -> reimburse ETH or if fiat (presale) investor: do nothing // only complete settlement if investor got their money back // (does not throw (as .transfer would) // otherwise we would block settlement process of all following investments) if (p.investor != address(0) && p.weiAmount > 0) { if (p.investor.send(p.weiAmount)) { p.completedSettlement = true; } } } } /** * @dev allows the batch settlement of investments made * @param _investmentIds uint256[] array of uint256 of investment ids */ function batchSettleInvestments(uint256[] _investmentIds) public { for (uint256 c; c < _investmentIds.length; c = c.add(1)) { settleInvestment(_investmentIds[c]); } } /** * @dev allows contract owner to finalize the ICO, unpause tokens, set treasurer, finish minting, and transfer ownship of the token contract */ function finalize() public onlyUnderwriter onlyConfirmationOver { Pausable(token).unpause(); // this crowdsale also should not be treasurer of the token anymore IcoToken(token).setTreasurer(this, false); // do not allow new owner to mint further tokens MintableToken(token).finishMinting(); // until now the owner of the token is this crowdsale contract // in order for a human owner to make use of the tokens onlyOwner functions // we need to transfer the ownership // in the end the owner of this crowdsale will also be the owner of the token Ownable(token).transferOwnership(owner); } /** * @dev Create new instance of ico token contract */ function createTokenContract() internal returns (MintableToken) { return new IcoToken(); } /** * @dev extend base functionality with min investment amount */ function validPurchase() internal view returns (bool) { // minimal investment: 250 CHF (represented in wei) require (msg.value >= minContributionInWei); return super.validPurchase(); } }
allows contract owner to mint tokens for ICO enablers respecting the ICO_ENABLERS_CAP (no vesting) _to address for beneficiary _tokens uint256 token amount to mint/
function mintIcoEnablersTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) { require(icoEnablersTokensMinted.add(_tokens) <= ICO_ENABLERS_CAP); token.mint(_to, _tokens); icoEnablersTokensMinted = icoEnablersTokensMinted.add(_tokens); }
13,074,889
./full_match/1/0x28883d426dD2eF9EED05AdeAE1CA078D5648114E/sources/localhost/RFETHTOKEN.sol
Decrease the amount of tokens that an owner has allowed to a spender. spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by./
function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 oldValue = _allowedRFETH[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedRFETH[msg.sender][spender] = 0; _allowedRFETH[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedRFETH[msg.sender][spender]); return true; }
9,605,486
pragma solidity 0.4.24; import 'libraries/ContractExists.sol'; import 'libraries/IERC820Registry.sol'; interface ERC820ImplementerInterface { /// @notice Contracts that implement an interferce in behalf of another contract must return true /// @param addr Address that the contract woll implement the interface in behalf of /// @param interfaceHash keccak256 of the name of the interface /// @return ERC820_ACCEPT_MAGIC if the contract can implement the interface represented by /// `ìnterfaceHash` in behalf of `addr` function canImplementInterfaceForAddress(address addr, bytes32 interfaceHash) view external returns(bytes32); } contract ERC820Registry is IERC820Registry { using ContractExists for address; bytes4 constant InvalidID = 0xffffffff; bytes4 constant ERC165ID = 0x01ffc9a7; bytes32 constant ERC820_ACCEPT_MAGIC = keccak256("ERC820_ACCEPT_MAGIC"); address private constant FOUNDATION_820_REGISTRY_ADDRESS = address(0x991a1bcb077599290d7305493c9A630c20f8b798); constructor() public { // This is to confirm we are not on foundation network require(!FOUNDATION_820_REGISTRY_ADDRESS.exists()); } mapping (address => mapping(bytes32 => address)) interfaces; mapping (address => address) managers; mapping (address => mapping(bytes4 => bool)) erc165Cache; modifier canManage(address addr) { require(getManager(addr) == msg.sender); _; } event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed addr, address indexed newManager); /// @notice Query the hash of an interface given a name /// @param interfaceName Name of the interfce function interfaceHash(string interfaceName) public pure returns(bytes32) { return keccak256(abi.encodePacked(interfaceName)); } /// @notice GetManager function getManager(address addr) public view returns(address) { // By default the manager of an address is the same address if (managers[addr] == 0) { return addr; } else { return managers[addr]; } } /// @notice Sets an external `manager` that will be able to call `setInterfaceImplementer()` /// on behalf of the address. /// @param addr Address that you are defining the manager for. /// @param newManager The address of the manager for the `addr` that will replace /// the old one. Set to 0x0 if you want to remove the manager. function setManager(address addr, address newManager) public canManage(addr) { managers[addr] = newManager == addr ? 0 : newManager; emit ManagerChanged(addr, newManager); } /// @notice Query if an address implements an interface and thru which contract /// @param addr Address that is being queried for the implementation of an interface /// @param iHash SHA3 of the name of the interface as a string /// Example `web3.utils.sha3('ERC777Token`')` /// @return The address of the contract that implements a specific interface /// or 0x0 if `addr` does not implement this interface function getInterfaceImplementer(address addr, bytes32 iHash) public returns (address) { if (isERC165Interface(iHash)) { bytes4 i165Hash = bytes4(iHash); return erc165InterfaceSupported(addr, i165Hash) ? addr : 0; } return interfaces[addr][iHash]; } /// @notice Sets the contract that will handle a specific interface; only /// the address itself or a `manager` defined for that address can set it /// @param addr Address that you want to define the interface for /// @param iHash SHA3 of the name of the interface as a string /// For example `web3.utils.sha3('Ierc777')` for the Ierc777 function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public canManage(addr) { require(!isERC165Interface(iHash)); if ((implementer != 0) && (implementer!=msg.sender)) { require(ERC820ImplementerInterface(implementer).canImplementInterfaceForAddress(addr, iHash) == ERC820_ACCEPT_MAGIC); } interfaces[addr][iHash] = implementer; emit InterfaceImplementerSet(addr, iHash, implementer); } /// ERC165 Specific function isERC165Interface(bytes32 iHash) internal pure returns (bool) { return iHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0; } function erc165InterfaceSupported(address _contract, bytes4 _interfaceId) public returns (bool) { if (!erc165Cache[_contract][_interfaceId]) { erc165UpdateCache(_contract, _interfaceId); } return interfaces[_contract][_interfaceId] != 0; } function erc165UpdateCache(address _contract, bytes4 _interfaceId) public { interfaces[_contract][_interfaceId] = erc165InterfaceSupported_NoCache(_contract, _interfaceId) ? _contract : 0; erc165Cache[_contract][_interfaceId] = true; } function erc165InterfaceSupported_NoCache(address _contract, bytes4 _interfaceId) public view returns (bool) { uint256 success; uint256 result; (success, result) = noThrowCall(_contract, ERC165ID); if ((success==0)||(result==0)) { return false; } (success, result) = noThrowCall(_contract, InvalidID); if ((success==0)||(result!=0)) { return false; } (success, result) = noThrowCall(_contract, _interfaceId); if ((success==1)&&(result==1)) { return true; } return false; } function noThrowCall(address _contract, bytes4 _interfaceId) view internal returns (uint256 success, uint256 result) { bytes4 erc165ID = ERC165ID; assembly { let x := mload(0x40) // Find empty storage location using "free memory pointer" mstore(x, erc165ID) // Place signature at begining of empty storage mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature success := staticcall( 30000, // 30k gas _contract, // To addr x, // Inputs are stored at location x 0x08, // Inputs are 8 bytes long x, // Store output over input (saves space) 0x20) // Outputs are 32 bytes long result := mload(x) // Load the result } } }
Query the hash of an interface given a name interfaceName Name of the interfce
function interfaceHash(string interfaceName) public pure returns(bytes32) { return keccak256(abi.encodePacked(interfaceName)); }
13,016,178
./full_match/1/0x14b5Ceaf1957df0BC55c55A865470Ddd245857b5/sources/PAYMENTS_LOT22.sol
Completely Resets Splitter and withdrawls any remaining ETH. NOTE: Any remaining ERC20 tokens will need to be manually withdrawn./remove the oldset the new
function resetSplit(address[] memory payees, uint256[] memory shares_) public onlyOwner { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < _payees.length; i++) { delete _shares[_payees[i]]; } delete _payees; _totalShares = 0; for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } if (address(this).balance != 0){ _totalReleased = 0; emergencyWithdraw(); } }
8,286,357
pragma solidity ^0.4.13; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract 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; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract SealTokenSale is Pausable { using SafeMath for uint256; /** * @dev Supporter struct to allow tracking supporters KYC status and referrer address */ struct Supporter { bool hasKYC; address referrerAddress; } /** * @dev External Supporter struct to allow tracking reserved amounts by supporter */ struct ExternalSupporter { uint256 reservedAmount; } /** * @dev Token Sale States */ enum TokenSaleState {Private, Pre, Main, Finished} // Variables mapping(address => Supporter) public supportersMap; // Mapping with all the Token Sale participants (Private excluded) mapping(address => ExternalSupporter) public externalSupportersMap; // Mapping with external supporters SealToken public token; // ERC20 Token contract address address public vaultWallet; // Wallet address to which ETH and Company Reserve Tokens get forwarded address public airdropWallet; // Wallet address to which Unsold Tokens get forwarded address public kycWallet; // Wallet address for the KYC server uint256 public tokensSold; // How many tokens have been sold uint256 public tokensReserved; // How many tokens have been reserved uint256 public maxTxGasPrice; // Maximum transaction gas price allowed for fair-chance transactions TokenSaleState public currentState; // current Sale state uint256 public constant ONE_MILLION = 10 ** 6; // One million for token cap calculation reference uint256 public constant PRE_SALE_TOKEN_CAP = 384 * ONE_MILLION * 10 ** 18; // Maximum amount that can be sold during the Pre Sale period uint256 public constant TOKEN_SALE_CAP = 492 * ONE_MILLION * 10 ** 18; // Maximum amount of tokens that can be sold by this contract uint256 public constant TOTAL_TOKENS_SUPPLY = 1200 * ONE_MILLION * 10 ** 18; // Total supply that will be minted uint256 public constant MIN_ETHER = 0.1 ether; // Minimum ETH Contribution allowed during the crowd sale /* Minimum PreSale Contributions in Ether */ uint256 public constant PRE_SALE_MIN_ETHER = 1 ether; // Minimum to get 10% Bonus Tokens uint256 public constant PRE_SALE_15_BONUS_MIN = 60 ether; // Minimum to get 15% Bonus Tokens uint256 public constant PRE_SALE_20_BONUS_MIN = 300 ether; // Minimum to get 20% Bonus Tokens uint256 public constant PRE_SALE_30_BONUS_MIN = 1200 ether; // Minimum to get 30% Bonus Tokens /* Rate */ uint256 public tokenBaseRate; // Base rate uint256 public referrerBonusRate; // Referrer Bonus Rate with 2 decimals (250 for 2.5% bonus for example) uint256 public referredBonusRate; // Referred Bonus Rate with 2 decimals (250 for 2.5% bonus for example) /** * @dev Modifier to only allow Owner or KYC Wallet to execute a function */ modifier onlyOwnerOrKYCWallet() { require(msg.sender == owner || msg.sender == kycWallet); _; } /** * Event for token purchase logging * @param purchaser The wallet address that bought the tokens * @param value How many Weis were paid for the purchase * @param amount The amount of tokens purchased */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); /** * Event for token reservation * @param wallet The beneficiary wallet address * @param amount The amount of tokens */ event TokenReservation(address indexed wallet, uint256 amount); /** * Event for token reservation confirmation * @param wallet The beneficiary wallet address * @param amount The amount of tokens */ event TokenReservationConfirmation(address indexed wallet, uint256 amount); /** * Event for token reservation cancellation * @param wallet The beneficiary wallet address * @param amount The amount of tokens */ event TokenReservationCancellation(address indexed wallet, uint256 amount); /** * Event for kyc status change logging * @param user User address * @param isApproved KYC approval state */ event KYC(address indexed user, bool isApproved); /** * Event for referrer set * @param user User address * @param referrerAddress Referrer address */ event ReferrerSet(address indexed user, address indexed referrerAddress); /** * Event for referral bonus incomplete * @param userAddress User address * @param missingAmount Missing Amount */ event ReferralBonusIncomplete(address indexed userAddress, uint256 missingAmount); /** * Event for referral bonus minted * @param userAddress User address * @param amount Amount minted */ event ReferralBonusMinted(address indexed userAddress, uint256 amount); /** * Constructor * @param _vaultWallet Vault address * @param _airdropWallet Airdrop wallet address * @param _kycWallet KYC address * @param _tokenBaseRate Token Base rate (Tokens/ETH) * @param _referrerBonusRate Referrer Bonus rate (2 decimals, ex 250 for 2.5%) * @param _referredBonusRate Referred Bonus rate (2 decimals, ex 250 for 2.5%) * @param _maxTxGasPrice Maximum gas price allowed when buying tokens */ function SealTokenSale( address _vaultWallet, address _airdropWallet, address _kycWallet, uint256 _tokenBaseRate, uint256 _referrerBonusRate, uint256 _referredBonusRate, uint256 _maxTxGasPrice ) public { require(_vaultWallet != address(0)); require(_airdropWallet != address(0)); require(_kycWallet != address(0)); require(_tokenBaseRate > 0); require(_referrerBonusRate > 0); require(_referredBonusRate > 0); require(_maxTxGasPrice > 0); vaultWallet = _vaultWallet; airdropWallet = _airdropWallet; kycWallet = _kycWallet; tokenBaseRate = _tokenBaseRate; referrerBonusRate = _referrerBonusRate; referredBonusRate = _referredBonusRate; maxTxGasPrice = _maxTxGasPrice; tokensSold = 0; tokensReserved = 0; token = new SealToken(); // init sale state; currentState = TokenSaleState.Private; } /* fallback function can be used to buy tokens */ function() public payable { buyTokens(); } /* low level token purchase function */ function buyTokens() public payable whenNotPaused { // Do not allow if gasprice is bigger than the maximum // This is for fair-chance for all contributors, so no one can // set a too-high transaction price and be able to buy earlier require(tx.gasprice <= maxTxGasPrice); // make sure we're in pre or main sale period require(isPublicTokenSaleRunning()); // check if KYC ok require(userHasKYC(msg.sender)); // check user is sending enough Wei for the stage's rules require(aboveMinimumPurchase()); address sender = msg.sender; uint256 weiAmountSent = msg.value; // calculate token amount uint256 bonusMultiplier = getBonusMultiplier(weiAmountSent); uint256 newTokens = weiAmountSent.mul(tokenBaseRate).mul(bonusMultiplier).div(100); // check totals and mint the tokens checkTotalsAndMintTokens(sender, newTokens, false); // Log Event TokenPurchase(sender, weiAmountSent, newTokens); // forward the funds to the vault wallet vaultWallet.transfer(msg.value); } /** * @dev Reserve Tokens * @param _wallet Destination Address * @param _amount Amount of tokens */ function reserveTokens(address _wallet, uint256 _amount) public onlyOwner { // check amount positive require(_amount > 0); // check destination address not null require(_wallet != address(0)); // make sure that we're in private sale or presale require(isPrivateSaleRunning() || isPreSaleRunning()); // check cap uint256 totalTokensReserved = tokensReserved.add(_amount); require(tokensSold + totalTokensReserved <= PRE_SALE_TOKEN_CAP); // update total reserved tokensReserved = totalTokensReserved; // save user reservation externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.add(_amount); // Log Event TokenReservation(_wallet, _amount); } /** * @dev Confirm Reserved Tokens * @param _wallet Destination Address * @param _amount Amount of tokens */ function confirmReservedTokens(address _wallet, uint256 _amount) public onlyOwner { // check amount positive require(_amount > 0); // check destination address not null require(_wallet != address(0)); // make sure the sale hasn't ended yet require(!hasEnded()); // check amount not more than reserved require(_amount <= externalSupportersMap[_wallet].reservedAmount); // check totals and mint the tokens checkTotalsAndMintTokens(_wallet, _amount, true); // Log Event TokenReservationConfirmation(_wallet, _amount); } /** * @dev Cancel Reserved Tokens * @param _wallet Destination Address * @param _amount Amount of tokens */ function cancelReservedTokens(address _wallet, uint256 _amount) public onlyOwner { // check amount positive require(_amount > 0); // check destination address not null require(_wallet != address(0)); // make sure the sale hasn't ended yet require(!hasEnded()); // check amount not more than reserved require(_amount <= externalSupportersMap[_wallet].reservedAmount); // update total reserved tokensReserved = tokensReserved.sub(_amount); // update user reservation externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.sub(_amount); // Log Event TokenReservationCancellation(_wallet, _amount); } /** * @dev Check totals and Mint tokens * @param _wallet Destination Address * @param _amount Amount of tokens */ function checkTotalsAndMintTokens(address _wallet, uint256 _amount, bool _fromReservation) private { // check that we have not yet reached the cap uint256 totalTokensSold = tokensSold.add(_amount); uint256 totalTokensReserved = tokensReserved; if (_fromReservation) { totalTokensReserved = totalTokensReserved.sub(_amount); } if (isMainSaleRunning()) { require(totalTokensSold + totalTokensReserved <= TOKEN_SALE_CAP); } else { require(totalTokensSold + totalTokensReserved <= PRE_SALE_TOKEN_CAP); } // update contract state tokensSold = totalTokensSold; if (_fromReservation) { externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.sub(_amount); tokensReserved = totalTokensReserved; } // mint the tokens token.mint(_wallet, _amount); address userReferrer = getUserReferrer(_wallet); if (userReferrer != address(0)) { // Mint Referrer bonus mintReferralShare(_amount, userReferrer, referrerBonusRate); // Mint Referred bonus mintReferralShare(_amount, _wallet, referredBonusRate); } } /** * @dev Mint Referral Share * @param _amount Amount of tokens * @param _userAddress User Address * @param _bonusRate Bonus rate (2 decimals) */ function mintReferralShare(uint256 _amount, address _userAddress, uint256 _bonusRate) private { // calculate max tokens available uint256 currentCap; if (isMainSaleRunning()) { currentCap = TOKEN_SALE_CAP; } else { currentCap = PRE_SALE_TOKEN_CAP; } uint256 maxTokensAvailable = currentCap - tokensSold - tokensReserved; // check if we have enough tokens uint256 fullShare = _amount.mul(_bonusRate).div(10000); if (fullShare <= maxTokensAvailable) { // mint the tokens token.mint(_userAddress, fullShare); // update state tokensSold = tokensSold.add(fullShare); // log event ReferralBonusMinted(_userAddress, fullShare); } else { // mint the available tokens token.mint(_userAddress, maxTokensAvailable); // update state tokensSold = tokensSold.add(maxTokensAvailable); // log events ReferralBonusMinted(_userAddress, maxTokensAvailable); ReferralBonusIncomplete(_userAddress, fullShare - maxTokensAvailable); } } /** * @dev Start Presale */ function startPreSale() public onlyOwner { // make sure we're in the private sale state require(currentState == TokenSaleState.Private); // move to presale currentState = TokenSaleState.Pre; } /** * @dev Go back to private sale */ function goBackToPrivateSale() public onlyOwner { // make sure we're in the pre sale require(currentState == TokenSaleState.Pre); // go back to private currentState = TokenSaleState.Private; } /** * @dev Start Main sale */ function startMainSale() public onlyOwner { // make sure we're in the presale state require(currentState == TokenSaleState.Pre); // move to main sale currentState = TokenSaleState.Main; } /** * @dev Go back to Presale */ function goBackToPreSale() public onlyOwner { // make sure we're in the main sale require(currentState == TokenSaleState.Main); // go back to presale currentState = TokenSaleState.Pre; } /** * @dev Ends the operation of the contract */ function finishContract() public onlyOwner { // make sure we're in the main sale require(currentState == TokenSaleState.Main); // make sure there are no pending reservations require(tokensReserved == 0); // mark sale as finished currentState = TokenSaleState.Finished; // send the unsold tokens to the airdrop wallet uint256 unsoldTokens = TOKEN_SALE_CAP.sub(tokensSold); token.mint(airdropWallet, unsoldTokens); // send the company reserve tokens to the vault wallet uint256 notForSaleTokens = TOTAL_TOKENS_SUPPLY.sub(TOKEN_SALE_CAP); token.mint(vaultWallet, notForSaleTokens); // finish the minting of the token, so that transfers are allowed token.finishMinting(); // transfer ownership of the token contract to the owner, // so it isn't locked to be a child of the crowd sale contract token.transferOwnership(owner); } /** * @dev Updates the maximum allowed gas price that can be used when calling buyTokens() * @param _newMaxTxGasPrice The new maximum gas price */ function updateMaxTxGasPrice(uint256 _newMaxTxGasPrice) public onlyOwner { require(_newMaxTxGasPrice > 0); maxTxGasPrice = _newMaxTxGasPrice; } /** * @dev Updates the token baserate * @param _tokenBaseRate The new token baserate in tokens/eth */ function updateTokenBaseRate(uint256 _tokenBaseRate) public onlyOwner { require(_tokenBaseRate > 0); tokenBaseRate = _tokenBaseRate; } /** * @dev Updates the Vault Wallet address * @param _vaultWallet The new vault wallet */ function updateVaultWallet(address _vaultWallet) public onlyOwner { require(_vaultWallet != address(0)); vaultWallet = _vaultWallet; } /** * @dev Updates the KYC Wallet address * @param _kycWallet The new kyc wallet */ function updateKYCWallet(address _kycWallet) public onlyOwner { require(_kycWallet != address(0)); kycWallet = _kycWallet; } /** * @dev Approve user's KYC * @param _user User Address */ function approveUserKYC(address _user) onlyOwnerOrKYCWallet public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = true; KYC(_user, true); } /** * @dev Disapprove user's KYC * @param _user User Address */ function disapproveUserKYC(address _user) onlyOwnerOrKYCWallet public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = false; KYC(_user, false); } /** * @dev Approve user's KYC and sets referrer * @param _user User Address * @param _referrerAddress Referrer Address */ function approveUserKYCAndSetReferrer(address _user, address _referrerAddress) onlyOwnerOrKYCWallet public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = true; sup.referrerAddress = _referrerAddress; // log events KYC(_user, true); ReferrerSet(_user, _referrerAddress); } /** * @dev check if private sale is running */ function isPrivateSaleRunning() public view returns (bool) { return (currentState == TokenSaleState.Private); } /** * @dev check if pre sale or main sale are running */ function isPublicTokenSaleRunning() public view returns (bool) { return (isPreSaleRunning() || isMainSaleRunning()); } /** * @dev check if pre sale is running */ function isPreSaleRunning() public view returns (bool) { return (currentState == TokenSaleState.Pre); } /** * @dev check if main sale is running */ function isMainSaleRunning() public view returns (bool) { return (currentState == TokenSaleState.Main); } /** * @dev check if sale has ended */ function hasEnded() public view returns (bool) { return (currentState == TokenSaleState.Finished); } /** * @dev Check if user has passed KYC * @param _user User Address */ function userHasKYC(address _user) public view returns (bool) { return supportersMap[_user].hasKYC; } /** * @dev Get User's referrer address * @param _user User Address */ function getUserReferrer(address _user) public view returns (address) { return supportersMap[_user].referrerAddress; } /** * @dev Get User's reserved amount * @param _user User Address */ function getReservedAmount(address _user) public view returns (uint256) { return externalSupportersMap[_user].reservedAmount; } /** * @dev Returns the bonus multiplier to calculate the purchase rate * @param _weiAmount Purchase amount */ function getBonusMultiplier(uint256 _weiAmount) internal view returns (uint256) { if (isMainSaleRunning()) { return 100; } else if (isPreSaleRunning()) { if (_weiAmount >= PRE_SALE_30_BONUS_MIN) { // 30% bonus return 130; } else if (_weiAmount >= PRE_SALE_20_BONUS_MIN) { // 20% bonus return 120; } else if (_weiAmount >= PRE_SALE_15_BONUS_MIN) { // 15% bonus return 115; } else if (_weiAmount >= PRE_SALE_MIN_ETHER) { // 10% bonus return 110; } else { // Safeguard but this should never happen as aboveMinimumPurchase checks the minimum revert(); } } } /** * @dev Check if the user is buying above the required minimum */ function aboveMinimumPurchase() internal view returns (bool) { if (isMainSaleRunning()) { return msg.value >= MIN_ETHER; } else if (isPreSaleRunning()) { return msg.value >= PRE_SALE_MIN_ETHER; } else { return false; } } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract SealToken is MintableToken { // Constants string public constant name = "SealToken"; string public constant symbol = "SEAL"; uint8 public constant decimals = 18; /** * @dev Modifier to only allow transfers after the minting has been done */ modifier onlyWhenTransferEnabled() { require(mintingFinished); _; } modifier validDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); _; } function SealToken() public { } function transferFrom(address _from, address _to, uint256 _value) public onlyWhenTransferEnabled validDestination(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public onlyWhenTransferEnabled returns (bool) { return super.approve(_spender, _value); } function increaseApproval (address _spender, uint _addedValue) public onlyWhenTransferEnabled returns (bool) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval (address _spender, uint _subtractedValue) public onlyWhenTransferEnabled returns (bool) { return super.decreaseApproval(_spender, _subtractedValue); } function transfer(address _to, uint256 _value) public onlyWhenTransferEnabled validDestination(_to) returns (bool) { return super.transfer(_to, _value); } }
Start Presale/ make sure we're in the private sale state move to presale
function startPreSale() public onlyOwner { require(currentState == TokenSaleState.Private); currentState = TokenSaleState.Pre; }
5,841,250
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.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 = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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/finance/PaymentSplitter.sol // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (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); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/E_LIGHTNING.sol pragma solidity ^0.8.7; /// @title The first company in the world has developed the blockchain electric /// @author LINAEL.ETH contract E_LIGHTNING is ERC721Enumerable, PaymentSplitter, Ownable, ReentrancyGuard { //To increment the id of the NFTs using Counters for Counters.Counter; //To concatenate the URL of an NFT using Strings for uint256; //To check the addresses in the whitelist bytes32 public merkleRoot; //Id of the next NFT to mint Counters.Counter private _nftIdCounter; //Number of NFTs in the collection uint public constant MAX_SUPPLY = 7777; //Maximum number of NFTs an address can mint uint public max_mint_allowed = 10; //Price of one NFT in presale uint public pricePresale = 0.08 ether; //Price of one NFT in sale uint public priceSale = 0.10 ether; //URI of the NFTs when revealed string public baseURI; //URI of the NFTs when not revealed string public notRevealedURI; //The extension of the file containing the Metadatas of the NFTs string public baseExtension = ".json"; //Are the NFTs revealed yet ? bool public revealed = false; //Is the contract paused ? bool public paused = false; //The different stages of selling the collection enum Steps { Before, Presale, Sale, SoldOut, Reveal } Steps public sellingStep; //Owner of the smart contract address private _owner; //Keep a track of the number of tokens per address mapping(address => uint) nftsPerWallet; //Addresses of all the members of the team address[] private _team = [ 0x5680Db41b34323caF237064ce77dbd77E0542Ffa ]; //Shares of all the members of the team uint[] private _teamShares = [ 100 ]; //Constructor of the collection constructor(string memory _theBaseURI, string memory _notRevealedURI, bytes32 _merkleRoot) ERC721("E-LIGHTNING", "E-LIGHTNING") PaymentSplitter(_team, _teamShares) { _nftIdCounter.increment(); transferOwnership(msg.sender); sellingStep = Steps.Before; baseURI = _theBaseURI; notRevealedURI = _notRevealedURI; merkleRoot = _merkleRoot; } /** * @notice Edit the Merkle Root * * @param _newMerkleRoot The new Merkle Root **/ function changeMerkleRoot(bytes32 _newMerkleRoot) external onlyOwner { merkleRoot = _newMerkleRoot; } /** * @notice Set pause to true or false * * @param _paused True or false if you want the contract to be paused or not **/ function setPaused(bool _paused) external onlyOwner { paused = _paused; } /** * @notice Change the number of NFTs that an address can mint * * @param _maxMintAllowed The number of NFTs that an address can mint **/ function changeMaxMintAllowed(uint _maxMintAllowed) external onlyOwner { max_mint_allowed = _maxMintAllowed; } /** * @notice Change the price of one NFT for the presale * * @param _pricePresale The new price of one NFT for the presale **/ function changePricePresale(uint _pricePresale) external onlyOwner { pricePresale = _pricePresale; } /** * @notice Change the price of one NFT for the sale * * @param _priceSale The new price of one NFT for the sale **/ function changePriceSale(uint _priceSale) external onlyOwner { priceSale = _priceSale; } /** * @notice Change the base URI * * @param _newBaseURI The new base URI **/ function setBaseUri(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } /** * @notice Change the not revealed URI * * @param _notRevealedURI The new not revealed URI **/ function setNotRevealURI(string memory _notRevealedURI) external onlyOwner { notRevealedURI = _notRevealedURI; } /** * @notice Allows to set the revealed variable to true **/ function reveal() external onlyOwner{ revealed = true; } /** * @notice Return URI of the NFTs when revealed * * @return The URI of the NFTs when revealed **/ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @notice Allows to change the base extension of the metadatas files * * @param _baseExtension the new extension of the metadatas files **/ function setBaseExtension(string memory _baseExtension) external onlyOwner { baseExtension = _baseExtension; } /** * @notice Allows to change the sellinStep to Presale **/ function setUpPresale() external onlyOwner { sellingStep = Steps.Presale; } /** * @notice Allows to change the sellinStep to Sale **/ function setUpSale() external onlyOwner { require(sellingStep == Steps.Presale, "First the presale, then the sale."); sellingStep = Steps.Sale; } /** * @notice Allows to mint one NFT if whitelisted * * @param _account The account of the user minting the NFT * @param _proof The Merkle Proof **/ function presaleMint(address _account, bytes32[] calldata _proof) external payable nonReentrant { //Are we in Presale ? require(sellingStep == Steps.Presale, "Presale has not started yet."); //Did this account already mint an NFT ? require(nftsPerWallet[_account] < 1, "You can only get 10 NFT on the Presale"); //Is this user on the whitelist ? require(isWhiteListed(_account, _proof), "Not on the whitelist"); //Get the price of one NFT during the Presale uint price = pricePresale; //Did the user send enought Ethers ? require(msg.value >= price, "Not enought funds."); //Increment the number of NFTs this user minted nftsPerWallet[_account]++; //Mint the user NFT _safeMint(_account, _nftIdCounter.current()); //Increment the Id of the next NFT to mint _nftIdCounter.increment(); } /** * @notice Allows to mint NFTs * * @param _ammount The ammount of NFTs the user wants to mint **/ function saleMint(uint256 _ammount) external payable nonReentrant { //Get the number of NFT sold uint numberNftSold = totalSupply(); //Get the price of one NFT in Sale uint price = priceSale; //If everything has been bought require(sellingStep != Steps.SoldOut, "Sorry, no NFTs left."); //If Sale didn't start yet require(sellingStep == Steps.Sale, "Sorry, sale has not started yet."); //Did the user then enought Ethers to buy ammount NFTs ? require(msg.value >= price * _ammount, "Not enought funds."); //The user can only mint max 3 NFTs require(_ammount <= max_mint_allowed, "You can't mint more than 3 tokens"); //If the user try to mint any non-existent token require(numberNftSold + _ammount <= MAX_SUPPLY, "Sale is almost done and we don't have enought NFTs left."); //Add the ammount of NFTs minted by the user to the total he minted nftsPerWallet[msg.sender] += _ammount; //If this account minted the last NFTs available if(numberNftSold + _ammount == MAX_SUPPLY) { sellingStep = Steps.SoldOut; } //Minting all the account NFTs for(uint i = 1 ; i <= _ammount ; i++) { _safeMint(msg.sender, numberNftSold + i); } } /** * @notice Allows to gift one NFT to an address * * @param _account The account of the happy new owner of one NFT **/ function gift(address _account) external onlyOwner { uint supply = totalSupply(); require(supply + 1 <= MAX_SUPPLY, "Sold out"); _safeMint(_account, supply + 1); } /** * @notice Return true or false if the account is whitelisted or not * * @param account The account of the user * @param proof The Merkle Proof * * @return true or false if the account is whitelisted or not **/ function isWhiteListed(address account, bytes32[] calldata proof) internal view returns(bool) { return _verify(_leaf(account), proof); } /** * @notice Return the account hashed * * @param account The account to hash * * @return The account hashed **/ function _leaf(address account) internal pure returns(bytes32) { return keccak256(abi.encodePacked(account)); } /** * @notice Returns true if a leaf can be proved to be a part of a Merkle tree defined by root * * @param leaf The leaf * @param proof The Merkle Proof * * @return True if a leaf can be provded to be a part of a Merkle tree defined by root **/ function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns(bool) { return MerkleProof.verify(proof, merkleRoot, leaf); } /** * @notice Allows to get the complete URI of a specific NFT by his ID * * @param _nftId The id of the NFT * * @return The token URI of the NFT which has _nftId Id **/ function tokenURI(uint _nftId) public view override(ERC721) returns (string memory) { require(_exists(_nftId), "This NFT doesn't exist."); if(revealed == false) { return notRevealedURI; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _nftId.toString(), baseExtension)) : ""; } }
Change the base URI _newBaseURI The new base URI/
function setBaseUri(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; }
270,073
//Address: 0x0a630de26e5b41eaef08741e74da4018a6c2e14c //Contract name: dgame //Balance: 0.00001 Ether //Verification Date: 6/1/2017 //Transacion Count: 214 // CODE STARTS HERE pragma solidity ^0.4.10; /* * This is an example gambling contract that works without any ABI interface. * The entire game logic is invoked by calling the fallback function which * is triggered, e.g. upon receiving a transaction at the contract address * without any data sent along. The contract is attackable in a number of ways: * - as soon as someone paid in Ether and starts the game, register with a * large number of addresses to spam the player list and most likely win. * - blockhash as source of entropy is attackable by miners * - probably further exploits * This only serves as a minimalistic example of how to gamble on Ethereum * Author: S.C. Buergel for Validity Labs AG */ contract dgame { uint public registerDuration; uint public endRegisterTime; uint public gameNumber; uint public numPlayers; mapping(uint => mapping(uint => address)) public players; mapping(uint => mapping(address => bool)) public registered; event StartedGame(address initiator, uint regTimeEnd, uint amountSent, uint gameNumber); event RegisteredPlayer(address player, uint gameNumber); event FoundWinner(address player, uint gameNumber); // constructor sets default registration duration to 5min function dgame() { registerDuration = 600; } // fallback function is used for entire game logic function() payable { // status idle: start new game and transition to status ongoing if (endRegisterTime == 0) { endRegisterTime = now + registerDuration; if (msg.value == 0) throw; // prevent a new game to be started with empty pot StartedGame(msg.sender, endRegisterTime, msg.value, gameNumber); } else if (now > endRegisterTime && numPlayers > 0) { // status completed: find winner and transition to status idle uint winner = uint(block.blockhash(block.number - 1)) % numPlayers; // find index of winner (take blockhash as source of entropy -> exploitable!) uint currentGamenumber = gameNumber; FoundWinner(players[currentGamenumber][winner], currentGamenumber); endRegisterTime = 0; numPlayers = 0; gameNumber++; // pay winner all Ether that we have // ignore if winner rejects prize // in that case Ether will be added to prize of the next game players[currentGamenumber][winner].send(this.balance); } else { // status ongoing: register player if (registered[gameNumber][msg.sender]) throw; // prevent same player to register twice with same address registered[gameNumber][msg.sender] = true; players[gameNumber][numPlayers] = (msg.sender); numPlayers++; RegisteredPlayer(msg.sender, gameNumber); } } }
fallback function is used for entire game logic status idle: start new game and transition to status ongoing status completed: find winner and transition to status idle pay winner all Ether that we have ignore if winner rejects prize in that case Ether will be added to prize of the next game status ongoing: register player
function() payable { if (endRegisterTime == 0) { endRegisterTime = now + registerDuration; if (msg.value == 0) StartedGame(msg.sender, endRegisterTime, msg.value, gameNumber); uint currentGamenumber = gameNumber; FoundWinner(players[currentGamenumber][winner], currentGamenumber); endRegisterTime = 0; numPlayers = 0; gameNumber++; players[currentGamenumber][winner].send(this.balance); if (registered[gameNumber][msg.sender]) registered[gameNumber][msg.sender] = true; players[gameNumber][numPlayers] = (msg.sender); numPlayers++; RegisteredPlayer(msg.sender, gameNumber); } }
2,491,908
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/ICozy.sol"; import "./interfaces/ICozyInvest.sol"; import "./lib/CozyInvestHelpers.sol"; import "@openzeppelin/contracts/utils/Address.sol"; interface IRibbon { function depositETH() external payable; function initiateWithdraw(uint256 numShares) external; function withdrawInstantly(uint256 amount) external; function completeWithdraw() external; } /** * @notice On-chain scripts for borrowing from Cozy and using the borrowed funds to * supply to curve and then deposit into Ribbon * @dev This contract is intended to be used by delegatecalling to it from a DSProxy */ contract CozyInvestRibbon is CozyInvestHelpers, ICozyInvest2 { using Address for address payable; using SafeERC20 for IERC20; /// @notice The unprotected money market we borrow from / repay to address public immutable moneyMarket; /// @notice The protection market we borrow from / repay to address public immutable protectionMarket; /// @notice Maximillion contract for repaying ETH debt IMaximillion public constant maximillion = IMaximillion(0xf859A1AD94BcF445A406B892eF0d3082f4174088); /// @notice Ribbon ETH theta vault contract address address public immutable ribbon = 0x25751853Eab4D0eB3652B5eB6ecB102A2789644B; constructor(address _moneyMarket, address _protectionMarket) { moneyMarket = _moneyMarket; protectionMarket = _protectionMarket; } /** * @notice Invest method for borrowing ETH and depositing it to Ribbon * @param _market Address of the market to borrow from * @param _borrowAmount Amount of underlying to borrow and invest */ function invest(address _market, uint256 _borrowAmount) external { require((_market == address(moneyMarket) || _market == address(protectionMarket)), "Invalid borrow market"); require(ICozyToken(_market).borrow(_borrowAmount) == 0, "Borrow failed"); IRibbon _ribbon = IRibbon(ribbon); _ribbon.depositETH{value: _borrowAmount}(); } /** * @notice Instantly withdraws funds from Ribbon that are available to withdraw. * @param _market Address of the market to repay debt to * @param _recipient Address where any leftover funds should be transferred * @param _withdrawAmount Amount of Curve receipt tokens to redeem */ function withdrawInstantly( address _market, address _recipient, uint256 _withdrawAmount ) external payable { // 1. Borrow underlying from cozy require((_market == address(moneyMarket) || _market == address(protectionMarket)), "Invalid borrow market"); // 2. Withdraws instantly from ribbon IRibbon _ribbon = IRibbon(ribbon); _ribbon.withdrawInstantly(_withdrawAmount); // 3. Pay back as much of the borrow as possible, excess ETH is refunded to `recipient` maximillion.repayBehalfExplicit{value: address(this).balance}(address(this), ICozyEther(_market)); // 4. Transfer any remaining funds to the user payable(_recipient).sendValue(address(this).balance); } /** * @notice Initiates two-step divest method from Ribbon. completeWithdraw() must be called later once the next round has started. * @param _numShares Number of shares to divest */ function divest(uint256 _numShares) external { IRibbon _ribbon = IRibbon(ribbon); _ribbon.initiateWithdraw(_numShares); } /** * @notice Instantly withdraws funds from Ribbon that are available to withdraw. divest() must be called beforehand. * @param _market Address of the market to repay debt to * @param _recipient Address where any leftover funds should be transferred */ function completeWithdraw(address _market, address _recipient) external { require((_market == address(moneyMarket) || _market == address(protectionMarket)), "Invalid borrow market"); // 1. Completes withdraw from Ribbon IRibbon _ribbon = IRibbon(ribbon); _ribbon.completeWithdraw(); // 2. Pay back as much of the borrow as possible, excess ETH is refunded to `recipient` maximillion.repayBehalfExplicit{value: address(this).balance}(address(this), ICozyEther(_market)); // 3. Transfer any remaining funds to the user payable(_recipient).sendValue(address(this).balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; /** * @dev Interfaces for Cozy contracts */ interface ICozyShared { function underlying() external view returns (address); function borrow(uint256 borrowAmount) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); } interface ICozyToken is ICozyShared { function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); } interface ICozyEther is ICozyShared { function repayBorrowBehalf(address borrower) external payable; } interface IMaximillion { function repayBehalfExplicit(address borrower, ICozyEther market) external payable; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; /** * @notice Interfaces for developing on-chain scripts for borrowing from the Cozy markets then supplying to * investment opportunities in a single transaction * @dev Contract developed from this interface are intended to be used by delegatecalling to it from a DSProxy * @dev For interactions with the Cozy Protocol, ensure the return value is zero and revert otherwise. See * the Cozy Protocol documentation on error codes for more info */ interface ICozyInvest1 { function invest( address _ethMarket, uint256 _borrowAmount, uint256 _minAmountOut ) external payable; } interface ICozyInvest2 { function invest(address _market, uint256 _borrowAmount) external; } interface ICozyInvest3 { // NOTE: Same signature as ICozyInvest1, but without the payable modifier function invest( address _ethMarket, uint256 _borrowAmount, uint256 _minAmountOut ) external; } interface ICozyInvest4 { function invest( address _market, uint256 _borrowAmount, uint256 _minToMint, uint256 _deadline ) external; } interface ICozyInvest5 { function invest( address _ethMarket, uint256 _borrowAmount, uint256 _minAmountOut ) external; } interface ICozyDivest1 { function divest( address _marketAddress, address _recipient, uint256 _redeemAmount, uint256 _curveMinAmountOut ) external payable; } interface ICozyDivest2 { // NOTE: Same signature as above (except for the payable part), but with different meanings of each input function divest( address _marketAddress, address _recipient, uint256 _withdrawAmount, uint256 _excessTokens ) external; } interface ICozyDivest3 { function divest( address _market, address _recipient, uint256 _yearnRedeemAmount, uint256 _curveMinAmountOut, uint256 _excessTokens ) external; } interface ICozyDivest4 { function divest( address _marketAddress, address _recipient, uint256 _withdrawAmount, uint256 _minWithdrawAmount, uint256 _deadline ) external payable; } interface ICozyDivest5 { function divest( address _marketAddress, address _recipient, uint256 _withdrawAmount, uint256 _excessTokens, uint256 _curveMinAmountOut ) external; } interface ICozyDivest6 { function divest( address _marketAddress, address _recipient, uint256 _withdrawAmount ) external payable; } interface ICozyReward { function claimRewards(address _recipient) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import "../interfaces/ICozy.sol"; import "./TransferHelper.sol"; abstract contract CozyInvestHelpers { /** * @notice Repays as much token debt as possible * @param _market Market to repay * @param _underlying That market's underlying token (can be obtained by a call, but passing it in saves gas) * @param _excessTokens Quantity to transfer from the caller into this address to ensure * the borrow can be repaid in full. Only required if you want to repay the full borrow amount and the * amount obtained from withdrawing from the invest opportunity will not cover the full debt. A value of zero * will not attempt to transfer tokens from the caller, and the transfer will not be attempted if it's not required */ function executeMaxRepay( address _market, address _underlying, uint256 _excessTokens ) internal { // Pay back as much of the borrow as possible, excess is refunded to `recipient` uint256 _borrowBalance = ICozyToken(_market).borrowBalanceCurrent(address(this)); uint256 _initialBalance = IERC20(_underlying).balanceOf(address(this)); if (_initialBalance < _borrowBalance && _excessTokens > 0) { TransferHelper.safeTransferFrom(_underlying, msg.sender, address(this), _excessTokens); } uint256 _balance = _initialBalance + _excessTokens; // this contract's current balance uint256 _repayAmount = _balance >= _borrowBalance ? type(uint256).max : _balance; TransferHelper.safeApprove(_underlying, address(_market), _repayAmount); require(ICozyToken(_market).repayBorrow(_repayAmount) == 0, "Repay failed"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: UNLICENSED pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Based on https://github.com/Uniswap/v3-periphery/blob/80f26c86c57b8a5e4b913f42844d4c8bd274d058/contracts/libraries/TransferHelper.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))), "Transfer from failed"); } /** * @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))), "Transfer failed"); } /** * @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))), "Approve failed"); } }
Approves the stipulated contract to spend the given allowance in the given token Errors with 'SA' if transfer fails token The contract address of the token to be approved to The target of the approval 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))), "Approve failed"); }
1,482,142
./full_match/44787/0xbB8cAD00EAf597299c947eCD1a07af9a7Ff23e0B/sources/contracts/Celoquest.sol
_questId quest id we would get winning contribution Get present contribution having the more votes in case of equality, first contribution is winning/Quest owner vote count as 25% of total votation
function getWinningContribution(uint _questId) public view returns(uint) { require(_questId < nbQuests, "Quest not found"); uint tmpWinning = quests[_questId].userVote[quests[_questId].owner]; uint maxVote = contributions[tmpWinning].nbVotes + (quests[_questId].nbVotes / 4); for (uint i = 0 ; i < quests[_questId].nbContributions ; i++) { Contribution memory tmpContrib = contributions[quests[_questId].contributions[i]]; if (tmpContrib.nbVotes > maxVote) { tmpWinning = i; maxVote = tmpContrib.nbVotes; } } return tmpWinning; }
13,268,437
pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Compound's Comptroller Contract * @author Compound */ contract Comptroller is ComptrollerV6Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an admin removes a market event MarketRemoved(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(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when a new COMP speed is set for a contributor event ContributorCompSpeedUpdated(address indexed contributor, uint newSpeed); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when COMP is granted by admin event CompGranted(address recipient, uint amount); /// @notice Emitted when B.Protocol is changed event NewBProtocol(address indexed cToken, address oldBProtocol, address newBProtocol); /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { // Set admin to Hundred deployer admin = 0x1001009911e3FE1d5B45FF8Efea7732C33a6C012; } /*** 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 (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(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)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } 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 (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(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]; uint len = userAssetList.length; uint assetIndex = len; for (uint 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]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param 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, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter); return uint(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, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param 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, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param 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, uint redeemAmount, uint 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, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.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 Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving // Disabled for borrowers return uint(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, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param 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, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving // Disabled for borrowers return uint(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, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param 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, uint repayAmount) external returns (uint) { if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } /* Only B.Protocol can liquidate */ address bLiquidator = bprotocol[address(cTokenBorrowed)]; if(bLiquidator != address(0) && IBProtocol(bLiquidator).canLiquidate(cTokenBorrowed, cTokenCollateral, repayAmount)) { require(liquidator == bLiquidator, "only B.Protocol can liquidate"); } return uint(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, uint actualRepayAmount, uint 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) { maxAssets = maxAssets; } } /** * @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, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower); distributeSupplierComp(cTokenCollateral, liquidator); return uint(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, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param 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, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src); distributeSupplierComp(cToken, dst); return uint(Error.NO_ERROR); } /** * @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, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `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 { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, 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, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(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, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * 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, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the 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 (uint) { // 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 uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param 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, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(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 uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken // Note that isComped is not in active use anymore markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } function _disableMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (!markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken require(CToken(cToken).totalBorrowsCurrent() == 0, "market has borrows"); require(CToken(cToken).totalSupply() == 0, "market has supply"); _removeMarketInternal(address(cToken)); emit MarketRemoved(cToken); return uint(Error.NO_ERROR); } function _removeMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { if (allMarkets[i] == CToken(cToken)) { allMarkets[i] = allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } delete markets[cToken]; } /** * @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 borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @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, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @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 (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == implementation; } /*** Comp Distribution ***/ /** * @notice Set COMP speed for a single market * @param cToken The market whose COMP speed to update * @param compSpeed New COMP speed for market */ function setCompSpeedInternal(CToken cToken, uint compSpeed) internal { uint currentCompSpeed = compSpeeds[address(cToken)]; if (currentCompSpeed != 0) { // note that COMP speed could be set to 0 to halt liquidity rewards for a market updateCompSupplyIndex(address(cToken)); } else if (compSpeed != 0) { // Add the COMP market Market storage market = markets[address(cToken)]; require(market.isListed == true, "comp market is not listed"); if (compSupplyState[address(cToken)].index == 0 && compSupplyState[address(cToken)].block == 0) { compSupplyState[address(cToken)] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[address(cToken)].index == 0 && compBorrowState[address(cToken)].block == 0) { compBorrowState[address(cToken)] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } if (currentCompSpeed != compSpeed) { compSpeeds[address(cToken)] = compSpeed; emit CompSpeedUpdated(cToken, compSpeed); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = supplierAccrued; emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate additional accrued COMP for a contributor since last accrual * @param contributor The address to calculate contributor rewards for */ function updateContributorRewards(address contributor) public { uint compSpeed = compContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && compSpeed > 0) { uint newAccrued = mul_(deltaBlocks, compSpeed); uint contributorAccrued = add_(compAccrued[contributor], newAccrued); compAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address[] memory holders, CToken[] memory cTokens) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j]); compAccrued[holders[j]] = grantCompInternal(holders[j], compAccrued[holders[j]]); } } } /** * @notice Transfer COMP to the user * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param amount The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function grantCompInternal(address user, uint amount) internal returns (uint) { IERC20 comp = IERC20(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (amount > 0 && amount <= compRemaining) { comp.transfer(user, amount); return 0; } return amount; } /*** Comp Distribution Admin ***/ /** * @notice Transfer COMP to the recipient * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param recipient The address of the recipient to transfer COMP to * @param amount The amount of COMP to (possibly) transfer */ function _grantComp(address recipient, uint amount) public { require(adminOrInitializing(), "only admin can grant comp"); uint amountLeft = grantCompInternal(recipient, amount); require(amountLeft == 0, "insufficient comp for grant"); emit CompGranted(recipient, amount); } /** * @notice Set COMP speed for a single market * @param cToken The market whose COMP speed to update * @param compSpeed New COMP speed for market */ function _setCompSpeed(CToken cToken, uint compSpeed) public { require(adminOrInitializing(), "only admin can set comp speed"); setCompSpeedInternal(cToken, compSpeed); } /** * @notice Set COMP speed for a single contributor * @param contributor The contributor whose COMP speed to update * @param compSpeed New COMP speed for contributor */ function _setContributorCompSpeed(address contributor, uint compSpeed) public { require(adminOrInitializing(), "only admin can set comp speed"); // note that COMP speed could be set to 0 to halt liquidity rewards for a contributor updateContributorRewards(contributor); if (compSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } else { lastContributorBlock[contributor] = getBlockNumber(); } compContributorSpeeds[contributor] = compSpeed; emit ContributorCompSpeedUpdated(contributor, compSpeed); } function _setBProtocol(address cToken, address newBProtocol) public returns (uint) { require(adminOrInitializing(), "only admin can set B.Protocol"); emit NewBProtocol(cToken, bprotocol[cToken], newBProtocol); bprotocol[cToken] = newBProtocol; return uint(Error.NO_ERROR); } /** * @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 (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public pure returns (address) { return 0x10010078a54396F62c96dF8532dc2B4847d47ED3; } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.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_, 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 comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting 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 == 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 = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_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 srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = 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] = srcTokensNew; 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); // unused function // comptroller.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 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 (uint, uint, uint, uint) { uint cTokenBalance = 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), 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 (uint) { 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 (uint) { 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 (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 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 (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 CToken * @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 cToken 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 AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(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 * @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 cTokens 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 = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_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 cToken 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 cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens 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 cTokens 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 Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @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 * @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 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 * @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 cTokens 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 cTokens 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 cTokens (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 = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_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 cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken 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 Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.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 = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_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 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); /* 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 Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.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 = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_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 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); /* * 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 RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.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 cToken to be liquidated * @param cTokenCollateral 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, CTokenInterface cTokenCollateral) 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 = cTokenCollateral.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, cTokenCollateral); } /** * @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 * @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, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_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 cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.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) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.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(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.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 LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), 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 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, 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 CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @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 seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_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 */ // unused function // comptroller.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 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 (uint) { // 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(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); 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 NewReserveFactor(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 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); 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 NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(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 } } 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(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, 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_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_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_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_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_COMPTROLLER_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_COMPTROLLER_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_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, 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); } } pragma solidity ^0.5.16; import "./CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @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 (uint); } pragma solidity ^0.5.16; 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 (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle.sol"; import "./IBProtocol.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 implementation; /** * @notice Pending brains of Unitroller */ address public pendingImplementation; } 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 */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { 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. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @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; } contract ComptrollerV3Storage is ComptrollerV2Storage { 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 rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @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 => uint) public borrowCaps; } contract ComptrollerV5Storage is ComptrollerV4Storage { /// @notice The portion of COMP that each contributor receives per block mapping(address => uint) public compContributorSpeeds; /// @notice Last block at which a contributor's COMP rewards have been allocated mapping(address => uint) public lastContributorBlock; } contract ComptrollerV6Storage is ComptrollerV5Storage { /// @notice CToken => IBProtocol (per CToken debt) mapping(address => address) public bprotocol; } 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 `implementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingImplementation 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 Hundred Deployer admin = 0x1001009911e3FE1d5B45FF8Efea7732C33a6C012; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingImplementation; pendingImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingImplementation); return uint(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 (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingImplementation || pendingImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = implementation; address oldPendingImplementation = pendingImplementation; implementation = pendingImplementation; pendingImplementation = address(0); emit NewImplementation(oldImplementation, implementation); emit NewPendingImplementation(oldPendingImplementation, pendingImplementation); return uint(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 (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() public 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); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./EIP20NonStandardInterface.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) */ 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-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) */ 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; } 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(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, 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 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(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 _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** 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, CTokenInterface cTokenCollateral) external returns (uint); function sweepToken(EIP20NonStandardInterface token) external; /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @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 is CDelegationStorage { /** * @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; } pragma solidity ^0.5.16; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @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, ExponentialNoError { /** * @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); } } 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 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 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); } 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; /** * @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(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); } } pragma solidity ^0.5.16; /** * @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 ExponentialNoError { 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 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 Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { 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, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @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)}); } } pragma solidity ^0.5.16; interface IBProtocol { function canLiquidate( address cTokenBorrowed, address cTokenCollateral, uint repayAmount ) external view returns(bool); }
Claim all comp accrued by the holders holders The addresses to claim COMP for cTokens The list of markets to claim COMP in/
function claimComp(address[] memory holders, CToken[] memory cTokens) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j]); compAccrued[holders[j]] = grantCompInternal(holders[j], compAccrued[holders[j]]); } } for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j]); compAccrued[holders[j]] = grantCompInternal(holders[j], compAccrued[holders[j]]); } } }
5,814,437
pragma solidity >=0.4.22 <0.6.0; pragma experimental ABIEncoderV2; contract TripLogic { struct offer //offer cant be reserved while its started { address carOwnerAddress; uint64 startTime; uint64 endDate; //repeat to let the client know uint32 endTime; //hours - was added by 1000 to ensure 0000 is not possible uint64 latpickupLocation; uint64 longpickupLocation; uint64[10] latPolygons; uint64[10] longPolygons; // uint32 dropoffRange; //DropoffRange, depricated //uint64 latdropofflocation; //center of polygons, depricated //uint64 longdropOffLocation; //center of polygons, depricated address reservedAdress; //Address of the reserved Trip, if address == owner means that trip got deleted bool reserved; //Is a trip reserved? uint256 reservedBlockNumber; //BlockNumber when a trip got reserved uint256 maxReservedAmount; //max amount of reservation time allowed in blocknumbers uint256 started; //Block number of start time, 0 by default -> acts as a bool check uint256 userDemandsEnd; //Block number of end demand uint256 index; //index in the mapping uint256 id; //Uid of the trip uint256 price; //price in tokens per block (5 secs) uint8 objectType; //car, charging station, ... string model; //further information like BMW i3, Emmy Vesper, can be also used to present a more accurat pciture to the user in the app } struct user { uint balance; //needs to be changed to tokens bool reserved; //did the user reserve a trip? bool started; //did the user start a trip? bool[5] verifiedDriver; //is the user allowed to drive this kind of object? bool verifiedCarOwner; //is the user subrent his/her own a car? uint8 rating; //Review Rating for that user from 1-5 on Client side uint256 ratingCount; //how often has this user been rated? Used to calculate rating mapping(address => bool) hasRatingRight; //checks if user has the right to give a 1-5 star rating for a trip (1 right for each ended trip) } //Checks if object can be reservated by anyone right now, true is it can get reservated function getIsReservable(uint64 endTime, uint256 index) public view returns (bool) { if(endTimeMap[endTime][index].reserved == false) return true; if(block.number - endTimeMap[endTime][index].reservedBlockNumber > endTimeMap[endTime][index].maxReservedAmount) return true; return false; } //Object needs to be freem user needs to be verifired and cant have other reservations function reserveTrip(uint64 endTime, uint256 index) public onlyVerifiedDriver( endTimeMap[endTime][index].objectType) { require(usermap[msg.sender].reserved == false); //***************else: emit already reserved Trip event*************** require(getIsReservable(endTime, index) == true); //***************else: emit already reserved by somone else event *************** require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20***************** usermap[msg.sender].reserved = true; endTimeMap[endTime][index].reserved = true; endTimeMap[endTime][index].reservedAdress = msg.sender; endTimeMap[endTime][index].reservedBlockNumber = block.number; //***************emit Reservation successful event*************** } //canceling trip is only possible if user reserved the trip but did not start it yet function cancelReserve(uint64 endTime, uint256 index) public { if(endTimeMap[endTime][index].reservedAdress == msg.sender && endTimeMap[endTime][index].started == 0) { endTimeMap[endTime][index].reserved = false; usermap[msg.sender].reserved = false; //***************emit Reservation cancel successful event*************** } //***************emit Reservation cancel not successful event*************** } //start and end Trip section function startTrip(uint64 endTime, uint256 index) public { require(endTimeMap[endTime][index].reservedAdress == msg.sender && endTimeMap[endTime][index].started == 0); require(usermap[msg.sender].started == false); //user can only have 1 started trip require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20***************** //emit tripStart(tripAddress, tripKey, msg.sender, block.number); endTimeMap[endTime][index].started = block.number; usermap[msg.sender].started = true; } //only callable by Renter function demandEndTrip(uint64 endTime, uint256 index) public { require(endTimeMap[endTime][index].reservedAdress == msg.sender && endTimeMap[endTime][index].started != 0); require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check require(endTimeMap[endTime][index].userDemandsEnd == 0); endTimeMap[endTime][index].userDemandsEnd = block.number; } //only callable by Renter function userForcesEndTrip(uint64 endTime, uint256 index) public { require(endTimeMap[endTime][index].reservedAdress == msg.sender && endTimeMap[endTime][index].started != 0); require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check require(block.number > endTimeMap[endTime][index].userDemandsEnd+3); //authorit has 3 blocks time to answer to endDemand request contractEndsTrip(endTime, index); } //only callable by carOwner if user wants to end the trip function confirmEndTrip(uint64 endTime, uint256 index) public { require(endTimeMap[endTime][index].carOwnerAddress == msg.sender && endTimeMap[endTime][index].started != 0); require(endTimeMap[endTime][index].userDemandsEnd != 0); contractEndsTrip(endTime, index); } //On long rentals car owner can call this function to ensure sufficient balance from the user function doubtBalanceEnd(uint64 endTime, uint256 index) public { require(endTimeMap[endTime][index].carOwnerAddress == msg.sender && endTimeMap[endTime][index].started != 0); //**************ERC20*********** if balance is not sufficient, renter can end contract contractEndsTrip(endTime, index); //Alternative: automatically end trips after certain amount and require user to rebook trips } function contractEndsTrip (uint64 endTime, uint256 index) private { //*****************************ERC20Payment, out of money(?)************************************** usermap[msg.sender].started = false; usermap[msg.sender].hasRatingRight[endTimeMap[endTime][index].carOwnerAddress] = true; address def; endTimeMap[endTime][index].reservedAdress = def; endTimeMap[endTime][index].reserved = false; endTimeMap[endTime][index].started = 0; endTimeMap[endTime][index].userDemandsEnd = 0; } //User has a rating right for each ended trip function rateTrip(address ownerAddress, uint8 rating) public { require(usermap[msg.sender].hasRatingRight[ownerAddress] == true); require(rating > 0); require(rating < 6); usermap[ownerAddress].rating += rating; usermap[ownerAddress].ratingCount++; usermap[msg.sender].hasRatingRight[ownerAddress] = false; } //endTime needs to be added by 1000 to make 0000 not possible function offerTrip(uint64 startTime, uint32 endTime, uint64 endDate, uint64 latpickupLocation, uint64 longpickupLocation, uint256 price, uint64[10] memory latPolygons, uint64[10] memory longPolygons, uint256 maxReservedAmount, uint8 objectType, string memory model ) public onlyVerifiedCarOwner() { offer memory tempOffer; tempOffer.startTime = startTime; tempOffer.endTime = endTime; tempOffer.endDate = endDate; tempOffer.latpickupLocation = latpickupLocation; tempOffer.longpickupLocation = longpickupLocation; tempOffer.carOwnerAddress = msg.sender; // tempOffer.id = id; //maybe id should be set for the user to avoid collisions tempOffer.id = currentID; //setting id for the user currentID++; tempOffer.price = price; tempOffer.latPolygons = latPolygons; tempOffer.longPolygons = longPolygons; tempOffer.maxReservedAmount = maxReservedAmount; tempOffer.objectType = objectType; tempOffer.model = model; endTimeMap[endDate][mapindex[endDate]] = tempOffer; mapindex[endDate]++; // tempOffer.latdropofflocation = latdropofflocation; //tempOffer.longdropOffLocation = longdropOffLocation; //tempOffer.dropoffRange = dropoffRange; } //Change Trip details Section function updateCarLocation(uint64 endTime, uint256 index, uint64 newlat, uint64 newlong) public onlyVerifiedCarOwner { require(endTimeMap[endTime][index].carOwnerAddress == msg.sender); require(endTimeMap[endTime][index].reserved == false); endTimeMap[endTime][index].longpickupLocation = newlong; endTimeMap[endTime][index].latpickupLocation = newlat; } function updateCarPrice(uint64 endTime, uint256 index, uint256 price) public onlyVerifiedCarOwner { require(endTimeMap[endTime][index].carOwnerAddress == msg.sender); require(endTimeMap[endTime][index].reserved == false); endTimeMap[endTime][index].price = price; } function testVerifyme() public { usermap[msg.sender].verifiedDriver[0] = true; usermap[msg.sender].verifiedDriver[1] = true; usermap[msg.sender].verifiedDriver[2] = true; usermap[msg.sender].verifiedDriver[3] = true; usermap[msg.sender].verifiedDriver[4] = true; usermap[msg.sender].verifiedCarOwner = true; usermap[msg.sender].balance += 2000000; } /** Delete worked in test maybe not longer needed //basically deleting a trip function reserveTripExternal(uint64 endTime, uint256 index) public { require(endTimeMap[endTime][index].reserved == false); require(endTimeMap[endTime][index].carOwnerAddress == msg.sender); endTimeMap[endTime][index].reserved = true; endTimeMap[endTime][index].reservedAdress = msg.sender; } //car Owner can only unreserve trip if it was booked externally and if its actually his car function unreserveTripExternal(uint64 endTime, uint256 index) public { require(endTimeMap[endTime][index].carOwnerAddress == msg.sender && endTimeMap[endTime][index].reservedAdress ==msg.sender); address def; endTimeMap[endTime][index].reservedAdress = def; endTimeMap[endTime][index].reserved = false; } */ //needs to be tested -> worked in test function deleteTrip(uint64 endTime, uint256 index) public { require(endTimeMap[endTime][index].reserved == false); require(endTimeMap[endTime][index].carOwnerAddress == msg.sender); endTimeMap[endTime][index] = endTimeMap[endTime][mapindex[endTime]-1]; delete endTimeMap[endTime][mapindex[endTime]-1]; mapindex[endTime]--; // endTimeMap[endTime][index] = endTimeMap[endTime][endTimeMap[endTime].length -1]; //copy last element to the position which should be deleted //only works with dynamic arrays // delete endTimeMap[endTime][endTimeMap[endTime].length -1]; //delete last element } //Get Trip Information Section function getTrip(uint64 endDate, uint256 index) public view returns(offer memory) //offer[] memory { return endTimeMap[endDate][index]; //maybe mapindex has to be set to allow client to refind the trip -> probably better to set this client side when looping } function getIndex(uint64 endTime) public view returns (uint256) //returns length of that array { return mapindex[endTime]; } //index +1 to make 0 distinguishable -no item found function getTripID(uint64 endTime, uint32 id, uint256 startindex) public view returns(uint256 index) { for(uint256 i = startindex; i<= mapindex[endTime]; i++) { if(endTimeMap[endTime][i].carOwnerAddress == msg.sender && endTimeMap[endTime][i].id == id) { return i+1; } } } }
User has a rating right for each ended trip
function rateTrip(address ownerAddress, uint8 rating) public { require(usermap[msg.sender].hasRatingRight[ownerAddress] == true); require(rating > 0); require(rating < 6); usermap[ownerAddress].rating += rating; usermap[ownerAddress].ratingCount++; usermap[msg.sender].hasRatingRight[ownerAddress] = false; }
15,820,456
./partial_match/1/0xa03ba2D6Dd3c4e5cD558F8ed90F4FE1BD5AFe7AC/sources/TornomyERC20Staked.sol
A method to add a stakeholder. account The account to add./ if user exists, add _val else its new user
function _addStakeholder(address account) private { if (!_stakeHolderMap[account].status) { _stakeHolders.push(account); _stakeHolderMap[account].status = true; _stakeHolderMap[account].index = _stakeHolders.length - 1; } }
4,241,197
pragma solidity 0.5.17; library SafeMath { function MUL922(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function DIV682(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 SUB426(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b <= a); return a - b; } function ADD438(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OWNERSHIPTRANSFERRED626(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor() public { owner = msg.sender; } modifier ONLYOWNER539() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP867(address newOwner) ONLYOWNER539 public { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED626(owner, newOwner); owner = newOwner; } } contract ERC20Basic { uint256 public totalSupply; function BALANCEOF550(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER247(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER814(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; function TRANSFER247(address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING require(_to != address(0) && _to != address(this)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].SUB426(_value); balances[_to] = balances[_to].ADD438(_value); emit TRANSFER814(msg.sender, _to, _value); return true; } function BALANCEOF550(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return balances[_owner]; } } contract ERC20 is ERC20Basic { function ALLOWANCE624(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFERFROM452(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING function APPROVE694(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event APPROVAL612(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function TRANSFERFROM452(address _from, address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING require(_to != address(0) && _to != address(this)); 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].SUB426(_value); balances[_to] = balances[_to].ADD438(_value); allowed[_from][msg.sender] = _allowance.SUB426(_value); emit TRANSFER814(_from, _to, _value); return true; } function APPROVE694(address _spender, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING allowed[msg.sender][_spender] = _value; emit APPROVAL612(msg.sender, _spender, _value); return true; } function ALLOWANCE624(address _owner, address _spender) public view returns (uint256 remaining) { //inject NONSTANDARD NAMING return allowed[_owner][_spender]; } function INCREASEAPPROVAL555 (address _spender, uint _addedValue) public //inject NONSTANDARD NAMING returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].ADD438(_addedValue); emit APPROVAL612(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function DECREASEAPPROVAL969 (address _spender, uint _subtractedValue) public //inject NONSTANDARD NAMING returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.SUB426(_subtractedValue); } emit APPROVAL612(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } interface tokenRecipient { function RECEIVEAPPROVAL835(address _from, uint256 _value, bytes calldata _extraData) external; //inject NONSTANDARD NAMING } contract BurnableToken is StandardToken { event BURN972(address indexed burner, uint256 value); //inject NONSTANDARD NAMING function BURN583(address burner, uint256 _value) internal { //inject NONSTANDARD NAMING require(_value > 0); require(_value <= balances[burner]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[burner] = balances[burner].SUB426(_value); totalSupply = totalSupply.SUB426(_value); emit TRANSFER814(burner, address(0), _value); emit BURN972(burner, _value); } } contract DKING is BurnableToken, Ownable { address public stakingAddress; string public constant name593 = "Deflationary King"; //inject NONSTANDARD NAMING string public constant symbol894 = "DKING"; //inject NONSTANDARD NAMING uint public constant decimals497 = 18; //inject NONSTANDARD NAMING // there is no problem in using * here instead of .mul() uint256 public constant initialsupply444 = 1000000 * (10 ** uint256(decimals497)); //inject NONSTANDARD NAMING function SETSTAKINGADDRESS222(address _addr) public ONLYOWNER539 { //inject NONSTANDARD NAMING stakingAddress = _addr; } function TRANSFER247(address to, uint amount) public returns (bool) { //inject NONSTANDARD NAMING uint _amountToBurn = amount.MUL922(400).DIV682(10000); uint _amountToDisburse = amount.MUL922(400).DIV682(10000); uint _amountAfterFee = amount.SUB426(_amountToBurn).SUB426(_amountToDisburse); BURN583(msg.sender, _amountToBurn); require(super.TRANSFER247(stakingAddress, _amountToDisburse), "Cannot disburse rewards."); if (stakingAddress != address(0)) { tokenRecipient(stakingAddress).RECEIVEAPPROVAL835(msg.sender, _amountToDisburse, ""); } require(super.TRANSFER247(to, _amountAfterFee), "Cannot transfer tokens."); return true; } function TRANSFERFROM452(address from, address to, uint amount) public returns (bool) { //inject NONSTANDARD NAMING require(to != address(0) && to != address(this)); uint _amountToBurn = amount.MUL922(400).DIV682(10000); uint _amountToDisburse = amount.MUL922(400).DIV682(10000); uint _amountAfterFee = amount.SUB426(_amountToBurn).SUB426(_amountToDisburse); 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].SUB426(_amountAfterFee); balances[to] = balances[to].ADD438(_amountAfterFee); balances[from] = balances[from].SUB426(_amountToDisburse); balances[stakingAddress] = balances[stakingAddress].ADD438(_amountToDisburse); allowed[from][msg.sender] = _allowance.SUB426(amount); BURN583(from, _amountToBurn); emit TRANSFER814(from, stakingAddress, _amountToDisburse); emit TRANSFER814(from, to, _amountAfterFee); if (stakingAddress != address(0)) { tokenRecipient(stakingAddress).RECEIVEAPPROVAL835(msg.sender, _amountToDisburse, ""); } return true; } // Constructors constructor () public { totalSupply = initialsupply444; balances[msg.sender] = initialsupply444; // Send all tokens to owner emit TRANSFER814(address(0), msg.sender, initialsupply444); } function TRANSFERANYERC20TOKEN616(address _tokenAddress, address _to, uint _amount) public ONLYOWNER539 { //inject NONSTANDARD NAMING ERC20(_tokenAddress).TRANSFER247(_to, _amount); } }
inject NONSTANDARD NAMING
function TRANSFER247(address to, uint amount) public returns (bool) {
964,911
./partial_match/1/0x84F396739984e8bF9aCa791541B01637c23BCB16/sources/Sale.sol
calculate token amount to be created
function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; require(_beneficiary != address(0)); require(weiAmount != 0); uint256 tokensAmount = checkTokensAmount(weiAmount); usdRaised = usdRaised.add(weiAmount.mul(rate).div(10**18)); token.mint(_beneficiary, tokensAmount); wallet.transfer(msg.value); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokensAmount ); }
2,745,954
./full_match/1/0x162A78B8bbB2c7dbD6D7aceC507EF9625d2b34E4/sources/contracts/savings/Bank.sol
If it is the first borrow FIN rate checkpoint, set the deltaBlock value be 0 so that the first point on borrowFINRateIndex is zero. If the totalBorrow of the token is zero, no FIN token should be mined and the FINRateIndex is unchanged.
function updateBorrowFINIndex(address _token) public onlyAuthorized { uint256 currentBlock = getBlockNumber(); uint256 deltaBlock; deltaBlock = lastBorrowFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastBorrowFINRateCheckpoint[_token]); borrowFINRateIndex[_token][currentBlock] = borrowFINRateIndex[_token][lastBorrowFINRateCheckpoint[_token]].add( totalLoans[_token] == 0 ? 0 : borrowRateIndex[_token][lastCheckpoint[_token]] .mul(deltaBlock) .mul(globalConfig.tokenRegistry().borrowMiningSpeeds(_token)) .div(totalLoans[_token]) ); lastBorrowFINRateCheckpoint[_token] = currentBlock; emit UpdateBorrowFINIndex(_token, borrowFINRateIndex[_token][currentBlock]); }
17,083,678
./full_match/1/0x402993515350c973f1D44FC8762644E3806cB9bC/sources/contracts/data/Keys.sol
key for stable price value token the token to get the key for return key for stable price value
function stablePriceKey(address token) internal pure returns (bytes32) { return keccak256(abi.encode( STABLE_PRICE, token )); }
16,543,176
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.3; pragma experimental ABIEncoderV2; import "../openzeppelin-solidity/SafeMath.sol"; import "../storage/BZxStorage.sol"; import "../BZxVault.sol"; import "../oracle/OracleInterface.sol"; import "./MathFunctions.sol"; contract MiscFunctions is BZxStorage, MathFunctions { using SafeMath for uint256; function _payInterestForOracle( LenderInterest memory oracleInterest, address lender, address oracleAddress, address interestTokenAddress, bool sendToOracle) internal returns (uint256) { address oracleRef = oracleAddresses[oracleAddress]; uint256 interestOwedNow; if (oracleInterest.interestOwedPerDay > 0 && oracleInterest.interestPaidDate > 0 && interestTokenAddress != address(0)) { interestOwedNow = block.timestamp.sub(oracleInterest.interestPaidDate).mul(oracleInterest.interestOwedPerDay).div(86400); if (interestOwedNow > tokenInterestOwed[lender][interestTokenAddress]) interestOwedNow = tokenInterestOwed[lender][interestTokenAddress]; if (interestOwedNow != 0) { oracleInterest.interestPaid = oracleInterest.interestPaid.add(interestOwedNow); tokenInterestOwed[lender][interestTokenAddress] = tokenInterestOwed[lender][interestTokenAddress].sub(interestOwedNow); if (sendToOracle) { // send the interest to the oracle for further processing if (!BZxVault(vaultContract).withdrawToken( interestTokenAddress, oracleRef, interestOwedNow )) { revert("_payInterestForOracle: BZxVault.withdrawToken failed"); } // calls the oracle to signal processing of the interest (ie: paying the lender, retaining fees) if (!OracleInterface(oracleRef).didPayInterestByLender( lender, interestTokenAddress, interestOwedNow, gasUsed // initial used gas, collected in modifier )) { revert("_payInterestForOracle: OracleInterface.didPayInterestByLender failed"); } } else { if (!BZxVault(vaultContract).withdrawToken( interestTokenAddress, lender, interestOwedNow )) { revert("_payInterestForOracle: BZxVault.withdrawToken interest failed"); } } } } oracleInterest.interestPaidDate = block.timestamp; lenderOracleInterest[lender][oracleAddress][interestTokenAddress] = oracleInterest; return interestOwedNow; } /// @dev Calculates the sum of values already filled and cancelled for a given loanOrder. /// @param loanOrderHash A unique hash representing the loan order. /// @return Sum of values already filled and cancelled. function _getUnavailableLoanTokenAmount( bytes32 loanOrderHash) internal view returns (uint256) { uint256 unavailableAmount = orderFilledAmounts[loanOrderHash].add(orderCancelledAmounts[loanOrderHash]); return (orders[loanOrderHash].loanTokenAmount >= unavailableAmount ? unavailableAmount : orders[loanOrderHash].loanTokenAmount); } function _getCollateralRequired( address loanTokenAddress, address collateralTokenAddress, address oracleAddress, uint256 loanTokenAmountFilled, uint256 marginAmount) internal view returns (uint256 collateralTokenAmount) { if (loanTokenAddress == collateralTokenAddress) { collateralTokenAmount = loanTokenAmountFilled .mul(marginAmount) .div(10**20); } else { (uint256 sourceToDestRate, uint256 sourceToDestPrecision,) = OracleInterface(oracleAddresses[oracleAddress]).getTradeData( collateralTokenAddress, loanTokenAddress, MAX_UINT // get best rate ); collateralTokenAmount = loanTokenAmountFilled .mul(sourceToDestPrecision) .div(sourceToDestRate) .mul(marginAmount) .div(10**20); } if (collateralTokenAmount == 0) { revert("_getCollateralRequired: collateralTokenAmount == 0"); } } function _tradePositionWithOracle( LoanOrder memory loanOrder, LoanPosition memory loanPosition, address destTokenAddress, uint256 maxDestTokenAmount, bool ensureHealthy) internal returns (uint256 destTokenAmountReceived, uint256 positionTokenAmountUsed) { if (loanPosition.positionTokenAmountFilled > 0) { // transfer the current position token to the Oracle contract if (!BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, oracleAddresses[loanOrder.oracleAddress], loanPosition.positionTokenAmountFilled)) { revert("MiscFunctions::_tradePositionWithOracle: BZxVault.withdrawToken failed"); } (destTokenAmountReceived, positionTokenAmountUsed) = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).tradePosition( loanOrder, loanPosition, destTokenAddress, maxDestTokenAmount, ensureHealthy ); } } function _removeLoanOrder( bytes32 loanOrderHash, address addr) internal { if (orderListIndex[loanOrderHash][addr].isSet) { assert(orderList[addr].length > 0); uint256 index = orderListIndex[loanOrderHash][addr].index; if (orderList[addr].length > 1) { // replace order in list with last order in array orderList[addr][index] = orderList[addr][orderList[addr].length - 1]; // update the position of this replacement orderListIndex[orderList[addr][index]][addr].index = index; } // trim array and clear storage orderList[addr].length--; orderListIndex[loanOrderHash][addr].index = 0; orderListIndex[loanOrderHash][addr].isSet = false; } } }
Calculates the sum of values already filled and cancelled for a given loanOrder. loanOrderHash A unique hash representing the loan order. return Sum of values already filled and cancelled.
function _getUnavailableLoanTokenAmount( bytes32 loanOrderHash) internal view returns (uint256) { uint256 unavailableAmount = orderFilledAmounts[loanOrderHash].add(orderCancelledAmounts[loanOrderHash]); return (orders[loanOrderHash].loanTokenAmount >= unavailableAmount ? unavailableAmount : orders[loanOrderHash].loanTokenAmount); }
6,434,753
pragma solidity >=0.4.24; import "./DataType.sol"; import "./Ownable.sol"; /** * @title Role (Role Access Control) */ contract Role is Ownable, DataType { //(action => operator => permission), action recommend use string(business directive) mapping(bytes32=>mapping (address => bool)) roles; event AddRole(address _operator, bytes32 _action); event RemoveRole(address _operator, bytes32 _action); constructor () public { roles[stringToBytes32("manageRole")][msg.sender] = true; } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _action the name of the role * // reverts */ modifier onlyRole(string _action) { require(checkRole(msg.sender, stringToBytes32(_action)), "Permission deny"); _; } /** * @dev modifier to scope access to a single role (uses msg.sender as address) * @param _action the name of the role */ modifier onlyOwnerOrRole(string _action) { if(owner == msg.sender) { _; } else if (_checkRole(msg.sender, _action)) { _; } else { revert("Permission deny"); } } /** * check permission * @param _operator address of operator * @param _action the name of the role */ function checkRole(address _operator, bytes32 _action) public view returns (bool) { return roles[_action][_operator]; } function _checkRole(address _operator, string _action) internal view returns (bool) { return checkRole(_operator, stringToBytes32(_action)); } /** * @dev add a role to an address * @param _operator address of operator * @param _action the name of the role */ function addRole(address _operator, bytes32 _action) public onlyRole("manageRole") returns (bool) { roles[_action][_operator] = true; emit AddRole(_operator, _action); return true; } function _addRole(address _operator, string _action) internal returns (bool) { roles[stringToBytes32(_action)][_operator] = true; return true; } /** * @dev remove a role from an address * @param _operator address of operator * @param _action the name of the role */ function removeRole(address _operator, bytes32 _action) public onlyRole("manageRole") returns (bool) { if(_operator == msg.sender && _action == stringToBytes32("manageRole")) { revert("can not remove it if operator there is manageRole"); } roles[_action][_operator] = false; emit RemoveRole(_operator, _action); return true; } }
remove a role from an address _operator address of operator _action the name of the role/
function removeRole(address _operator, bytes32 _action) public onlyRole("manageRole") returns (bool) { if(_operator == msg.sender && _action == stringToBytes32("manageRole")) { revert("can not remove it if operator there is manageRole"); } roles[_action][_operator] = false; emit RemoveRole(_operator, _action); return true; }
6,451,106
./full_match/1/0x07445312dB273589dcb0fd2bd57aa815A5Afb8CC/sources/contracts/SimpleStaking.sol
Allows new pairs to be added to the "watcher" code pair the address to add as the liquidity pair
function addNewLPPair(address pair) external onlyOwner { mappedAddresses[pair].isLPPair = true; lpPairs.push(pair); }
16,503,523
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SafeMath { function ADD388(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB906(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB906(a, b, "SafeMath: subtraction overflow"); } function SUB906(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 MUL601(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 DIV456(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV456(a, b, "SafeMath: division by zero"); } function DIV456(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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 MOD78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD78(a, b, "SafeMath: modulo by zero"); } function MOD78(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _MSGSENDER877() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA207() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER734(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE35(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE429(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM531(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL956(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/utils/Address.sol library Address { function ISCONTRACT600(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE944(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"); } function FUNCTIONCALL15(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL15(target, data, "Address: low-level call failed"); } function FUNCTIONCALL15(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE358(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE499(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE358(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE358(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT600(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/token/ERC20/ERC20.sol 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME254() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL669() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS84() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY738() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF68(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER734(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER67(_MSGSENDER877(), recipient, amount); return true; } function ALLOWANCE35(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE429(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, amount); return true; } function TRANSFERFROM531(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER67(sender, recipient, amount); _APPROVE455(sender, _MSGSENDER877(), _allowances[sender][_MSGSENDER877()].SUB906(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE275(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].ADD388(addedValue)); return true; } function DECREASEALLOWANCE402(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].SUB906(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER67(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER81(sender, recipient, amount); _balances[sender] = _balances[sender].SUB906(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD388(amount); emit TRANSFER657(sender, recipient, amount); } function _MINT823(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER81(address(0), account, amount); _totalSupply = _totalSupply.ADD388(amount); _balances[account] = _balances[account].ADD388(amount); emit TRANSFER657(address(0), account, amount); } function _BURN465(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER81(account, address(0), amount); _balances[account] = _balances[account].SUB906(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB906(amount); emit TRANSFER657(account, address(0), amount); } function _APPROVE455(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL956(owner, spender, amount); } function _SETUPDECIMALS854(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER81(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER331(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFER734.selector, to, value)); } function SAFETRANSFERFROM748(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFERFROM531.selector, from, to, value)); } function SAFEAPPROVE284(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.ALLOWANCE35(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, value)); } function SAFEINCREASEALLOWANCE243(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE35(address(this), spender).ADD388(value); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE653(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE35(address(this), spender).SUB906(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN31(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. 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).FUNCTIONCALL15(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"); } } } interface IVault is IERC20 { function TOKEN190() external view returns (address); //inject NONSTANDARD NAMING function DECIMALS84() external view returns (uint8); //inject NONSTANDARD NAMING function EARN763() external; //inject NONSTANDARD NAMING function DEPOSIT115(uint256) external; //inject NONSTANDARD NAMING function DEPOSITALL187() external; //inject NONSTANDARD NAMING function WITHDRAW593(uint256) external; //inject NONSTANDARD NAMING function WITHDRAWALL63() external; //inject NONSTANDARD NAMING function DISTRIBUTE67() external; //inject NONSTANDARD NAMING function SALVAGE929(address, uint256) external; //inject NONSTANDARD NAMING function GETRATIO675() external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveFi_2 { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[2] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[2] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[2] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurve3Pool { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[3] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[3] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[3] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(uint256) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveFi_4 { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[4] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[4] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveZap_4 { function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING uint256[4] calldata uamounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata min_uamounts) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[4] calldata uamounts, uint256 max_burn_amount ) external; function CALC_WITHDRAW_ONE_COIN560(uint256 _token_amount, int128 i) //inject NONSTANDARD NAMING external returns (uint256); function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount ) external; function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function WITHDRAW_DONATED_DUST417() external; //inject NONSTANDARD NAMING function COINS352(int128 arg0) external returns (address); //inject NONSTANDARD NAMING function UNDERLYING_COINS1(int128 arg0) external returns (address); //inject NONSTANDARD NAMING function CURVE335() external returns (address); //inject NONSTANDARD NAMING function TOKEN190() external returns (address); //inject NONSTANDARD NAMING } interface ICurveZap { function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveGauge { function DEPOSIT115(uint256 _value) external; //inject NONSTANDARD NAMING function DEPOSIT115(uint256 _value, address addr) external; //inject NONSTANDARD NAMING function BALANCEOF68(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW593(uint256 _value) external; //inject NONSTANDARD NAMING function WITHDRAW593(uint256 _value, bool claim_rewards) external; //inject NONSTANDARD NAMING function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING function CLAIM_REWARDS536(address addr) external; //inject NONSTANDARD NAMING function CLAIMABLE_TOKENS440(address addr) external returns (uint256); //inject NONSTANDARD NAMING function CLAIMABLE_REWARD978(address addr) external view returns (uint256); //inject NONSTANDARD NAMING function INTEGRATE_FRACTION797(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveMintr { function MINT951(address) external; //inject NONSTANDARD NAMING function MINTED257(address arg0, address arg1) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveVotingEscrow { function LOCKED178(address arg0) //inject NONSTANDARD NAMING external view returns (int128 amount, uint256 end); function LOCKED__END474(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE_LOCK305(uint256, uint256) external; //inject NONSTANDARD NAMING function INCREASE_AMOUNT922(uint256) external; //inject NONSTANDARD NAMING function INCREASE_UNLOCK_TIME38(uint256 _unlock_time) external; //inject NONSTANDARD NAMING function WITHDRAW593() external; //inject NONSTANDARD NAMING function SMART_WALLET_CHECKER846() external returns (address); //inject NONSTANDARD NAMING } interface ICurveSmartContractChecker { function WALLETS237(address) external returns (bool); //inject NONSTANDARD NAMING function APPROVEWALLET249(address _wallet) external; //inject NONSTANDARD NAMING } interface UniswapRouterV2 { function SWAPEXACTTOKENSFORTOKENS167( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function ADDLIQUIDITY947( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function ADDLIQUIDITYETH996( //inject NONSTANDARD NAMING address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function REMOVELIQUIDITY801( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function GETAMOUNTSOUT893(uint256 amountIn, address[] calldata path) //inject NONSTANDARD NAMING external view returns (uint256[] memory amounts); function GETAMOUNTSIN14(uint256 amountOut, address[] calldata path) //inject NONSTANDARD NAMING external view returns (uint256[] memory amounts); function SWAPETHFOREXACTTOKENS437( //inject NONSTANDARD NAMING uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function SWAPEXACTETHFORTOKENS898( //inject NONSTANDARD NAMING uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event APPROVAL956( //inject NONSTANDARD NAMING address indexed owner, address indexed spender, uint256 value ); event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING function NAME254() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL669() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS84() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE35(address owner, address spender) //inject NONSTANDARD NAMING external view returns (uint256); function APPROVE429(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER734(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM531( //inject NONSTANDARD NAMING address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR578() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH551() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES443(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function PERMIT326( //inject NONSTANDARD NAMING address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event MINT405(address indexed sender, uint256 amount0, uint256 amount1); //inject NONSTANDARD NAMING event BURN673( //inject NONSTANDARD NAMING address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event SWAP227( //inject NONSTANDARD NAMING address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY881() external pure returns (uint256); //inject NONSTANDARD NAMING function FACTORY729() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0644() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1449() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES964() //inject NONSTANDARD NAMING external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function PRICE0CUMULATIVELAST588() external view returns (uint256); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST951() external view returns (uint256); //inject NONSTANDARD NAMING function KLAST390() external view returns (uint256); //inject NONSTANDARD NAMING function MINT951(address to) external returns (uint256 liquidity); //inject NONSTANDARD NAMING function BURN57(address to) //inject NONSTANDARD NAMING external returns (uint256 amount0, uint256 amount1); function SWAP519( //inject NONSTANDARD NAMING uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function SKIM366(address to) external; //inject NONSTANDARD NAMING function SYNC84() external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED988( //inject NONSTANDARD NAMING address indexed token0, address indexed token1, address pair, uint256 ); function GETPAIR36(address tokenA, address tokenB) //inject NONSTANDARD NAMING external view returns (address pair); function ALLPAIRS303(uint256) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH195() external view returns (uint256); //inject NONSTANDARD NAMING function FEETO341() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER863() external view returns (address); //inject NONSTANDARD NAMING function CREATEPAIR664(address tokenA, address tokenB) //inject NONSTANDARD NAMING external returns (address pair); } interface ICurveTBTC { function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING uint256[4] calldata amounts, uint256 min_mint_amount ) external returns (uint256); } interface IKeepRewardsClaimable { function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING } // Base of all strategy contracts abstract contract VoxStrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees uint256 public treasuryFee = 1000; uint256 public constant treasuryfeemax584 = 2000; //inject NONSTANDARD NAMING uint256 public constant treasuryfeebase971 = 10000; //inject NONSTANDARD NAMING uint256 public strategyFee = 500; uint256 public constant strategyfeemax620 = 5000; //inject NONSTANDARD NAMING uint256 public constant strategyfeebase640 = 10000; //inject NONSTANDARD NAMING uint256 public developerFee = 250; uint256 public constant developerfeemax597 = 500; //inject NONSTANDARD NAMING uint256 public constant developerfeebase561 = 10000; //inject NONSTANDARD NAMING // Withdrawal fee uint256 public withdrawalFee = 15; uint256 public constant withdrawalfeemax274 = 15; //inject NONSTANDARD NAMING uint256 public constant withdrawalfeebase605 = 10000; //inject NONSTANDARD NAMING // Tokens address public underlying; address public constant weth339 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address public constant wbtc162 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; //inject NONSTANDARD NAMING // User accounts address public governance; address public strategist; address public treasury; address public devfund; address public timelock; address public vault; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _underlying, address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public { require(_underlying != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_treasury != address(0)); require(_devfund != address(0)); require(_timelock != address(0)); require(_vault != address(0)); underlying = _underlying; governance = _governance; strategist = _strategist; treasury = _treasury; devfund = _devfund; timelock = _timelock; vault = _vault; } // **** Modifiers **** // modifier RESTRICTED912 { //inject NONSTANDARD NAMING require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function BALANCEOFUNDERLYING222() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(underlying).BALANCEOF68(address(this)); } function BALANCEOFPOOL881() public virtual view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFUNDERLYING222().ADD388(BALANCEOFPOOL881()); } function GETNAME974() external virtual pure returns (string memory); //inject NONSTANDARD NAMING // **** Setters **** // function SETTREASURYFEE502(uint256 _treasuryFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); treasuryFee = _treasuryFee; } function SETSTRATEGYFEE761(uint256 _strategyFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); strategyFee = _strategyFee; } function SETDEVELOPERFEE113(uint256 _developerFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); developerFee = _developerFee; } function SETWITHDRAWALFEE980(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); withdrawalFee = _withdrawalFee; } function SETSTRATEGIST654(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function SETGOVERNANCE136(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETTREASURY187(address _treasury) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); treasury = _treasury; } function SETDEVFUND591(address _devfund) external { //inject NONSTANDARD NAMING require(msg.sender == devfund, "!devfund"); devfund = _devfund; } function SETTIMELOCK277(address _timelock) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); timelock = _timelock; } // **** State mutations **** // function DEPOSIT115() public virtual; //inject NONSTANDARD NAMING // Governance only function to salvage non-underlying assets function SALVAGE929(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); require(underlying != address(_asset), "underlying"); balance = _asset.BALANCEOF68(address(this)); _asset.SAFETRANSFER331(treasury, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW593(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == vault, "!vault"); uint256 _balance = IERC20(underlying).BALANCEOF68(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME235(_amount.SUB906(_balance)); _amount = _amount.ADD388(_balance); } uint256 _withdrawalFee = _amount.MUL601(withdrawalFee).DIV456(withdrawalfeebase605); IERC20(underlying).SAFETRANSFER331(treasury, _withdrawalFee); require(vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(underlying).SAFETRANSFER331(vault, _amount.SUB906(_withdrawalFee)); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL63() external RESTRICTED912 returns (uint256 balance) { //inject NONSTANDARD NAMING _WITHDRAWALL78(); balance = IERC20(underlying).BALANCEOF68(address(this)); require(vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(underlying).SAFETRANSFER331(vault, balance); } function _WITHDRAWALL78() internal { //inject NONSTANDARD NAMING _WITHDRAWSOME235(BALANCEOFPOOL881()); } function _WITHDRAWSOME235(uint256 _amount) internal virtual returns (uint256); //inject NONSTANDARD NAMING function HARVEST372() public virtual; //inject NONSTANDARD NAMING function _DISTRIBUTEANDDEPOSIT388() internal { //inject NONSTANDARD NAMING uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this)); if (_underlying > 0) { // Treasury fees IERC20(underlying).SAFETRANSFER331( treasury, _underlying.MUL601(treasuryFee).DIV456(treasuryfeebase971) ); // Strategy fee IERC20(underlying).SAFETRANSFER331( strategist, _underlying.MUL601(strategyFee).DIV456(strategyfeebase640) ); // Developer fee IERC20(underlying).SAFETRANSFER331( devfund, _underlying.MUL601(developerFee).DIV456(developerfeebase561) ); DEPOSIT115(); } } // **** Emergency functions **** function EXECUTE807(address _target, bytes memory _data) //inject NONSTANDARD NAMING public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _SWAPUNISWAP503( //inject NONSTANDARD NAMING address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).SAFEAPPROVE284(univ2Router2, 0); IERC20(_from).SAFEAPPROVE284(univ2Router2, _amount); address[] memory path; if (_from == weth339 || _to == weth339) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth339; path[2] = _to; } UniswapRouterV2(univ2Router2).SWAPEXACTTOKENSFORTOKENS167( _amount, 0, path, address(this), now.ADD388(60) ); } } // Base contract for Curve based vault strategies abstract contract VoxStrategyCurveBase is VoxStrategyBase { // curve dao address public curve; address public gauge; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // keep address public keep = 0x85Eee30c52B0b379b046Fb0F85F4f3Dc3009aFEC; address public keep_rewards = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6; // How much CRV tokens to keep uint256 public keepCRV = 0; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _underlying, address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public VoxStrategyBase(_underlying, _governance, _strategist, _treasury, _devfund, _timelock, _vault) { curve = _curve; gauge = _gauge; } // **** Getters **** function BALANCEOFPOOL881() public override view returns (uint256) { //inject NONSTANDARD NAMING return ICurveGauge(gauge).BALANCEOF68(address(this)); } function GETHARVESTABLE58() external returns (uint256) { //inject NONSTANDARD NAMING return ICurveGauge(gauge).CLAIMABLE_TOKENS440(address(this)); } function GETMOSTPREMIUM814() public virtual view returns (address, uint256); //inject NONSTANDARD NAMING // **** Setters **** function SETKEEPCRV171(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function DEPOSIT115() public override { //inject NONSTANDARD NAMING uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this)); if (_underlying > 0) { IERC20(underlying).SAFEAPPROVE284(gauge, 0); IERC20(underlying).SAFEAPPROVE284(gauge, _underlying); ICurveGauge(gauge).DEPOSIT115(_underlying); } } function _WITHDRAWSOME235(uint256 _amount) //inject NONSTANDARD NAMING internal override returns (uint256) { ICurveGauge(gauge).WITHDRAW593(_amount); return _amount; } } contract VoxStrategyCurveTBTC is VoxStrategyCurveBase { // Curve stuff address public tbtc_pool = 0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c; address public tbtc_gauge = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6; address public tbtc_crv = 0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd; // EVENTS event HARVESTED180(address indexed token, uint256 amount); //inject NONSTANDARD NAMING constructor( address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public VoxStrategyCurveBase( tbtc_pool, tbtc_gauge, tbtc_crv, _governance, _strategist, _treasury, _devfund, _timelock, _vault ) {} // **** Views **** function GETMOSTPREMIUM814() //inject NONSTANDARD NAMING public override view returns (address, uint256) { return (wbtc162, 2); } function GETNAME974() external override pure returns (string memory) { //inject NONSTANDARD NAMING return "VoxStrategyCurveTBTC"; } // **** State Mutations **** function HARVEST372() public RESTRICTED912 override { //inject NONSTANDARD NAMING // bitcoin we want to convert to (address to, uint256 toIndex) = GETMOSTPREMIUM814(); // Collects crv tokens // this also sends KEEP to keep_rewards contract ICurveMintr(mintr).MINT951(gauge); uint256 _crv = IERC20(crv).BALANCEOF68(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.MUL601(keepCRV).DIV456(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).SAFETRANSFER331( treasury, _keepCRV ); } _crv = _crv.SUB906(_keepCRV); _SWAPUNISWAP503(crv, to, _crv); } // Collects keep tokens IKeepRewardsClaimable(keep_rewards).CLAIM_REWARDS536(); uint256 _keep = IERC20(keep).BALANCEOF68(address(this)); if (_keep > 0) { _SWAPUNISWAP503(keep, to, _keep); } // Adds liquidity to curve.fi's pool // to get back underlying (tbtccrv) uint256 _to = IERC20(to).BALANCEOF68(address(this)); if (_to > 0) { IERC20(to).SAFEAPPROVE284(curve, 0); IERC20(to).SAFEAPPROVE284(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveTBTC(curve).ADD_LIQUIDITY50(liquidity, 0); } // Distribute the collected funds and deposit underlying // Emit harvested event _DISTRIBUTEANDDEPOSIT388(); emit HARVESTED180(to, _to); } }
inject NONSTANDARD NAMING
function ALLPAIRS303(uint256) external view returns (address pair);
12,569,023
./full_match/1/0xAce00EEe06B03873A266eC798d099a74363b941c/sources/contracts/SwapCentral.sol
---------------Uniswap V2 Starts Here----------------------get estimation output
function V2GetEstimatedOut(uint amountIn, address tokenIn, address tokenOut) external view returns (uint[] memory){ address[] memory path = createPath(tokenIn, tokenOut); return routerV2.getAmountsOut(amountIn, path); }
2,959,062
// SPDX-License-Identifier: MIT // Inspired by Stable Joe Staking which in turn is derived from the SushiSwap MasterChef contract pragma solidity 0.8.10; import "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import "../libraries/BoringOwnable.sol"; /** * @title Magic Spell Staking * @author 0xMerlin */ contract mSpellStaking is BoringOwnable { using SafeTransferLib for ERC20; /// @notice Info of each user struct UserInfo { uint128 amount; uint128 rewardDebt; uint128 lastAdded; /** * @notice We do some fancy math here. Basically, any point in time, the amount of JOEs * entitled to a user but is pending to be distributed is: * * pending reward = (user.amount * accRewardPerShare) - user.rewardDebt[token] * * Whenever a user deposits or withdraws SPELL. Here's what happens: * 1. accRewardPerShare (and `lastRewardBalance`) gets updated * 2. User receives the pending reward sent to his/her address * 3. User's `amount` gets updated * 4. User's `rewardDebt[token]` gets updated */ } ERC20 public immutable spell; /// @notice Array of tokens that users can claim ERC20 public immutable mim; /// @notice Last reward balance of `token` uint256 public lastRewardBalance; /// @notice amount of time that the position is locked for. uint256 private constant LOCK_TIME = 24 hours; bool public toggleLockup; /// @notice Accumulated `token` rewards per share, scaled to `ACC_REWARD_PER_SHARE_PRECISION` uint256 public accRewardPerShare; /// @notice The precision of `accRewardPerShare` uint256 public constant ACC_REWARD_PER_SHARE_PRECISION = 1e24; /// @dev Info of each user that stakes SPELL mapping(address => UserInfo) public userInfo; /// @notice Emitted when a user deposits SPELL event Deposit(address indexed user, uint256 amount); /// @notice Emitted when a user withdraws SPELL event Withdraw(address indexed user, uint256 amount); /// @notice Emitted when a user claims reward event ClaimReward(address indexed user, uint256 amount); /// @notice Emitted when a user emergency withdraws its SPELL event EmergencyWithdraw(address indexed user, uint256 amount); /** * @notice Initialize a new mSpellStaking contract * @dev This contract needs to receive an ERC20 `_rewardToken` in order to distribute them * (with MoneyMaker in our case) * @param _mim The address of the MIM token * @param _spell The address of the SPELL token */ constructor( ERC20 _mim, ERC20 _spell ) { require(address(_mim) != address(0), "mSpellStaking: reward token can't be address(0)"); require(address(_spell) != address(0), "mSpellStaking: spell can't be address(0)"); spell = _spell; toggleLockup = true; mim = _mim; } /** * @notice Deposit SPELL for reward token allocation * @param _amount The amount of SPELL to deposit */ function deposit(uint256 _amount) external { UserInfo storage user = userInfo[msg.sender]; uint256 _previousAmount = user.amount; uint256 _newAmount = user.amount + _amount; user.amount = uint128(_newAmount); user.lastAdded = uint128(block.timestamp); updateReward(); uint256 _previousRewardDebt = user.rewardDebt; user.rewardDebt = uint128(_newAmount * accRewardPerShare / ACC_REWARD_PER_SHARE_PRECISION); if (_previousAmount != 0) { uint256 _pending = _previousAmount * accRewardPerShare / ACC_REWARD_PER_SHARE_PRECISION - _previousRewardDebt; if (_pending != 0) { safeTokenTransfer(mim, msg.sender, _pending); emit ClaimReward(msg.sender, _pending); } } spell.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); } /** * @notice View function to see pending reward token on frontend * @param _user The address of the user * @return `_user`'s pending reward token */ function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 _totalSpell = spell.balanceOf(address(this)); uint256 _accRewardTokenPerShare = accRewardPerShare; uint256 _rewardBalance = mim.balanceOf(address(this)); if (_rewardBalance != lastRewardBalance && _totalSpell != 0) { uint256 _accruedReward = _rewardBalance - lastRewardBalance; _accRewardTokenPerShare = _accRewardTokenPerShare + _accruedReward * ACC_REWARD_PER_SHARE_PRECISION / _totalSpell; } return user.amount * _accRewardTokenPerShare / ACC_REWARD_PER_SHARE_PRECISION - user.rewardDebt; } /** * @notice Withdraw SPELL and harvest the rewards * @param _amount The amount of SPELL to withdraw */ function withdraw(uint256 _amount) external { UserInfo storage user = userInfo[msg.sender]; require(!toggleLockup || user.lastAdded + LOCK_TIME < block.timestamp, "mSpell: Wait for LockUp"); uint256 _previousAmount = user.amount; uint256 _newAmount = user.amount - _amount; user.amount = uint128(_newAmount); updateReward(); uint256 _pending = _previousAmount * accRewardPerShare / ACC_REWARD_PER_SHARE_PRECISION - user.rewardDebt; user.rewardDebt = uint128(_newAmount * accRewardPerShare / ACC_REWARD_PER_SHARE_PRECISION); if (_pending != 0) { safeTokenTransfer(mim, msg.sender, _pending); emit ClaimReward(msg.sender, _pending); } spell.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY */ function emergencyWithdraw() external { UserInfo storage user = userInfo[msg.sender]; require(!toggleLockup || user.lastAdded + LOCK_TIME < block.timestamp, "mSpell: Wait for LockUp"); uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; spell.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _amount); } /** * @notice Update reward variables * @dev Needs to be called before any deposit or withdrawal */ function updateReward() public { uint256 _rewardBalance = mim.balanceOf(address(this)); uint256 _totalSpell = spell.balanceOf(address(this)); // Did mSpellStaking receive any token if (_rewardBalance == lastRewardBalance || _totalSpell == 0) { return; } uint256 _accruedReward = _rewardBalance - lastRewardBalance; accRewardPerShare = accRewardPerShare + _accruedReward * ACC_REWARD_PER_SHARE_PRECISION / _totalSpell; lastRewardBalance = _rewardBalance; } /** * @notice Safe token transfer function, just in case if rounding error * causes pool to not have enough reward tokens * @param _token The address of then token to transfer * @param _to The address that will receive `_amount` `rewardToken` * @param _amount The amount to send to `_to` */ function safeTokenTransfer( ERC20 _token, address _to, uint256 _amount ) internal { uint256 _rewardBalance = _token.balanceOf(address(this)); if (_amount > _rewardBalance) { lastRewardBalance = lastRewardBalance - _rewardBalance; _token.safeTransfer(_to, _rewardBalance); } else { lastRewardBalance = lastRewardBalance - _amount; _token.safeTransfer(_to, _amount); } } /** * @notice Allows to enable and disable the lockup * @param status The new lockup status */ function toggleLockUp(bool status) external onlyOwner { toggleLockup = status; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { if (allowance[from][msg.sender] != type(uint256).max) { allowance[from][msg.sender] -= amount; } balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_PERMIT_SIGNATURE"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } }
Withdraw without caring about rewards. EMERGENCY ONLY/
function emergencyWithdraw() external { UserInfo storage user = userInfo[msg.sender]; require(!toggleLockup || user.lastAdded + LOCK_TIME < block.timestamp, "mSpell: Wait for LockUp"); uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; spell.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _amount); }
5,818,246
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() 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 contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() 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 ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(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 MUL16(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 DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(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 MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function __CONTEXT_INIT10() internal INITIALIZER65 {
1,018,796
pragma solidity >= 0.5.17; contract FreeportMainURI { //string public tokenURI; string public URISubfile; address public superManager = 0xaA04E088eBbf63877a58F6B14D1D6F61dF9f3EE8; address public manager; string[] public tokenURI; constructor() public{ manager = msg.sender; } modifier onlyManager{ require(msg.sender == manager || msg.sender == superManager, "Is not manager"); _; } function changeManager(address _new_manager) public { require(msg.sender == superManager, "It's not superManager"); manager = _new_manager; } //----------------Add URI---------------------------- //--Manager only--// function setURI(uint _sort, string memory _tokenURI) public onlyManager{ uint arrayAmounts = tokenURI.length; require(_sort <= arrayAmounts, "Array amounts error."); tokenURI[_sort] = _tokenURI; } function inputURIarr() public onlyManager{ tokenURI.push(""); } function setSubfile(string memory _URISubfile) public onlyManager{ URISubfile = _URISubfile; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; 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); } //--Get token URI uint--// function GettokenURI(uint _tokenID) public view returns(string memory){ string memory _tokenIDSTR = uint2str(_tokenID); return GettokenSTRURI(_tokenID, _tokenIDSTR); } //--Get token URI string--// function GettokenSTRURI(uint _tokenID, string memory _tokenIDSTR) public view returns(string memory){ string memory preURI = strConcat(tokenURI[uint(_tokenID / 10000)], _tokenIDSTR); string memory finalURI = strConcat(preURI, URISubfile); return finalURI; } function strConcat(string memory _a, string memory _b) internal view returns (string memory){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ret = new string(_ba.length + _bb.length); bytes memory bret = bytes(ret); uint k = 0; for (uint i = 0; i < _ba.length; i++){ bret[k++] = _ba[i]; } for (uint i = 0; i < _bb.length; i++){ bret[k++] = _bb[i]; } return string(ret); } //--Manager only--// function destroy() external onlyManager{ selfdestruct(msg.sender); } }
----------------Add URI------------------------------Manager only--
function setURI(uint _sort, string memory _tokenURI) public onlyManager{ uint arrayAmounts = tokenURI.length; require(_sort <= arrayAmounts, "Array amounts error."); tokenURI[_sort] = _tokenURI; }
12,592,114
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import './ERC721Upgradeable.sol'; interface IHonorToken { function updateBalance( address wallet, uint256 debit, uint256 credit ) external; function mint(address wallet, uint256 amount) external; function burn(address wallet, uint256 amount) external; function balanceOf(address wallet) external view returns (uint256); } /*** * .oooooo..o ooooo ooooo .o. oooooooooo. .oooooo. oooooo oooooo oooo * d8P' `Y8 `888' `888' .888. `888' `Y8b d8P' `Y8b `888. `888. .8' * Y88bo. 888 888 .8"888. 888 888 888 888 `888. .8888. .8' * `"Y8888o. 888ooooo888 .8' `888. 888 888 888 888 `888 .8'`888. .8' * `"Y88b 888 888 .88ooo8888. 888 888 888 888 `888.8' `888.8' * oo .d8P 888 888 .8' `888. 888 d88' `88b d88' `888' `888' * 8""88888P' o888o o888o o88o o8888o o888bood8P' `Y8bood8P' `8' `8' * * * * .oooooo. ooooo ooo oooooooooooo .oooooo..o ooooooooooooo * d8P' `Y8b `888' `8' `888' `8 d8P' `Y8 8' 888 `8 * 888 888 888 8 888 Y88bo. 888 * 888 888 888 8 888oooo8 `"Y8888o. 888 * 888 888 888 8 888 " `"Y88b 888 * `88b d88b `88. .8' 888 o oo .d8P 888 * `Y8bood8P'Ybd' `YbodP' o888ooooood8 8""88888P' o888o * * * */ contract ShadowQuest is OwnableUpgradeable, ERC721Upgradeable { event Move( address indexed owner, uint256 indexed tokenId, uint256 indexed direction ); event LocationChanged( uint8 indexed locationIdFrom, uint8 indexed locationIdTo, uint256 amount ); uint256 public constant MAX_GEN0_SUPPLY = 9996; uint256 public constant MAX_GEN1_SUPPLY = 18000; uint256 public constant SALE_PRIVATE_PRICE = 0.075 ether; uint256 public constant SALE_PUBLIC_PRICE = 0.08 ether; uint256 public SALE_PUBLIC_STARTED_AT; uint256 public SALE_PRIVATE_STARTED_AT; uint256 public SALE_PRIVATE_MAX_SUPPLY; uint256 public gen0Supply; uint256 public gen1Supply; string public provenanceHash; IHonorToken public honorContract; address private _proxyRegistryAddress; address private _verifier; string private _baseTokenURI; struct TokenMeta { address owner; uint32 movedAt; uint8 location; uint56 meta; } mapping(uint256 => TokenMeta) public tokenState; uint256[] internal _tokenStateKeys; mapping(address => uint16) public _tokenOwnerState; mapping(address => int16) private _balances; uint256 public locationsBalance; uint256[] public samsarIds; mapping(address => uint256) public honrDeposited; mapping(address => uint256) public honrWithdrawn; function initialize(address verifier_, address proxyRegistryAddress_) public initializer { __ERC721_init('ShadowQuest', 'SQ'); __Ownable_init(); _verifier = verifier_; _proxyRegistryAddress = proxyRegistryAddress_; SALE_PRIVATE_MAX_SUPPLY = 3000; } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } function isOnArena(uint256 tokenId) internal view returns (bool) { return tokenState[tokenId].location > 0; } function actualOwnerOf(uint256 tokenId) public view returns (address) { if (tokenState[tokenId].owner != address(0)) { return tokenState[tokenId].owner; } address tokenIdOwner = address(uint160(tokenId)); uint16 tokenIndex = uint16(tokenId >> 160); require(_tokenOwnerState[tokenIdOwner] != 0, 'SQ: not minted'); require( tokenIndex < _tokenOwnerState[tokenIdOwner], 'SQ: invalid index' ); return tokenIdOwner; } /** * @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' ); if (owner_ == address(this)) { return locationsBalance; } return uint16(int16(_tokenOwnerState[owner_]) + _balances[owner_]); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { if (isOnArena(tokenId)) { return address(this); } return actualOwnerOf(tokenId); } /** * @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 override returns (bool) { if (tokenState[tokenId].owner != address(0)) { return true; } address tokenIdOwner = address(uint160(tokenId)); uint16 tokenIndex = uint16(tokenId >> 160); return (_tokenOwnerState[tokenIdOwner] != 0) && (tokenIndex < _tokenOwnerState[tokenIdOwner]); } /** * @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 override { require( ownerOf(tokenId) == from, 'ERC721: transfer from incorrect owner' ); require(to != address(0), 'ERC721: transfer to the zero address'); require(to != from, "ERC721: can't transfer themself"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); if (tokenState[tokenId].owner == address(0)) { _tokenStateKeys.push(tokenId); } _balances[from] -= 1; _balances[to] += 1; tokenState[tokenId].owner = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } function _recoverSigner(bytes32 hash, bytes memory signature) internal pure returns (address) { return ECDSAUpgradeable.recover( ECDSAUpgradeable.toEthSignedMessageHash(hash), signature ); } function random(uint256 nonce, uint256 number) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked(block.timestamp, block.difficulty, nonce) ) ) % (number + 1); } event MintGen1( address indexed owner, uint256 indexed nonce, uint16 mintedAmount ); event Steal( address indexed owner, address indexed samsarOwner, uint256 indexed samsarId, uint256 tokenId ); function mintGen1( uint16 expectedAmount, uint256[] calldata samsarIds_, uint256 nonce, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); uint16 tokenAmount = _tokenOwnerState[sender]; uint256 amount = expectedAmount - tokenAmount; require( amount > 0 && amount <= 10 && samsarIds_.length == amount, 'SQ: invalid amount' ); require( gen1Supply + amount < MAX_GEN1_SUPPLY, 'SQ: gen1 supply exceeded' ); require(block.timestamp < timestamp, 'SQ: outdated transaction'); bytes32 hash = keccak256( abi.encodePacked( sender, expectedAmount, samsarIds_, nonce, timestamp ) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); gen1Supply += amount; uint256 rand = random(nonce, 11 - amount); if (rand <= amount - 1) { address samsarOwner = actualOwnerOf(samsarIds_[rand]); uint256 tokenId = uint256(uint160(samsarOwner)) | (uint256(_tokenOwnerState[samsarOwner]) << 160); _tokenOwnerState[samsarOwner] += 1; amount -= 1; emit Transfer(address(0), samsarOwner, tokenId); emit Steal(sender, samsarOwner, samsarIds_[rand], tokenId); } uint256 ownerBase = uint256(uint160(sender)); uint16 minted; for (uint256 index; index < amount; index++) { emit Transfer( address(0), sender, ownerBase | (uint256(_tokenOwnerState[sender] + minted) << 160) ); minted += 1; } emit MintGen1(sender, nonce, minted); if (minted > 0) { _tokenOwnerState[sender] += minted; } } function move( uint8 locationIdFrom, uint8 locationIdTo, uint256[] calldata tokenIds, /** * nation, notIterable, samsarNotIterable */ uint256[] calldata tokenMeta, uint256 timestamp, bytes memory sig ) external { require(block.timestamp < timestamp, 'SQ: outdated transaction'); address sender = _msgSender(); bytes32 hash = keccak256( abi.encodePacked( sender, locationIdFrom, locationIdTo, tokenIds, tokenMeta, timestamp ) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); for (uint256 index; index < tokenIds.length; index++) { uint256 tokenId = tokenIds[index]; require( actualOwnerOf(tokenId) == sender, 'SQ: not owner of the token' ); TokenMeta storage _tokenMeta = tokenState[tokenId]; require( _tokenMeta.location == locationIdFrom, 'SQ: incorrect location' ); if (uint8(tokenMeta[index] >> 8) == 1) { _tokenStateKeys.push(tokenId); } if (uint8(tokenMeta[index] >> 16) == 1) { samsarIds.push(tokenId); } tokenState[tokenId] = TokenMeta({ owner: sender, movedAt: uint32(block.timestamp), location: locationIdTo, meta: uint8(tokenMeta[index]) }); if (locationIdTo == 0) { emit Transfer(address(this), sender, tokenId); } else if (locationIdFrom == 0) { emit Transfer(sender, address(this), tokenId); } } uint256 tokensAmount = tokenIds.length; if (locationIdFrom == 0) { locationsBalance += tokensAmount; } else if (locationIdTo == 0) { locationsBalance -= tokensAmount; } emit LocationChanged(locationIdFrom, locationIdTo, tokensAmount); } event HonrWithdraw( address indexed wallet, uint256 indexed nonce, uint256 amount ); function honrWithdraw( uint256 amount, uint256 expectedAmount, uint256 nonce, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); bytes32 hash = keccak256( abi.encodePacked(sender, amount, expectedAmount, nonce, timestamp) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); require( honrWithdrawn[sender] + amount == expectedAmount, 'SQ: invalid transaction' ); honorContract.mint(sender, amount); honrWithdrawn[sender] += amount; emit HonrWithdraw(sender, nonce, amount); } event HonrDeposit(address indexed wallet, uint256 amount); function honrDeposit( uint256 amount, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); bytes32 hash = keccak256(abi.encodePacked(sender, amount, timestamp)); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); honorContract.burn(sender, amount); honrDeposited[sender] += amount; emit HonrDeposit(sender, amount); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner_, address operator_) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress); if (address(proxyRegistry.proxies(owner_)) == operator_) { return true; } return super.isApprovedForAll(owner_, operator_); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return gen0Supply + gen1Supply - locationsBalance; } struct TokenData { address owner; uint8 location; uint32 movedAt; uint56 meta; uint256 tokenId; } function sliceTokenStateArray( TokenData[] memory arr, uint256 start, uint256 length ) internal pure returns (TokenData[] memory) { TokenData[] memory result = new TokenData[](length); for (uint256 index; index < length; index++) { result[index] = arr[start + index]; } return result; } function getSamsarTokens() external view returns (uint256[] memory) { return samsarIds; } function getTokenStateKeys() external view returns (uint256[] memory) { return _tokenStateKeys; } /** * @dev location_ == -1 – any location */ function getOwnerTokens(address owner_, int8 location_) public view returns (TokenData[] memory) { require( owner_ != address(0), 'ERC721: balance query for the zero address' ); uint256 balance = balanceOf(owner_); TokenData[] memory ownedTokens = new TokenData[](balance); uint256 ownerBase = uint256(uint160(owner_)); uint256 mintedAmount = _tokenOwnerState[owner_]; uint256 resultIndex; for (uint256 index; index < mintedAmount; index++) { uint256 tokenId = ownerBase | (index << 160); TokenMeta storage currentTokenState = tokenState[tokenId]; if ( currentTokenState.owner == address(0) && (location_ == -1 || location_ == 0) ) { ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } else if (currentTokenState.owner == owner_) { if ( location_ == -1 || uint8(location_) == currentTokenState.location ) { ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } } } for (uint256 index = 0; index < _tokenStateKeys.length; index++) { if (resultIndex == balance) { break; } uint256 tokenId = _tokenStateKeys[index]; if (tokenState[tokenId].owner != owner_) { continue; } address tokenIdOwner = address(uint160(tokenId)); if (tokenIdOwner == owner_) { continue; } if ( location_ == -1 || tokenState[tokenId].location == uint8(location_) ) { TokenMeta storage currentTokenState = tokenState[tokenId]; ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } } return sliceTokenStateArray(ownedTokens, 0, resultIndex); } /* OwnerOnly */ function setVerifier(address verifier_) external onlyOwner { _verifier = verifier_; } function setBaseURI(string memory baseURI_) external onlyOwner { _baseTokenURI = baseURI_; } function setState( bool publicSaleState_, bool privateSaleState_, uint256 maxPresaleSupply_ ) external onlyOwner { SALE_PUBLIC_STARTED_AT = publicSaleState_ ? block.timestamp : 0; SALE_PRIVATE_STARTED_AT = privateSaleState_ ? block.timestamp : 0; SALE_PRIVATE_MAX_SUPPLY = maxPresaleSupply_; } function withdraw(uint256 amount) public onlyOwner { (bool success, ) = _msgSender().call{value: amount}(''); require(success, 'Withdraw failed'); } function withdrawAll() external onlyOwner { withdraw(address(this).balance); } function setHonorContract(IHonorToken honorContract_) external onlyOwner { honorContract = honorContract_; } function setLocationsBalance(uint256 amount) external onlyOwner { locationsBalance = amount; } function pushTokenStateKeys(uint256[] calldata tokenIds) external onlyOwner { uint256 tokensAmount = tokenIds.length; for (uint256 index; index < tokensAmount; index++) { _tokenStateKeys.push(tokenIds[index]); } } function _mintGen0(address sender, uint16 amount) internal { require( gen0Supply + amount <= MAX_GEN0_SUPPLY, 'SQ: gen0 supply overflow' ); uint16 tokensAmount = _tokenOwnerState[sender] + amount; uint256 ownerBase = uint256(uint160(sender)); for ( uint256 index = _tokenOwnerState[sender]; index < tokensAmount; index++ ) { emit Transfer(address(0), sender, ownerBase | (index << 160)); } _tokenOwnerState[sender] = tokensAmount; gen0Supply += amount; } function mintReserved(address wallet, uint16 amount) external onlyOwner { address receiver = wallet == address(0) ? _msgSender() : wallet; _mintGen0(receiver, amount); } function revertFalseMint(address wallet, uint16 amount) external onlyOwner { gen1Supply -= amount; _tokenOwnerState[wallet] -= amount; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(false, 'Implementation required'); return 0; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(false, 'Implementation required'); return address(0); } /** * @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 overridden 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 = ownerOf(tokenId); require(to != owner, 'ERC721: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721: approve caller is not owner nor approved for all' ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), 'ERC721: approved query for nonexistent token' ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), 'ERC721: transfer caller is not owner nor approved' ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), 'ERC721: transfer caller is not owner nor approved' ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721: transfer to non ERC721Receiver implementer' ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { require(false, 'Implementation required'); return false; } /** * @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 = 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 {} /** * @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 {} /** * @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 {} /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, 'ERC721: approve to caller'); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library 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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; 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 onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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); }
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' ); }
121,124
./full_match/137/0x7d561bE86eBCB1d8353f98c21Bef7232343598a8/sources/WebaverseERC721.sol
List collaborators for a token tokenId Token ID of the token to get collaborators for/
function getSingleCollaborators(uint256 tokenId) public view returns (address[] memory) { address[] memory collaborators = tokenIdToCollaborators[tokenId]; return collaborators; }
4,669,351
pragma solidity ^0.5; /* NOTE: @kleros/kleros-interraction is not compatible with this solc version */ /* NOTE: I put all the arbitration files in the same file because the dependancy between the different contracts is a real "headache" */ /* If someone takes up the challenge, a PR is welcome */ /** * @title CappedMath * @dev Math operations with caps for under and overflow. * NOTE: see https://raw.githubusercontent.com/kleros/kleros-interaction/master/contracts/libraries/CappedMath.sol */ library CappedMath { uint constant private UINT_MAX = 2**256 - 1; /** * @dev Adds two unsigned integers, returns 2^256 - 1 on overflow. */ function addCap(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; return c >= _a ? c : UINT_MAX; } /** * @dev Subtracts two integers, returns 0 on underflow. */ function subCap(uint _a, uint _b) internal pure returns (uint) { if (_b > _a) return 0; else return _a - _b; } /** * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow. */ function mulCap(uint _a, uint _b) internal pure returns (uint) { // 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; uint c = _a * _b; return c / _a == _b ? c : UINT_MAX; } } /** @title IArbitrable * Arbitrable interface. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ interface IArbitrable { /** @dev To be emmited when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); /** @dev To be emmited when a dispute is created to link the correct meta-evidence to the disputeID * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute. */ event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID); /** @dev To be raised when evidence are submitted. Should point to the ressource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence(Arbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence); /** @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external; } /** @title Arbitrable * Arbitrable abstract contract. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ contract Arbitrable is IArbitrable { Arbitrator public arbitrator; bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour. /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. */ constructor(Arbitrator _arbitrator, bytes memory _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { emit Ruling(Arbitrator(msg.sender), _disputeID, _ruling); executeRuling(_disputeID, _ruling); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal; } /** @title Arbitrator * Arbitrator abstract contract. * When developing arbitrator contracts we need to: * -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, use nbDisputes). * -Define the functions for cost display (arbitrationCost and appealCost). * -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling). */ contract Arbitrator { enum DisputeStatus {Waiting, Appealable, Solved} modifier requireArbitrationFee(bytes memory _extraData) { require(msg.value >= arbitrationCost(_extraData), "Not enough ETH to cover arbitration costs."); _; } modifier requireAppealFee(uint _disputeID, bytes memory _extraData) { require(msg.value >= appealCost(_disputeID, _extraData), "Not enough ETH to cover appeal costs."); _; } /** @dev To be raised when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when a dispute can be appealed. * @param _disputeID ID of the dispute. */ event AppealPossible(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes memory _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function arbitrationCost(bytes memory _extraData) public view returns(uint fee); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes memory _extraData) public requireAppealFee(_disputeID,_extraData) payable { emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint fee); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) {} /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) public view returns(uint ruling); } /** @title Centralized Arbitrator * @dev This is a centralized arbitrator deciding alone on the result of disputes. No appeals are possible. */ contract CentralizedArbitrator is Arbitrator { address public owner = msg.sender; uint arbitrationPrice; // Not public because arbitrationCost already acts as an accessor. uint constant NOT_PAYABLE_VALUE = (2**256-2)/2; // High value to be sure that the appeal is too expensive. struct DisputeStruct { Arbitrable arbitrated; uint choices; uint fee; uint ruling; DisputeStatus status; } modifier onlyOwner {require(msg.sender==owner, "Can only be called by the owner."); _;} DisputeStruct[] public disputes; /** @dev Constructor. Set the initial arbitration price. * @param _arbitrationPrice Amount to be paid for arbitration. */ constructor(uint _arbitrationPrice) public { arbitrationPrice = _arbitrationPrice; } /** @dev Set the arbitration price. Only callable by the owner. * @param _arbitrationPrice Amount to be paid for arbitration. */ function setArbitrationPrice(uint _arbitrationPrice) public onlyOwner { arbitrationPrice = _arbitrationPrice; } /** @dev Cost of arbitration. Accessor to arbitrationPrice. * @param _extraData Not used by this contract. * @return fee Amount to be paid. */ function arbitrationCost(bytes memory _extraData) public view returns(uint fee) { return arbitrationPrice; } /** @dev Cost of appeal. Since it is not possible, it's a high value which can never be paid. * @param _disputeID ID of the dispute to be appealed. Not used by this contract. * @param _extraData Not used by this contract. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint fee) { return NOT_PAYABLE_VALUE; } /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(). * @param _choices Amount of choices the arbitrator can make in this dispute. When ruling ruling<=choices. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes memory _extraData) public payable returns(uint disputeID) { super.createDispute(_choices, _extraData); disputeID = disputes.push(DisputeStruct({ arbitrated: Arbitrable(msg.sender), choices: _choices, fee: msg.value, ruling: 0, status: DisputeStatus.Waiting })) - 1; // Create the dispute and return its number. emit DisputeCreation(disputeID, Arbitrable(msg.sender)); } /** @dev Give a ruling. UNTRUSTED. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision". */ function _giveRuling(uint _disputeID, uint _ruling) internal { DisputeStruct storage dispute = disputes[_disputeID]; require(_ruling <= dispute.choices, "Invalid ruling."); require(dispute.status != DisputeStatus.Solved, "The dispute must not be solved already."); dispute.ruling = _ruling; dispute.status = DisputeStatus.Solved; msg.sender.send(dispute.fee); // Avoid blocking. dispute.arbitrated.rule(_disputeID,_ruling); } /** @dev Give a ruling. UNTRUSTED. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision". */ function giveRuling(uint _disputeID, uint _ruling) public onlyOwner { return _giveRuling(_disputeID, _ruling); } /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { return disputes[_disputeID].status; } /** @dev Return the ruling of a dispute. * @param _disputeID ID of the dispute to rule. * @return ruling The ruling which would or has been given. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { return disputes[_disputeID].ruling; } } /** * @title AppealableArbitrator * @dev A centralized arbitrator that can be appealed. */ contract AppealableArbitrator is CentralizedArbitrator, Arbitrable { /* Structs */ struct AppealDispute { uint rulingTime; Arbitrator arbitrator; uint appealDisputeID; } /* Storage */ uint public timeOut; mapping(uint => AppealDispute) public appealDisputes; mapping(uint => uint) public appealDisputeIDsToDisputeIDs; /* Constructor */ /** @dev Constructs the `AppealableArbitrator` contract. * @param _arbitrationPrice The amount to be paid for arbitration. * @param _arbitrator The back up arbitrator. * @param _arbitratorExtraData Not used by this contract. * @param _timeOut The time out for the appeal period. */ constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut ) public CentralizedArbitrator(_arbitrationPrice) Arbitrable(_arbitrator, _arbitratorExtraData) { timeOut = _timeOut; } /* External */ /** @dev Changes the back up arbitrator. * @param _arbitrator The new back up arbitrator. */ function changeArbitrator(Arbitrator _arbitrator) external onlyOwner { arbitrator = _arbitrator; } /** @dev Changes the time out. * @param _timeOut The new time out. */ function changeTimeOut(uint _timeOut) external onlyOwner { timeOut = _timeOut; } /* External Views */ /** @dev Gets the specified dispute's latest appeal ID. * @param _disputeID The ID of the dispute. */ function getAppealDisputeID(uint _disputeID) external view returns(uint disputeID) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) disputeID = AppealableArbitrator(address(appealDisputes[_disputeID].arbitrator)).getAppealDisputeID(appealDisputes[_disputeID].appealDisputeID); else disputeID = _disputeID; } /* Public */ /** @dev Appeals a ruling. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. */ function appeal(uint _disputeID, bytes memory _extraData) public payable requireAppealFee(_disputeID, _extraData) { super.appeal(_disputeID, _extraData); if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) appealDisputes[_disputeID].arbitrator.appeal.value(msg.value)(appealDisputes[_disputeID].appealDisputeID, _extraData); else { appealDisputes[_disputeID].arbitrator = arbitrator; appealDisputes[_disputeID].appealDisputeID = arbitrator.createDispute.value(msg.value)(disputes[_disputeID].choices, _extraData); appealDisputeIDsToDisputeIDs[appealDisputes[_disputeID].appealDisputeID] = _disputeID; } } /** @dev Gives a ruling. * @param _disputeID The ID of the dispute. * @param _ruling The ruling. */ function giveRuling(uint _disputeID, uint _ruling) public { require(disputes[_disputeID].status != DisputeStatus.Solved, "The specified dispute is already resolved."); if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) { require(Arbitrator(msg.sender) == appealDisputes[_disputeID].arbitrator, "Appealed disputes must be ruled by their back up arbitrator."); super._giveRuling(_disputeID, _ruling); } else { require(msg.sender == owner, "Not appealed disputes must be ruled by the owner."); if (disputes[_disputeID].status == DisputeStatus.Appealable) { if (now - appealDisputes[_disputeID].rulingTime > timeOut) super._giveRuling(_disputeID, disputes[_disputeID].ruling); else revert("Time out time has not passed yet."); } else { disputes[_disputeID].ruling = _ruling; disputes[_disputeID].status = DisputeStatus.Appealable; appealDisputes[_disputeID].rulingTime = now; emit AppealPossible(_disputeID, disputes[_disputeID].arbitrated); } } } /* Public Views */ /** @dev Gets the cost of appeal for the specified dispute. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. * @return The cost of the appeal. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint cost) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) cost = appealDisputes[_disputeID].arbitrator.appealCost(appealDisputes[_disputeID].appealDisputeID, _extraData); else if (disputes[_disputeID].status == DisputeStatus.Appealable) cost = arbitrator.arbitrationCost(_extraData); else cost = NOT_PAYABLE_VALUE; } /** @dev Gets the status of the specified dispute. * @param _disputeID The ID of the dispute. * @return The status. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) status = appealDisputes[_disputeID].arbitrator.disputeStatus(appealDisputes[_disputeID].appealDisputeID); else status = disputes[_disputeID].status; } /** @dev Return the ruling of a dispute. * @param _disputeID ID of the dispute to rule. * @return ruling The ruling which would or has been given. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) // Appealed. ruling = appealDisputes[_disputeID].arbitrator.currentRuling(appealDisputes[_disputeID].appealDisputeID); // Retrieve ruling from the arbitrator whom the dispute is appealed to. else ruling = disputes[_disputeID].ruling; // Not appealed, basic case. } /* Internal */ /** @dev Executes the ruling of the specified dispute. * @param _disputeID The ID of the dispute. * @param _ruling The ruling. */ function executeRuling(uint _disputeID, uint _ruling) internal { require( appealDisputes[appealDisputeIDsToDisputeIDs[_disputeID]].arbitrator != Arbitrator(address(0)), "The dispute must have been appealed." ); giveRuling(appealDisputeIDsToDisputeIDs[_disputeID], _ruling); } } /** * @title EnhancedAppealableArbitrator * @author Enrique Piqueras - <epiquerass@gmail.com> * @dev Implementation of `AppealableArbitrator` that supports `appealPeriod`. */ contract EnhancedAppealableArbitrator is AppealableArbitrator { /* Constructor */ /** @dev Constructs the `EnhancedAppealableArbitrator` contract. * @param _arbitrationPrice The amount to be paid for arbitration. * @param _arbitrator The back up arbitrator. * @param _arbitratorExtraData Not used by this contract. * @param _timeOut The time out for the appeal period. */ constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut ) public AppealableArbitrator(_arbitrationPrice, _arbitrator, _arbitratorExtraData, _timeOut) {} /* Public Views */ /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) (start, end) = appealDisputes[_disputeID].arbitrator.appealPeriod(appealDisputes[_disputeID].appealDisputeID); else { start = appealDisputes[_disputeID].rulingTime; require(start != 0, "The specified dispute is not appealable."); end = start + timeOut; } } } /** * @title Permission Interface * This is a permission interface for arbitrary values. The values can be cast to the required types. */ interface PermissionInterface { /** * @dev Return true if the value is allowed. * @param _value The value we want to check. * @return allowed True if the value is allowed, false otherwise. */ function isPermitted(bytes32 _value) external view returns (bool allowed); } /** * @title ArbitrableBetList * This smart contract is a viewer moderation for the bet goal contract. * This is working progress. */ contract ArbitrableBetList is IArbitrable { using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. /* Enums */ enum BetStatus { Absent, // The bet is not in the registry. Registered, // The bet is in the registry. RegistrationRequested, // The bet has a request to be added to the registry. ClearingRequested // The bet has a request to be removed from the registry. } enum Party { None, // Party per default when there is no challenger or requester. Also used for unconclusive ruling. Requester, // Party that made the request to change a bet status. Challenger // Party that challenges the request to change a bet status. } // ************************ // // * Request Life Cycle * // // ************************ // // Changes to the bet status are made via requests for either listing or removing a bet from the Bet Curated Registry. // To make or challenge a request, a party must pay a deposit. This value will be rewarded to the party that ultimately wins a dispute. If no one challenges the request, the value will be reimbursed to the requester. // Additionally to the challenge reward, in the case a party challenges a request, both sides must fully pay the amount of arbitration fees required to raise a dispute. The party that ultimately wins the case will be reimbursed. // Finally, arbitration fees can be crowdsourced. To incentivise insurers, an additional fee stake must be deposited. Contributors that fund the side that ultimately wins a dispute will be reimbursed and rewarded with the other side's fee stake proportionally to their contribution. // In summary, costs for placing or challenging a request are the following: // - A challenge reward given to the party that wins a potential dispute. // - Arbitration fees used to pay jurors. // - A fee stake that is distributed among insurers of the side that ultimately wins a dispute. /* Structs */ struct Bet { BetStatus status; // The status of the bet. Request[] requests; // List of status change requests made for the bet. } // Some arrays below have 3 elements to map with the Party enums for better readability: // - 0: is unused, matches `Party.None`. // - 1: for `Party.Requester`. // - 2: for `Party.Challenger`. struct Request { bool disputed; // True if a dispute was raised. uint disputeID; // ID of the dispute, if any. uint submissionTime; // Time when the request was made. Used to track when the challenge period ends. bool resolved; // True if the request was executed and/or any disputes raised were resolved. address[3] parties; // Address of requester and challenger, if any. Round[] rounds; // Tracks each round of a dispute. Party ruling; // The final ruling given, if any. Arbitrator arbitrator; // The arbitrator trusted to solve disputes for this request. bytes arbitratorExtraData; // The extra data for the trusted arbitrator of this request. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side on this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint[3]) contributions; // Maps contributors to their contributions for each side. } /* Storage */ // Constants uint RULING_OPTIONS = 2; // The amount of non 0 choices the arbitrator can give. // Settings address public governor; // The address that can make governance changes to the parameters of the Bet Curated Registry. Arbitrator arbitrator; bytes public arbitratorExtraData; address public selfCommitmentRegistry; // The address of the selfCommitmentRegistry contract. uint public requesterBaseDeposit; // The base deposit to make a request. uint public challengerBaseDeposit; // The base deposit to challenge a request. uint public challengePeriodDuration; // The time before a request becomes executable if not challenged. uint public metaEvidenceUpdates; // The number of times the meta evidence has been updated. Used to track the latest meta evidence ID. // The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round. // Multipliers are in basis points. uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round. uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where there isn't a winner and loser (e.g. when it's the first round or the arbitrator ruled "refused to rule"/"could not rule"). uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. // Registry data. mapping(uint => Bet) public bets; // Maps the uint bet to the bet data. mapping(address => mapping(uint => uint)) public arbitratorDisputeIDToBetID; // Maps a dispute ID to the bet with the disputed request. uint[] public betList; // List of submitted bets. /* Modifiers */ modifier onlyGovernor {require(msg.sender == governor, "The caller must be the governor."); _;} /* Events */ /** * @dev Emitted when a party submits a new bet. * @param _betID The bet. * @param _requester The address of the party that made the request. */ event BetSubmitted(uint indexed _betID, address indexed _requester); /** @dev Emitted when a party makes a request to change a bet status. * @param _betID The bet index. * @param _registrationRequest Whether the request is a registration request. False means it is a clearing request. */ event RequestSubmitted(uint indexed _betID, bool _registrationRequest); /** * @dev Emitted when a party makes a request, dispute or appeals are raised, or when a request is resolved. * @param _requester Address of the party that submitted the request. * @param _challenger Address of the party that has challenged the request, if any. * @param _betID The address. * @param _status The status of the bet. * @param _disputed Whether the bet is disputed. * @param _appealed Whether the current round was appealed. */ event BetStatusChange( address indexed _requester, address indexed _challenger, uint indexed _betID, BetStatus _status, bool _disputed, bool _appealed ); /** @dev Emitted when a reimbursements and/or contribution rewards are withdrawn. * @param _betID The bet ID from which the withdrawal was made. * @param _contributor The address that sent the contribution. * @param _request The request from which the withdrawal was made. * @param _round The round from which the reward was taken. * @param _value The value of the reward. */ event RewardWithdrawal(uint indexed _betID, address indexed _contributor, uint indexed _request, uint _round, uint _value); /* Constructor */ /** * @dev Constructs the arbitrable token curated registry. * @param _arbitrator The trusted arbitrator to resolve potential disputes. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _registrationMetaEvidence The URI of the meta evidence object for registration requests. * @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests. * @param _governor The trusted governor of this contract. * @param _requesterBaseDeposit The base deposit to make a request. * @param _challengerBaseDeposit The base deposit to challenge a request. * @param _challengePeriodDuration The time in seconds, parties have to challenge a request. * @param _sharedStakeMultiplier Multiplier of the arbitration cost that each party must pay as fee stake for a round when there isn't a winner/loser in the previous round (e.g. when it's the first round or the arbitrator refused to or did not rule). In basis points. * @param _winnerStakeMultiplier Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. * @param _loserStakeMultiplier Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. */ constructor( Arbitrator _arbitrator, bytes memory _arbitratorExtraData, string memory _registrationMetaEvidence, string memory _clearingMetaEvidence, address _governor, uint _requesterBaseDeposit, uint _challengerBaseDeposit, uint _challengePeriodDuration, uint _sharedStakeMultiplier, uint _winnerStakeMultiplier, uint _loserStakeMultiplier ) public { emit MetaEvidence(0, _registrationMetaEvidence); emit MetaEvidence(1, _clearingMetaEvidence); governor = _governor; arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; requesterBaseDeposit = _requesterBaseDeposit; challengerBaseDeposit = _challengerBaseDeposit; challengePeriodDuration = _challengePeriodDuration; sharedStakeMultiplier = _sharedStakeMultiplier; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; } /* External and Public */ // ************************ // // * Requests * // // ************************ // /** @dev Submits a request to change an address status. Accepts enough ETH to fund a potential dispute considering the current required amount and reimburses the rest. TRUSTED. * @param _betID The address. * @param _sender The address of the sender. */ function requestStatusChange(uint _betID, address payable _sender) external payable { Bet storage bet = bets[_betID]; if (bet.requests.length == 0) { // Initial bet registration. require(msg.sender == selfCommitmentRegistry); betList.push(_betID); emit BetSubmitted(_betID, _sender); } // Update bet status. if (bet.status == BetStatus.Absent) bet.status = BetStatus.RegistrationRequested; else if (bet.status == BetStatus.Registered) bet.status = BetStatus.ClearingRequested; else revert("Bet already has a pending request."); // Setup request. Request storage request = bet.requests[bet.requests.length++]; request.parties[uint(Party.Requester)] = _sender; request.submissionTime = now; request.arbitrator = arbitrator; request.arbitratorExtraData = arbitratorExtraData; Round storage round = request.rounds[request.rounds.length++]; emit RequestSubmitted(_betID, bet.status == BetStatus.RegistrationRequested); // Amount required to fully the requester: requesterBaseDeposit + arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = request.arbitrator.arbitrationCost(request.arbitratorExtraData); uint totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(requesterBaseDeposit); contribute(round, Party.Requester, _sender, msg.value, totalCost); require(round.paidFees[uint(Party.Requester)] >= totalCost, "You must fully fund your side."); round.hasPaid[uint(Party.Requester)] = true; emit BetStatusChange( request.parties[uint(Party.Requester)], address(0x0), _betID, bet.status, false, false ); } /** @dev Get the total cost */ function getTotalCost() external view returns (uint totalCost) { uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(requesterBaseDeposit); } /** @dev Challenges the latest request of a bet. Accepts enough ETH to fund a potential dispute considering the current required amount. Reimburses unused ETH. TRUSTED. * @param _betID The bet ID with the request to challenge. * @param _evidence A link to an evidence using its URI. Ignored if not provided or if not enough funds were provided to create a dispute. */ function challengeRequest(uint _betID, string calldata _evidence) external payable { Bet storage bet = bets[_betID]; require( bet.status == BetStatus.RegistrationRequested || bet.status == BetStatus.ClearingRequested, "The bet must have a pending request." ); Request storage request = bet.requests[bet.requests.length - 1]; require(now - request.submissionTime <= challengePeriodDuration, "Challenges must occur during the challenge period."); require(!request.disputed, "The request should not have already been disputed."); // Take the deposit and save the challenger's bet. request.parties[uint(Party.Challenger)] = msg.sender; Round storage round = request.rounds[request.rounds.length - 1]; uint arbitrationCost = request.arbitrator.arbitrationCost(request.arbitratorExtraData); uint totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(challengerBaseDeposit); contribute(round, Party.Challenger, msg.sender, msg.value, totalCost); require(round.paidFees[uint(Party.Challenger)] >= totalCost, "You must fully fund your side."); round.hasPaid[uint(Party.Challenger)] = true; // Raise a dispute. request.disputeID = request.arbitrator.createDispute.value(arbitrationCost)(RULING_OPTIONS, request.arbitratorExtraData); arbitratorDisputeIDToBetID[address(request.arbitrator)][request.disputeID] = _betID; request.disputed = true; request.rounds.length++; round.feeRewards = round.feeRewards.subCap(arbitrationCost); emit Dispute( request.arbitrator, request.disputeID, bet.status == BetStatus.RegistrationRequested ? 2 * metaEvidenceUpdates : 2 * metaEvidenceUpdates + 1, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))) ); emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], _betID, bet.status, true, false ); if (bytes(_evidence).length > 0) emit Evidence(request.arbitrator, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))), msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. TRUSTED. * @param _betID The bet index. * @param _side The recipient of the contribution. */ function fundAppeal(uint _betID, Party _side) external payable { // Recipient must be either the requester or challenger. require(_side == Party.Requester || _side == Party.Challenger); // solium-disable-line error-reason Bet storage bet = bets[_betID]; require( bet.status == BetStatus.RegistrationRequested || bet.status == BetStatus.ClearingRequested, "The bet must have a pending request." ); Request storage request = bet.requests[bet.requests.length - 1]; require(request.disputed, "A dispute must have been raised to fund an appeal."); (uint appealPeriodStart, uint appealPeriodEnd) = request.arbitrator.appealPeriod(request.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Contributions must be made within the appeal period." ); // Amount required to fully fund each side: arbitration cost + (arbitration cost * multiplier) Round storage round = request.rounds[request.rounds.length - 1]; Party winner = Party(request.arbitrator.currentRuling(request.disputeID)); Party loser; if (winner == Party.Requester) loser = Party.Challenger; else if (winner == Party.Challenger) loser = Party.Requester; require(!(_side==loser) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period."); uint multiplier; if (_side == winner) multiplier = winnerStakeMultiplier; else if (_side == loser) multiplier = loserStakeMultiplier; else multiplier = sharedStakeMultiplier; uint appealCost = request.arbitrator.appealCost(request.disputeID, request.arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); contribute(round, _side, msg.sender, msg.value, totalCost); if (round.paidFees[uint(_side)] >= totalCost) round.hasPaid[uint(_side)] = true; // Raise appeal if both sides are fully funded. if (round.hasPaid[uint(Party.Challenger)] && round.hasPaid[uint(Party.Requester)]) { request.arbitrator.appeal.value(appealCost)(request.disputeID, request.arbitratorExtraData); request.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], _betID, bet.status, true, true ); } } /** @dev Reimburses contributions if no disputes were raised. If a dispute was raised, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions to a request. * @param _betID The bet index submission with the request from which to withdraw. * @param _request The request from which to withdraw. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards(address payable _beneficiary, uint _betID, uint _request, uint _round) public { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; Round storage round = request.rounds[_round]; // The request must be executed and there can be no disputes pending resolution. require(request.resolved); // solium-disable-line error-reason uint reward; if (!round.hasPaid[uint(Party.Requester)] || !round.hasPaid[uint(Party.Challenger)]) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint(Party.Requester)] + round.contributions[_beneficiary][uint(Party.Challenger)]; round.contributions[_beneficiary][uint(Party.Requester)] = 0; round.contributions[_beneficiary][uint(Party.Challenger)] = 0; } else if (request.ruling == Party.None) { // No disputes were raised, or there isn't a winner and loser. Reimburse unspent fees proportionally. uint rewardRequester = round.paidFees[uint(Party.Requester)] > 0 ? (round.contributions[_beneficiary][uint(Party.Requester)] * round.feeRewards) / (round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)]) : 0; uint rewardChallenger = round.paidFees[uint(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)]) : 0; reward = rewardRequester + rewardChallenger; round.contributions[_beneficiary][uint(Party.Requester)] = 0; round.contributions[_beneficiary][uint(Party.Challenger)] = 0; } else { // Reward the winner. reward = round.paidFees[uint(request.ruling)] > 0 ? (round.contributions[_beneficiary][uint(request.ruling)] * round.feeRewards) / round.paidFees[uint(request.ruling)] : 0; round.contributions[_beneficiary][uint(request.ruling)] = 0; } emit RewardWithdrawal(_betID, _beneficiary, _request, _round, reward); _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Withdraws rewards and reimbursements of multiple rounds at once. This function is O(n) where n is the number of rounds. This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions to the request. * @param _betID The bet index. * @param _request The request from which to withdraw contributions. * @param _cursor The round from where to start withdrawing. * @param _count Rounds greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchRoundWithdraw(address payable _beneficiary, uint _betID, uint _request, uint _cursor, uint _count) public { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; for (uint i = _cursor; i<request.rounds.length && (_count==0 || i<_count); i++) withdrawFeesAndRewards(_beneficiary, _betID, _request, i); } /** @dev Withdraws rewards and reimbursements of multiple requests at once. This function is O(n*m) where n is the number of requests and m is the number of rounds. This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions to the request. * @param _betID The bet index. * @param _cursor The request from which to start withdrawing. * @param _count Requests greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of request, iterates until the last request. * @param _roundCursor The round of each request from where to start withdrawing. * @param _roundCount Rounds greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of rounds a request has, iteration for that request will stop at the last round. */ function batchRequestWithdraw( address payable _beneficiary, uint _betID, uint _cursor, uint _count, uint _roundCursor, uint _roundCount ) external { Bet storage bet = bets[_betID]; for (uint i = _cursor; i<bet.requests.length && (_count==0 || i<_count); i++) batchRoundWithdraw(_beneficiary, _betID, i, _roundCursor, _roundCount); } /** @dev Executes a request if the challenge period passed and no one challenged the request. * @param _betID The bet index with the request to execute. */ function executeRequest(uint _betID) external { Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; require( now - request.submissionTime > challengePeriodDuration, "Time to challenge the request must have passed." ); require(!request.disputed, "The request should not be disputed."); if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Registered; else if (bet.status == BetStatus.ClearingRequested) bet.status = BetStatus.Absent; else revert("There must be a request."); request.resolved = true; address payable party = address(uint160(request.parties[uint(Party.Requester)])); withdrawFeesAndRewards(party, _betID, bet.requests.length - 1, 0); // Automatically withdraw for the requester. emit BetStatusChange( request.parties[uint(Party.Requester)], address(0x0), _betID, bet.status, false, false ); } /** @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED. * Overrides parent function to account for the situation where the winner loses a case due to paying less appeal fees than expected. * @param _disputeID ID of the dispute in the arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { Party resultRuling = Party(_ruling); uint _betID = arbitratorDisputeIDToBetID[msg.sender][_disputeID]; Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; Round storage round = request.rounds[request.rounds.length - 1]; require(_ruling <= RULING_OPTIONS); // solium-disable-line error-reason require(address(request.arbitrator) == msg.sender); // solium-disable-line error-reason require(!request.resolved); // solium-disable-line error-reason // The ruling is inverted if the loser paid its fees. if (round.hasPaid[uint(Party.Requester)] == true) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created. resultRuling = Party.Requester; else if (round.hasPaid[uint(Party.Challenger)] == true) resultRuling = Party.Challenger; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(_disputeID, uint(resultRuling)); } /** @dev Submit a reference to evidence. EVENT. * @param _betID The bet index. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _betID, string calldata _evidence) external { Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; require(!request.resolved, "The dispute must not already be resolved."); emit Evidence(request.arbitrator, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))), msg.sender, _evidence); } // ************************ // // * Governance * // // ************************ // /** @dev Change the duration of the challenge period. * @param _challengePeriodDuration The new duration of the challenge period. */ function changeTimeToChallenge(uint _challengePeriodDuration) external onlyGovernor { challengePeriodDuration = _challengePeriodDuration; } /** @dev Change the base amount required as a deposit to make a request. * @param _requesterBaseDeposit The new base amount of wei required to make a request. */ function changeRequesterBaseDeposit(uint _requesterBaseDeposit) external onlyGovernor { requesterBaseDeposit = _requesterBaseDeposit; } /** @dev Change the base amount required as a deposit to challenge a request. * @param _challengerBaseDeposit The new base amount of wei required to challenge a request. */ function changeChallengerBaseDeposit(uint _challengerBaseDeposit) external onlyGovernor { challengerBaseDeposit = _challengerBaseDeposit; } /** @dev Change the governor of the token curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the address of the goal bet registry contract. * @param _selfCommitmentRegistry The address of the new goal bet registry contract. */ function changeSelfCommitmentRegistry(address _selfCommitmentRegistry) external onlyGovernor { selfCommitmentRegistry = _selfCommitmentRegistry; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by parties when there isn't a winner or loser. * @param _sharedStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeSharedStakeMultiplier(uint _sharedStakeMultiplier) external onlyGovernor { sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by the winner of the previous round. * @param _winnerStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeWinnerStakeMultiplier(uint _winnerStakeMultiplier) external onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by the party that lost the previous round. * @param _loserStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeLoserStakeMultiplier(uint _loserStakeMultiplier) external onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; } /** @dev Change the arbitrator to be used for disputes that may be raised in the next requests. The arbitrator is trusted to support appeal periods and not reenter. * @param _arbitrator The new trusted arbitrator to be used in the next requests. * @param _arbitratorExtraData The extra data used by the new arbitrator. */ function changeArbitrator(Arbitrator _arbitrator, bytes calldata _arbitratorExtraData) external onlyGovernor { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Update the meta evidence used for disputes. * @param _registrationMetaEvidence The meta evidence to be used for future registration request disputes. * @param _clearingMetaEvidence The meta evidence to be used for future clearing request disputes. */ function changeMetaEvidence(string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence) external onlyGovernor { metaEvidenceUpdates++; emit MetaEvidence(2 * metaEvidenceUpdates, _registrationMetaEvidence); emit MetaEvidence(2 * metaEvidenceUpdates + 1, _clearingMetaEvidence); } /* Internal */ /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute(Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired) internal { // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @dev Execute the ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal { uint betID = arbitratorDisputeIDToBetID[msg.sender][_disputeID]; Bet storage bet = bets[betID]; Request storage request = bet.requests[bet.requests.length - 1]; Party winner = Party(_ruling); // Update bet state if (winner == Party.Requester) { // Execute Request if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Registered; else bet.status = BetStatus.Absent; } else { // Revert to previous state. if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Absent; else if (bet.status == BetStatus.ClearingRequested) bet.status = BetStatus.Registered; } request.resolved = true; request.ruling = Party(_ruling); // Automatically withdraw. if (winner == Party.None) { address payable requester = address(uint160(request.parties[uint(Party.Requester)])); address payable challenger = address(uint160(request.parties[uint(Party.Challenger)])); withdrawFeesAndRewards(requester, betID, bet.requests.length-1, 0); withdrawFeesAndRewards(challenger, betID, bet.requests.length-1, 0); } else { address payable winnerAddr = address(uint160(request.parties[uint(winner)])); withdrawFeesAndRewards(winnerAddr, betID, bet.requests.length-1, 0); } emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], betID, bet.status, request.disputed, false ); } /* Views */ /** @dev Return true if the bet is on the list. * @param _betID The bet index. * @return allowed True if the address is allowed, false otherwise. */ function isPermitted(uint _betID) external view returns (bool allowed) { Bet storage bet = bets[_betID]; return bet.status == BetStatus.Registered || bet.status == BetStatus.ClearingRequested; } /* Interface Views */ /** @dev Return the sum of withdrawable wei of a request an account is entitled to. This function is O(n), where n is the number of rounds of the request. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _betID The bet index to query. * @param _beneficiary The contributor for which to query. * @param _request The request from which to query for. * @return The total amount of wei available to withdraw. */ function amountWithdrawable(uint _betID, address _beneficiary, uint _request) external view returns (uint total){ Request storage request = bets[_betID].requests[_request]; if (!request.resolved) return total; for (uint i = 0; i < request.rounds.length; i++) { Round storage round = request.rounds[i]; if (!request.disputed || request.ruling == Party.None) { uint rewardRequester = round.paidFees[uint(Party.Requester)] > 0 ? (round.contributions[_beneficiary][uint(Party.Requester)] * round.feeRewards) / (round.paidFees[uint(Party.Requester)] + round.paidFees[uint(Party.Challenger)]) : 0; uint rewardChallenger = round.paidFees[uint(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint(Party.Requester)] + round.paidFees[uint(Party.Challenger)]) : 0; total += rewardRequester + rewardChallenger; } else { total += round.paidFees[uint(request.ruling)] > 0 ? (round.contributions[_beneficiary][uint(request.ruling)] * round.feeRewards) / round.paidFees[uint(request.ruling)] : 0; } } return total; } /** @dev Return the numbers of bets that were submitted. Includes bets that never made it to the list or were later removed. * @return count The numbers of bets in the list. */ function betCount() external view returns (uint count) { return betList.length; } /** @dev Gets the contributions made by a party for a given round of a request. * @param _betID The bet index. * @param _request The position of the request. * @param _round The position of the round. * @param _contributor The address of the contributor. * @return The contributions. */ function getContributions( uint _betID, uint _request, uint _round, address _contributor ) external view returns(uint[3] memory contributions) { Request storage request = bets[_betID].requests[_request]; Round storage round = request.rounds[_round]; contributions = round.contributions[_contributor]; } /** @dev Returns bet information. Includes length of requests array. * @param _betID The queried bet index. * @return The bet information. */ function getBetInfo(uint _betID) external view returns ( BetStatus status, uint numberOfRequests ) { Bet storage bet = bets[_betID]; return ( bet.status, bet.requests.length ); } /** @dev Gets information on a request made for a bet. * @param _betID The queried bet index. * @param _request The request to be queried. * @return The request information. */ function getRequestInfo(uint _betID, uint _request) external view returns ( bool disputed, uint disputeID, uint submissionTime, bool resolved, address[3] memory parties, uint numberOfRounds, Party ruling, Arbitrator arbitratorRequest, bytes memory arbitratorExtraData ) { Request storage request = bets[_betID].requests[_request]; return ( request.disputed, request.disputeID, request.submissionTime, request.resolved, request.parties, request.rounds.length, request.ruling, request.arbitrator, request.arbitratorExtraData ); } /** @dev Gets the information on a round of a request. * @param _betID The queried bet index. * @param _request The request to be queried. * @param _round The round to be queried. * @return The round information. */ function getRoundInfo(uint _betID, uint _request, uint _round) external view returns ( bool appealed, uint[3] memory paidFees, bool[3] memory hasPaid, uint feeRewards ) { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; Round storage round = request.rounds[_round]; return ( _round != (request.rounds.length-1), round.paidFees, round.hasPaid, round.feeRewards ); } } contract SelfCommitment is IArbitrable { using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. // **************************** // // * Contract variables * // // **************************** // struct Bet { string description; // alias metaevidence uint[3] period; // endBetPeriod, startClaimPeriod, endClaimPeriod uint[2] ratio; // For irrational numbers we assume that the loss of wei is negligible address[3] parties; uint[2] amount; // betterAmount (max), takerTotalAmount mapping(address => uint) amountTaker; bool isPrivate; mapping(address => bool) allowAddress; Arbitrator arbitrator; bytes arbitratorExtraData; uint[3] stakeMultiplier; Status status; // Status of the claim relative to a dispute. uint disputeID; // If dispute exists, the ID of the dispute. Round[] rounds; // Tracks each round of a dispute. Party ruling; // The final ruling given, if any. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side on this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint[3]) contributions; // Maps contributors to their contributions for each side. } Bet[] public bets; // Amount of choices to solve the dispute if needed. uint8 constant AMOUNT_OF_CHOICES = 2; // Enum relative to different periods in the case of a negotiation or dispute. enum Status {NoDispute, WaitingAsker, WaitingTaker, DisputeCreated, Resolved} // The different parties of the dispute. enum Party {None, Asker, Taker} // The different ruling for the dispute resolution. enum RulingOptions {NoRuling, AskerWins, TakerWins} // One-to-one relationship between the dispute and the bet. mapping(address => mapping(uint => uint)) public arbitratorDisputeIDtoBetID; // Settings address public governor; // The address that can make governance changes to the parameters. address public betArbitrableList; uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. // **************************** // // * Modifier * // // **************************** // modifier onlyGovernor {require(msg.sender == address(governor), "The caller must be the governor."); _;} // **************************** // // * Events * // // **************************** // /** @dev Indicate that a party has to pay a fee or would otherwise be considered as losing. * @param _transactionID The index of the transaction. * @param _party The party who has to pay. */ event HasToPayFee(uint indexed _transactionID, Party _party); /** @dev To be emitted when a party get the rewards or the deposit. * @param _id The index of the bet. * @param _party The party that paid. * @param _amount The amount paid. */ event Reward(uint indexed _id, Party _party, uint _amount); /** @dev Emitted when a reimbursements and/or contribution rewards are withdrawn. * @param _id The ID of the bet. * @param _contributor The address that sent the contribution. * @param _round The round from which the reward was taken. * @param _value The value of the reward. */ event RewardWithdrawal(uint indexed _id, address indexed _contributor, uint _round, uint _value); /* Constructor */ /** * @dev Constructs the arbitrable token curated registry. * @param _governor The trusted governor of this contract. */ constructor( address _governor ) public { governor = _governor; } // **************************** // // * Contract functions * // // * Modifying the state * // // **************************** // /** @dev To add a new bet. UNTRUSTED. * @param _description The description of the bet. * @param _period The different periods of the bet. * @param _ratio The ratio of the bet. * @param _allowAddress Addresses who are allowed to bet. Empty for all addresses. * @param _arbitrator The arbitrator of the bet. * @param _arbitratorExtraData The configuration for the arbitration. * @param _stakeMultiplier The multipler of the deposit for the different parties. */ function ask( string calldata _description, uint[3] calldata _period, uint[2] calldata _ratio, address[] calldata _allowAddress, Arbitrator _arbitrator, bytes calldata _arbitratorExtraData, uint[3] calldata _stakeMultiplier ) external payable { ArbitrableBetList betArbitrableListInstance = ArbitrableBetList(betArbitrableList); uint totalCost = betArbitrableListInstance.getTotalCost(); require(msg.value > totalCost); require(msg.value - totalCost >= 10000); require(_ratio[0] > 1); require(_ratio[0] > _ratio[1]); require(_period[0] > now); uint amountXratio1 = msg.value * _ratio[0]; // _ratio0 > (_ratio0/_ratio1) require(amountXratio1/msg.value == _ratio[0]); // To prevent multiply overflow. betArbitrableListInstance.requestStatusChange.value(totalCost)(bets.length, msg.sender); Bet storage bet = bets[bets.length++]; bet.parties[1] = msg.sender; bet.description = _description; bet.period = _period; bet.ratio = _ratio; bet.amount = [msg.value - totalCost, 0]; if (_allowAddress.length > 0) { for(uint i; i < _allowAddress.length; i++) bet.allowAddress[_allowAddress[i]] = true; bet.isPrivate = true; } bet.arbitrator = _arbitrator; bet.arbitratorExtraData = _arbitratorExtraData; bet.stakeMultiplier = _stakeMultiplier; } /** @dev To accept a bet. UNTRUSTED. * @param _id The id of the bet. */ function take( uint _id ) external payable { require(msg.value > 0); Bet storage bet = bets[_id]; require(now < bet.period[0], "Should bet before the end period bet."); require(bet.amount[0] > bet.amount[1]); if (bet.isPrivate) require(bet.allowAddress[msg.sender]); address payable taker = msg.sender; // r = bet.ratio[0] / bet.ratio[1] // maxAmountToBet = x / (r-1) - y // maxAmountToBet = x*x / (rx-x) - y uint maxAmountToBet = bet.amount[0]*bet.amount[0] / (bet.ratio[0]*bet.amount[0]/bet.ratio[1] - bet.amount[0]) - bet.amount[1]; uint amountBet = msg.value <= maxAmountToBet ? msg.value : maxAmountToBet; bet.amount[1] += amountBet; bet.amountTaker[taker] = amountBet; if (msg.value > maxAmountToBet) taker.transfer(msg.value - maxAmountToBet); } /** @dev Withdraw the bet if no one took it. TRUSTED. * @param _id The id of the bet. */ function withdraw( uint _id ) external { Bet storage bet = bets[_id]; require(now > bet.period[0], "Should end period bet finished."); if (bet.amount[1] == 0) executeRuling(_id, uint(Party.Asker)); else { uint maxAmountToTake = bet.amount[1] * bet.ratio[0] / bet.ratio[1]; uint amountToAsk = maxAmountToTake - bet.amount[1]; address payable asker = address(uint160(bet.parties[1])); require(bet.amount[0] > amountToAsk); asker.send(bet.amount[0] - amountToAsk); bet.amount[0] = amountToAsk; } } /* Section of Claims or Dispute Resolution */ /** @dev Pay the arbitration fee to claim the bet. To be called by the asker. UNTRUSTED. * Note that the arbitrator can have createDispute throw, * which will make this function throw and therefore lead to a party being timed-out. * This is not a vulnerability as the arbitrator can rule in favor of one party anyway. * @param _id The index of the bet. */ function claimAsker(uint _id) public payable { Bet storage bet = bets[_id]; require( bet.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); require(bet.parties[1] == msg.sender, "The caller must be the creator of the bet."); require(now > bet.period[1], "Should claim after the claim period start."); require(now < bet.period[2], "Should claim before the claim period end."); // Amount required to claim: arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); uint claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); // The asker must cover the claim cost. require(msg.value >= claimCost); if(bet.rounds.length == 0) bet.rounds.length++; Round storage round = bet.rounds[0]; round.hasPaid[uint(Party.Asker)] = true; contribute(round, Party.Asker, msg.sender, msg.value, claimCost); // The taker still has to pay. This can also happen if he has paid, // but arbitrationCost has increased. if (round.paidFees[uint(Party.Taker)] <= claimCost) { bet.status = Status.WaitingTaker; emit HasToPayFee(_id, Party.Taker); } else { // The taker has also paid the fee. We create the dispute raiseDispute(_id, arbitrationCost); } } /** @dev Pay the arbitration fee to claim a bet. To be called by the taker. UNTRUSTED. * @param _id The index of the claim. */ function claimTaker(uint _id) public payable { Bet storage bet = bets[_id]; require( bet.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); // NOTE: We assume that for this smart contract version, // this smart contract is vulnerable to a griefing attack. // We expect a very low ratio of griefing attack // in the majority of cases. require( bet.amountTaker[msg.sender] > 0, "The caller must be the one of the taker." ); require(now > bet.period[1], "Should claim after the claim period start."); require(now < bet.period[2], "Should claim before the claim period end."); bet.parties[2] = msg.sender; // Amount required to claim: arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); uint claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); // The taker must cover the claim cost. require(msg.value >= claimCost); if(bet.rounds.length == 0) bet.rounds.length++; Round storage round = bet.rounds[0]; round.hasPaid[uint(Party.Taker)] = true; contribute(round, Party.Taker, msg.sender, msg.value, claimCost); // The taker still has to pay. This can also happen if he has paid, // but arbitrationCost has increased. if (round.paidFees[uint(Party.Taker)] <= claimCost) { bet.status = Status.WaitingAsker; emit HasToPayFee(_id, Party.Taker); } else { // The taker has also paid the fee. We create the dispute. raiseDispute(_id, arbitrationCost); } } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute( Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired ) internal { // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Reward asker of the bet if the taker fails to pay the fee. * NOTE: The taker unspent fee are sent to the asker. * @param _id The index of the bet. */ function timeOutByAsker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingTaker, "The transaction of the bet must waiting on the taker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.AskerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); } /** @dev Pay taker if the asker fails to pay the fee. * NOTE: The asker unspent fee are sent to the taker. * @param _id The index of the claim. */ function timeOutByTaker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingAsker, "The transaction of the bet must waiting on the asker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.TakerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); } /** @dev Create a dispute. UNTRUSTED. * @param _id The index of the bet. * @param _arbitrationCost Amount to pay the arbitrator. */ function raiseDispute(uint _id, uint _arbitrationCost) internal { Bet storage bet = bets[_id]; bet.status = Status.DisputeCreated; uint disputeID = bet.arbitrator.createDispute.value(_arbitrationCost)(AMOUNT_OF_CHOICES, bet.arbitratorExtraData); arbitratorDisputeIDtoBetID[address(bet.arbitrator)][disputeID] = _id; bet.disputeID = disputeID; emit Dispute(bet.arbitrator, bet.disputeID, _id, _id); } /** @dev Submit a reference to evidence. EVENT. * @param _id The index of the claim. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _id, string memory _evidence) public { Bet storage bet = bets[_id]; require( msg.sender == bet.parties[1] || bet.amountTaker[msg.sender] > 0, "The caller must be the asker or a taker." ); require( bet.status >= Status.DisputeCreated, "The dispute has not been created yet." ); emit Evidence(bet.arbitrator, _id, msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. TRUSTED. * @param _id The ID of the bet with the request to fund. * @param _side The recipient of the contribution. */ function fundAppeal(uint _id, Party _side) external payable { // Recipient must be either the requester or challenger. require(_side == Party.Asker || _side == Party.Taker); // solium-disable-line error-reason Bet storage bet = bets[_id]; require( bet.status >= Status.DisputeCreated, "A dispute must have been raised to fund an appeal." ); (uint appealPeriodStart, uint appealPeriodEnd) = bet.arbitrator.appealPeriod(bet.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Contributions must be made within the appeal period." ); Round storage round = bet.rounds[bet.rounds.length - 1]; Party winner = Party(bet.arbitrator.currentRuling(bet.disputeID)); Party loser; if (winner == Party.Asker) loser = Party.Taker; else if (winner == Party.Taker) loser = Party.Asker; require(!(_side==loser) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period."); uint multiplier; if (_side == winner) multiplier = bet.stakeMultiplier[1]; else if (_side == loser) multiplier = bet.stakeMultiplier[2]; else multiplier = bet.stakeMultiplier[0]; uint appealCost = bet.arbitrator.appealCost(bet.disputeID, bet.arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); contribute(round, _side, msg.sender, msg.value, totalCost); if (round.paidFees[uint(_side)] >= totalCost) round.hasPaid[uint(_side)] = true; // Raise appeal if both sides are fully funded. if (round.hasPaid[uint(Party.Taker)] && round.hasPaid[uint(Party.Asker)]) { bet.arbitrator.appeal.value(appealCost)(bet.disputeID, bet.arbitratorExtraData); bet.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); } } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external { Party resultRuling = Party(_ruling); uint id = arbitratorDisputeIDtoBetID[msg.sender][_disputeID]; Bet storage bet = bets[id]; require(_ruling <= AMOUNT_OF_CHOICES); // solium-disable-line error-reason require(address(bet.arbitrator) == msg.sender); // solium-disable-line error-reason require(bet.status != Status.Resolved); // solium-disable-line error-reason Round storage round = bet.rounds[bet.rounds.length - 1]; // The ruling is inverted if the loser paid its fees. // If one side paid its fees, the ruling is in its favor. // Note that if the other side had also paid, an appeal would have been created. if (round.hasPaid[uint(Party.Asker)] == true) resultRuling = Party.Asker; else if (round.hasPaid[uint(Party.Taker)] == true) resultRuling = Party.Taker; bet.status = Status.Resolved; bet.ruling = resultRuling; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(id, uint(resultRuling)); } /** @dev Reimburses contributions if no disputes were raised. * If a dispute was raised, sends the fee stake and the reward for the winner. * @param _beneficiary The address that made contributions to a request. * @param _id The ID of the bet. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards( address payable _beneficiary, uint _id, uint _round ) public { Bet storage bet = bets[_id]; Round storage round = bet.rounds[_round]; // The request must be resolved. require(bet.status == Status.Resolved); // solium-disable-line error-reason uint reward; if (!round.hasPaid[uint(Party.Asker)] || !round.hasPaid[uint(Party.Taker)]) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint(Party.Asker)] + round.contributions[_beneficiary][uint(Party.Taker)]; round.contributions[_beneficiary][uint(Party.Asker)] = 0; round.contributions[_beneficiary][uint(Party.Taker)] = 0; if(bet.amountTaker[_beneficiary] > 0 && bet.ruling != Party.Asker) { reward += bet.amountTaker[_beneficiary] * bet.ratio[0] / bet.ratio[1]; bet.amountTaker[_beneficiary] = 0; } } else if (bet.ruling == Party.None) { // No disputes were raised, or there isn't a winner and loser. Reimburse unspent fees proportionally. uint rewardAsker = round.paidFees[uint(Party.Asker)] > 0 ? (round.contributions[_beneficiary][uint(Party.Asker)] * round.feeRewards) / (round.paidFees[uint(Party.Taker)] + round.paidFees[uint(Party.Asker)]) : 0; uint rewardTaker = round.paidFees[uint(Party.Taker)] > 0 ? (round.contributions[_beneficiary][uint(Party.Taker)] * round.feeRewards) / (round.paidFees[uint(Party.Taker)] + round.paidFees[uint(Party.Asker)]) : 0; reward = rewardAsker + rewardTaker; round.contributions[_beneficiary][uint(Party.Asker)] = 0; round.contributions[_beneficiary][uint(Party.Taker)] = 0; // Reimburse the fund bet. if(bet.amountTaker[_beneficiary] > 0) { reward += bet.amountTaker[_beneficiary]; bet.amountTaker[_beneficiary] = 0; } } else { // Reward the winner. reward = round.paidFees[uint(bet.ruling)] > 0 ? (round.contributions[_beneficiary][uint(bet.ruling)] * round.feeRewards) / round.paidFees[uint(bet.ruling)] : 0; round.contributions[_beneficiary][uint(bet.ruling)] = 0; if(bet.amountTaker[_beneficiary] > 0 && bet.ruling != Party.Asker) { reward += bet.amountTaker[_beneficiary] * bet.ratio[0] / bet.ratio[1]; bet.amountTaker[_beneficiary] = 0; } } emit RewardWithdrawal(_id, _beneficiary, _round, reward); _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Execute a ruling of a dispute. It reimburses the fee to the winning party. * @param _id The index of the bet. * @param _ruling Ruling given by the arbitrator. 1 : Reimburse the owner of the item. 2 : Pay the finder. */ function executeRuling(uint _id, uint _ruling) internal { require(_ruling <= AMOUNT_OF_CHOICES, "Invalid ruling."); Bet storage bet = bets[_id]; bet.status = Status.Resolved; address payable asker = address(uint160(bet.parties[1])); address payable taker = address(uint160(bet.parties[2])); if (_ruling == uint(Party.None)) { if(bet.amount[0] > 0) { asker.send(bet.amount[0]); bet.amount[0] = 0; } if (bet.rounds.length != 0) { withdrawFeesAndRewards(asker, _id, 0); withdrawFeesAndRewards(taker, _id, 0); } } else if (_ruling == uint(Party.Asker)) { require(bet.amount[0] > 0); asker.send(bet.amount[0] + bet.amount[1]); bet.amount[0] = 0; bet.amount[1] = 0; if (bet.rounds.length != 0) withdrawFeesAndRewards(asker, _id, 0); } else { if (bet.rounds.length != 0) withdrawFeesAndRewards(taker, _id, 0); } } /* Governance */ /** @dev Change the governor of the token curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the address of the goal bet registry contract. * @param _betArbitrableList The address of the new goal bet registry contract. */ function changeArbitrationBetList(address _betArbitrableList) external onlyGovernor { betArbitrableList = _betArbitrableList; } // **************************** // // * View functions * // // **************************** // /** @dev Get the claim cost * @param _id The index of the claim. */ function getClaimCost(uint _id) external view returns (uint claimCost) { Bet storage bet = bets[_id]; uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); } function getMaxAmountToBet( uint _id ) external view returns (uint maxAmountToBet) { Bet storage bet = bets[_id]; maxAmountToBet = bet.amount[0]*bet.amount[0] / (bet.ratio[0]*bet.amount[0] / bet.ratio[1] - bet.amount[0]) - bet.amount[1]; } /** @dev Return the values of the bets the query finds. This function is O(n), where n is the number of bets. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _cursor The bet index from which to start iterating. To start from either the oldest or newest item. * @param _count The number of bets to return. * @param _filter The filter to use. Each element of the array in sequence means: * - Include absent bets in result. * - Include registered bets in result. * - Include bets with registration requests that are not disputed in result. * - Include bets with clearing requests that are not disputed in result. * - Include disputed bets with registration requests in result. * - Include disputed bets with clearing requests in result. * - Include bets submitted by the caller. * - Include bets challenged by the caller. * - Include bets created. * - Include bets taken. * @return The values of the bets found and whether there are more bets for the current filter and sort. */ function queryBets(uint _cursor, uint _count, bool[10] calldata _filter) external view returns (uint[] memory values, bool hasMore) { values = new uint[](_count); uint index = 0; for ( uint i = _cursor == 0 ? bets.length - 1 : bets.length - 1 - _cursor; i < bets.length; i++ ) { Bet storage bet = bets[i]; ArbitrableBetList betArbitrableListInstance = ArbitrableBetList(betArbitrableList); (ArbitrableBetList.BetStatus arbitrableBetlistStatus, uint numberOfRequests) = betArbitrableListInstance.getBetInfo(i); (bool disputed, , , , address[3] memory parties, , , , ) = betArbitrableListInstance.getRequestInfo(i, numberOfRequests - 1); if ( /* solium-disable operator-whitespace */ (_filter[0] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.Absent) || (_filter[1] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.Registered) || (_filter[2] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.RegistrationRequested && !disputed) || (_filter[3] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.ClearingRequested && !disputed) || (_filter[4] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.RegistrationRequested && disputed) || (_filter[5] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.ClearingRequested && disputed) || (_filter[6] && parties[1] == msg.sender) || // My Submissions. (_filter[7] && parties[2] == msg.sender) || // My Challenges. (_filter[8] && bet.parties[1] == msg.sender) || // My bets. (_filter[9] && bet.parties[2] == msg.sender) // My taken bets. /* solium-enable operator-whitespace */ ) { if (index < _count) { values[index] = i; index++; } else { hasMore = true; break; } } } } }
Create a dispute. Must be called by the arbitrable contract. Must be paid at least arbitrationCost(). _choices Amount of choices the arbitrator can make in this dispute. When ruling ruling<=choices. _extraData Can be used to give additional info on the dispute to be created. return disputeID ID of the dispute created./ Give a ruling. UNTRUSTED. _disputeID ID of the dispute to rule. _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision"./ Give a ruling. UNTRUSTED. _disputeID ID of the dispute to rule. _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision"./ Return the status of a dispute. _disputeID ID of the dispute to rule. return status The status of the dispute./ Return the ruling of a dispute. _disputeID ID of the dispute to rule. return ruling The ruling which would or has been given./
function createDispute(uint _choices, bytes memory _extraData) public payable returns(uint disputeID) { super.createDispute(_choices, _extraData); disputeID = disputes.push(DisputeStruct({ arbitrated: Arbitrable(msg.sender), choices: _choices, fee: msg.value, ruling: 0, status: DisputeStatus.Waiting emit DisputeCreation(disputeID, Arbitrable(msg.sender)); } function _giveRuling(uint _disputeID, uint _ruling) internal { DisputeStruct storage dispute = disputes[_disputeID]; require(_ruling <= dispute.choices, "Invalid ruling."); require(dispute.status != DisputeStatus.Solved, "The dispute must not be solved already."); dispute.ruling = _ruling; dispute.status = DisputeStatus.Solved; dispute.arbitrated.rule(_disputeID,_ruling); } function giveRuling(uint _disputeID, uint _ruling) public onlyOwner { return _giveRuling(_disputeID, _ruling); } function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { return disputes[_disputeID].status; } function currentRuling(uint _disputeID) public view returns(uint ruling) { return disputes[_disputeID].ruling; } }
12,936,868
pragma solidity ^0.6.0; interface TokenInterface { function approve(address, uint) external; function transfer(address, uint) external; function deposit() external payable; function withdraw(uint) external; function balanceOf(address) external view returns (uint); } interface ManagerLike { function cdpCan(address, uint, address) external view returns (uint); function ilks(uint) external view returns (bytes32); function last(address) external view returns (uint); function count(address) external view returns (uint); function owns(uint) external view returns (address); function urns(uint) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint); function give(uint, address) external; function frob(uint, int, int) external; function flux(uint, address, uint) external; function move(uint, address, uint) external; } interface VatLike { function can(address, address) external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function dai(address) external view returns (uint); function urns(bytes32, address) external view returns (uint, uint); function frob( bytes32, address, address, address, int, int ) external; function hope(address) external; function move(address, address, uint) external; function gem(bytes32, address) external view returns (uint); } interface TokenJoinInterface { function dec() external returns (uint); function gem() external returns (TokenInterface); function join(address, uint) external payable; function exit(address, uint) external; } interface DaiJoinInterface { function vat() external returns (VatLike); function dai() external returns (TokenInterface); function join(address, uint) external payable; function exit(address, uint) external; } interface JugLike { function drip(bytes32) external returns (uint); } interface PotLike { function pie(address) external view returns (uint); function drip() external returns (uint); function join(uint) external; function exit(uint) external; } interface MemoryInterface { function getUint(uint _id) external returns (uint _num); function setUint(uint _id, uint _val) external; } interface InstaMapping { function gemJoinMapping(bytes32) external view returns (address); } interface EventInterface { function emitEvent(uint _connectorType, uint _connectorID, bytes32 _eventCode, bytes calldata _eventData) external; } interface AccountInterface { function isAuth(address _user) external view returns (bool); } contract DSMath { uint256 constant RAY = 10 ** 27; uint constant WAD = 10 ** 18; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "math-not-safe"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "math-not-safe"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = mul(_amt, 10 ** (18 - _dec)); } function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = (_amt / 10 ** (18 - _dec)); } } contract Helpers is DSMath { /** * @dev Return ETH Address. */ function getAddressETH() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } /** * @dev Return WETH Address. */ function getAddressWETH() internal pure returns (address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; } /** * @dev Return InstAaMemory Address. */ function getMemoryAddr() internal pure returns (address) { return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F; } /** * @dev Return InstaEvent Address. */ function getEventAddr() internal pure returns (address) { return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97; } /** * @dev Get Uint value from InstaMemory Contract. */ function getUint(uint getId, uint val) internal returns (uint returnVal) { returnVal = getId == 0 ? val : MemoryInterface(getMemoryAddr()).getUint(getId); } /** * @dev Set Uint value in InstaMemory Contract. */ function setUint(uint setId, uint val) internal { if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val); } /** * @dev emit event on event contract */ function emitEvent(bytes32 eventCode, bytes memory eventData) internal { (uint model, uint id) = connectorID(); EventInterface(getEventAddr()).emitEvent(model, id, eventCode, eventData); } /** * @dev Connector Details */ function connectorID() public pure returns(uint _type, uint _id) { (_type, _id) = (1, 40); } } contract MakerMCDAddresses is Helpers { /** * @dev Return Maker MCD Manager Address. */ function getMcdManager() internal pure returns (address) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } /** * @dev Return Maker MCD DAI Address. */ function getMcdDai() internal pure returns (address) { return 0x6B175474E89094C44Da98b954EedeAC495271d0F; } /** * @dev Return Maker MCD DAI_Join Address. */ function getMcdDaiJoin() internal pure returns (address) { return 0x9759A6Ac90977b93B58547b4A71c78317f391A28; } /** * @dev Return Maker MCD Jug Address. */ function getMcdJug() internal pure returns (address) { return 0x19c0976f590D67707E62397C87829d896Dc0f1F1; } /** * @dev Return Maker MCD Pot Address. */ function getMcdPot() internal pure returns (address) { return 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; } } contract MakerHelpers is MakerMCDAddresses { /** * @dev Return InstaMapping Address. */ function getMappingAddr() internal pure returns (address) { return 0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88; } /** * @dev Return Close Vault Address. */ function getGiveAddress() internal pure returns (address) { return 0x4dD58550eb15190a5B3DfAE28BB14EeC181fC267; } /** * @dev Get Vault's ilk. */ function getVaultData(ManagerLike managerContract, uint vault) internal view returns (bytes32 ilk, address urn) { ilk = managerContract.ilks(vault); urn = managerContract.urns(vault); } /** * @dev Gem Join address is ETH type collateral. */ function isEth(address tknAddr) internal pure returns (bool) { return tknAddr == getAddressWETH() ? true : false; } /** * @dev Get Vault Debt Amount. */ function _getVaultDebt( address vat, bytes32 ilk, address urn ) internal view returns (uint wad) { (, uint rate,,,) = VatLike(vat).ilks(ilk); (, uint art) = VatLike(vat).urns(ilk, urn); uint dai = VatLike(vat).dai(urn); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; wad = mul(wad, RAY) < rad ? wad + 1 : wad; } /** * @dev Get Borrow Amount. */ function _getBorrowAmt( address vat, address urn, bytes32 ilk, uint amt ) internal returns (int dart) { address jug = getMcdJug(); uint rate = JugLike(jug).drip(ilk); uint dai = VatLike(vat).dai(urn); if (dai < mul(amt, RAY)) { dart = toInt(sub(mul(amt, RAY), dai) / rate); dart = mul(uint(dart), rate) < mul(amt, RAY) ? dart + 1 : dart; } } /** * @dev Get Payback Amount. */ function _getWipeAmt( address vat, uint amt, address urn, bytes32 ilk ) internal view returns (int dart) { (, uint rate,,,) = VatLike(vat).ilks(ilk); (, uint art) = VatLike(vat).urns(ilk, urn); dart = toInt(amt / rate); dart = uint(dart) <= art ? - dart : - toInt(art); } /** * @dev Convert String to bytes32. */ function stringToBytes32(string memory str) internal pure returns (bytes32 result) { require(bytes(str).length != 0, "string-empty"); // solium-disable-next-line security/no-inline-assembly assembly { result := mload(add(str, 32)) } } /** * @dev Get vault ID. If `vault` is 0, get last opened vault. */ function getVault(ManagerLike managerContract, uint vault) internal view returns (uint _vault) { if (vault == 0) { require(managerContract.count(address(this)) > 0, "no-vault-opened"); _vault = managerContract.last(address(this)); } else { _vault = vault; } } } contract EventHelper is MakerHelpers { event LogOpen(uint256 indexed vault, bytes32 indexed ilk); event LogClose(uint256 indexed vault, bytes32 indexed ilk); event LogTransfer(uint256 indexed vault, bytes32 indexed ilk, address newOwner); event LogDeposit(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId); event LogWithdraw(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId); event LogBorrow(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId); event LogPayback(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId); function emitLogDeposit(uint256 vault, bytes32 ilk, uint256 tokenAmt, uint256 getId, uint256 setId) internal { emit LogDeposit(vault, ilk, tokenAmt, getId, setId); bytes32 _eventCode = keccak256("LogDeposit(uint256,bytes32,uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(vault, ilk, tokenAmt, getId, setId); emitEvent(_eventCode, _eventParam); } function emitLogBorrow(uint256 vault, bytes32 ilk, uint256 tokenAmt, uint256 getId, uint256 setId) internal { emit LogBorrow(vault, ilk, tokenAmt, getId, setId); bytes32 _eventCode = keccak256("LogBorrow(uint256,bytes32,uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(vault, ilk, tokenAmt, getId, setId); emitEvent(_eventCode, _eventParam); } } contract BasicResolver is EventHelper { /** * @dev Open Vault * @param colType Type of Collateral.(eg: 'ETH-A') */ function open(string calldata colType) external payable returns (uint vault) { bytes32 ilk = stringToBytes32(colType); require(InstaMapping(getMappingAddr()).gemJoinMapping(ilk) != address(0), "wrong-col-type"); vault = ManagerLike(getMcdManager()).open(ilk, address(this)); emit LogOpen(vault, ilk); bytes32 _eventCode = keccak256("LogOpen(uint256,bytes32)"); bytes memory _eventParam = abi.encode(vault, ilk); emitEvent(_eventCode, _eventParam); } /** * @dev Close Vault * @param vault Vault ID to close. */ function close(uint vault) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); uint _vault = getVault(managerContract, vault); (bytes32 ilk, address urn) = getVaultData(managerContract, _vault); (uint ink, uint art) = VatLike(managerContract.vat()).urns(ilk, urn); require(ink == 0 && art == 0, "vault-has-assets"); require(managerContract.owns(_vault) == address(this), "not-owner"); managerContract.give(_vault, getGiveAddress()); emit LogClose(_vault, ilk); bytes32 _eventCode = keccak256("LogClose(uint256,bytes32)"); bytes memory _eventParam = abi.encode(_vault, ilk); emitEvent(_eventCode, _eventParam); } /** * @dev Deposit ETH/ERC20_Token Collateral. * @param vault Vault ID. * @param amt token amount to deposit. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function deposit( uint vault, uint amt, uint getId, uint setId ) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); uint _amt = getUint(getId, amt); uint _vault = getVault(managerContract, vault); (bytes32 ilk, address urn) = getVaultData(managerContract, _vault); address colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk); TokenJoinInterface tokenJoinContract = TokenJoinInterface(colAddr); TokenInterface tokenContract = tokenJoinContract.gem(); if (isEth(address(tokenContract))) { _amt = _amt == uint(-1) ? address(this).balance : _amt; tokenContract.deposit.value(_amt)(); } else { _amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt; } tokenContract.approve(address(colAddr), _amt); tokenJoinContract.join(address(this), _amt); VatLike(managerContract.vat()).frob( ilk, urn, address(this), address(this), toInt(convertTo18(tokenJoinContract.dec(), _amt)), 0 ); setUint(setId, _amt); emitLogDeposit(_vault, ilk, _amt, getId, setId); } /** * @dev Withdraw ETH/ERC20_Token Collateral. * @param vault Vault ID. * @param amt token amount to withdraw. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function withdraw( uint vault, uint amt, uint getId, uint setId ) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); uint _amt = getUint(getId, amt); uint _vault = getVault(managerContract, vault); (bytes32 ilk, address urn) = getVaultData(managerContract, _vault); address colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk); TokenJoinInterface tokenJoinContract = TokenJoinInterface(colAddr); uint _amt18; if (_amt == uint(-1)) { (_amt18,) = VatLike(managerContract.vat()).urns(ilk, urn); _amt = convert18ToDec(tokenJoinContract.dec(), _amt18); } else { _amt18 = convertTo18(tokenJoinContract.dec(), _amt); } managerContract.frob( _vault, -toInt(_amt18), 0 ); managerContract.flux( _vault, address(this), _amt18 ); TokenInterface tokenContract = tokenJoinContract.gem(); if (isEth(address(tokenContract))) { tokenJoinContract.exit(address(this), _amt); tokenContract.withdraw(_amt); } else { tokenJoinContract.exit(address(this), _amt); } setUint(setId, _amt); emit LogWithdraw(_vault, ilk, _amt, getId, setId); bytes32 _eventCode = keccak256("LogWithdraw(uint256,bytes32,uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(_vault, ilk, _amt, getId, setId); emitEvent(_eventCode, _eventParam); } /** * @dev Borrow DAI. * @param vault Vault ID. * @param amt token amount to borrow. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function borrow( uint vault, uint amt, uint getId, uint setId ) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); uint _amt = getUint(getId, amt); uint _vault = getVault(managerContract, vault); (bytes32 ilk, address urn) = getVaultData(managerContract, _vault); address daiJoin = getMcdDaiJoin(); VatLike vatContract = VatLike(managerContract.vat()); managerContract.frob( _vault, 0, _getBorrowAmt( address(vatContract), urn, ilk, _amt ) ); managerContract.move( _vault, address(this), toRad(_amt) ); if (vatContract.can(address(this), address(daiJoin)) == 0) { vatContract.hope(daiJoin); } DaiJoinInterface(daiJoin).exit(address(this), _amt); setUint(setId, _amt); emitLogBorrow(_vault, ilk, _amt, getId, setId); } /** * @dev Payback borrowed DAI. * @param vault Vault ID. * @param amt token amount to payback. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function payback( uint vault, uint amt, uint getId, uint setId ) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); uint _amt = getUint(getId, amt); uint _vault = getVault(managerContract, vault); (bytes32 ilk, address urn) = getVaultData(managerContract, _vault); address vat = managerContract.vat(); uint _maxDebt = _getVaultDebt(vat, ilk, urn); _amt = _amt == uint(-1) ? _maxDebt : _amt; require(_maxDebt >= _amt, "paying-excess-debt"); DaiJoinInterface daiJoinContract = DaiJoinInterface(getMcdDaiJoin()); daiJoinContract.dai().approve(getMcdDaiJoin(), _amt); daiJoinContract.join(urn, _amt); managerContract.frob( _vault, 0, _getWipeAmt( vat, VatLike(vat).dai(urn), urn, ilk ) ); setUint(setId, _amt); emit LogPayback(_vault, ilk, _amt, getId, setId); bytes32 _eventCode = keccak256("LogPayback(uint256,bytes32,uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(_vault, ilk, _amt, getId, setId); emitEvent(_eventCode, _eventParam); } } contract BasicExtraResolver is BasicResolver { event LogWithdrawLiquidated(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId); event LogExitDai(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId); /** * @dev Withdraw leftover ETH/ERC20_Token after Liquidation. * @param vault Vault ID. * @param amt token amount to Withdraw. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function withdrawLiquidated( uint vault, uint amt, uint getId, uint setId ) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); uint _amt = getUint(getId, amt); (bytes32 ilk, address urn) = getVaultData(managerContract, vault); address colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk); TokenJoinInterface tokenJoinContract = TokenJoinInterface(colAddr); uint _amt18; if (_amt == uint(-1)) { _amt18 = VatLike(managerContract.vat()).gem(ilk, urn); _amt = convert18ToDec(tokenJoinContract.dec(), _amt); } else { _amt18 = convertTo18(tokenJoinContract.dec(), _amt); } managerContract.flux( vault, address(this), _amt18 ); TokenInterface tokenContract = tokenJoinContract.gem(); tokenJoinContract.exit(address(this), _amt); if (isEth(address(tokenContract))) { tokenContract.withdraw(_amt); } setUint(setId, _amt); emit LogWithdrawLiquidated(vault, ilk, _amt, getId, setId); bytes32 _eventCode = keccak256("LogWithdrawLiquidated(uint256,bytes32,uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(vault, ilk, _amt, getId, setId); emitEvent(_eventCode, _eventParam); } struct MakerData { uint _vault; address colAddr; address daiJoin; TokenJoinInterface tokenJoinContract; VatLike vatContract; TokenInterface tokenContract; } /** * @dev Deposit ETH/ERC20_Token Collateral and Borrow DAI. * @param vault Vault ID. * @param depositAmt token deposit amount to Withdraw. * @param borrowAmt token borrow amount to Withdraw. * @param getIdDeposit Get deposit token amount at this ID from `InstaMemory` Contract. * @param getIdBorrow Get borrow token amount at this ID from `InstaMemory` Contract. * @param setIdDeposit Set deposit token amount at this ID in `InstaMemory` Contract. * @param setIdBorrow Set borrow token amount at this ID in `InstaMemory` Contract. */ function depositAndBorrow( uint vault, uint depositAmt, uint borrowAmt, uint getIdDeposit, uint getIdBorrow, uint setIdDeposit, uint setIdBorrow ) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); MakerData memory makerData; uint _amtDeposit = getUint(getIdDeposit, depositAmt); uint _amtBorrow = getUint(getIdBorrow, borrowAmt); makerData._vault = getVault(managerContract, vault); (bytes32 ilk, address urn) = getVaultData(managerContract, makerData._vault); makerData.colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk); makerData.tokenJoinContract = TokenJoinInterface(makerData.colAddr); makerData.vatContract = VatLike(managerContract.vat()); makerData.daiJoin = getMcdDaiJoin(); makerData.tokenContract = makerData.tokenJoinContract.gem(); if (isEth(address(makerData.tokenContract))) { _amtDeposit = _amtDeposit == uint(-1) ? address(this).balance : _amtDeposit; makerData.tokenContract.deposit.value(_amtDeposit)(); } else { _amtDeposit = _amtDeposit == uint(-1) ? makerData.tokenContract.balanceOf(address(this)) : _amtDeposit; } makerData.tokenContract.approve(address(makerData.colAddr), _amtDeposit); makerData.tokenJoinContract.join(urn, _amtDeposit); managerContract.frob( makerData._vault, toInt(convertTo18(makerData.tokenJoinContract.dec(), _amtDeposit)), _getBorrowAmt( address(makerData.vatContract), urn, ilk, _amtBorrow ) ); managerContract.move( makerData._vault, address(this), toRad(_amtBorrow) ); if (makerData.vatContract.can(address(this), address(makerData.daiJoin)) == 0) { makerData.vatContract.hope(makerData.daiJoin); } DaiJoinInterface(makerData.daiJoin).exit(address(this), _amtBorrow); setUint(setIdDeposit, _amtDeposit); setUint(setIdBorrow, _amtBorrow); emitLogDeposit(makerData._vault, ilk, _amtDeposit, getIdDeposit, setIdDeposit); emitLogBorrow(makerData._vault, ilk, _amtBorrow, getIdBorrow, setIdBorrow); } /** * @dev Exit DAI from urn. * @param vault Vault ID. * @param amt token amount to exit. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function exitDai( uint vault, uint amt, uint getId, uint setId ) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); uint _amt = getUint(getId, amt); uint _vault = getVault(managerContract, vault); (bytes32 ilk, address urn) = getVaultData(managerContract, _vault); address daiJoin = getMcdDaiJoin(); VatLike vatContract = VatLike(managerContract.vat()); if(_amt == uint(-1)) { _amt = vatContract.dai(urn); _amt = _amt / 10 ** 27; } managerContract.move( _vault, address(this), toRad(_amt) ); if (vatContract.can(address(this), address(daiJoin)) == 0) { vatContract.hope(daiJoin); } DaiJoinInterface(daiJoin).exit(address(this), _amt); setUint(setId, _amt); emit LogExitDai(_vault, ilk, _amt, getId, setId); bytes32 _eventCode = keccak256("LogExitDai(uint256,bytes32,uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(_vault, ilk, _amt, getId, setId); (uint _type, uint _id) = connectorID(); EventInterface(getEventAddr()).emitEvent(_type, _id, _eventCode, _eventParam); } } contract DsrResolver is BasicExtraResolver { event LogDepositDai(uint256 tokenAmt, uint256 getId, uint256 setId); event LogWithdrawDai(uint256 tokenAmt, uint256 getId, uint256 setId); /** * @dev Deposit DAI in DSR. * @param amt DAI amount to deposit. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function depositDai( uint amt, uint getId, uint setId ) external payable { uint _amt = getUint(getId, amt); address pot = getMcdPot(); address daiJoin = getMcdDaiJoin(); DaiJoinInterface daiJoinContract = DaiJoinInterface(daiJoin); _amt = _amt == uint(-1) ? daiJoinContract.dai().balanceOf(address(this)) : _amt; VatLike vat = daiJoinContract.vat(); PotLike potContract = PotLike(pot); uint chi = potContract.drip(); daiJoinContract.dai().approve(daiJoin, _amt); daiJoinContract.join(address(this), _amt); if (vat.can(address(this), address(pot)) == 0) { vat.hope(pot); } potContract.join(mul(_amt, RAY) / chi); setUint(setId, _amt); emit LogDepositDai(_amt, getId, setId); bytes32 _eventCode = keccak256("LogDepositDai(uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(_amt, getId, setId); emitEvent(_eventCode, _eventParam); } /** * @dev Withdraw DAI from DSR. * @param amt DAI amount to withdraw. * @param getId Get token amount at this ID from `InstaMemory` Contract. * @param setId Set token amount at this ID in `InstaMemory` Contract. */ function withdrawDai( uint amt, uint getId, uint setId ) external payable { address daiJoin = getMcdDaiJoin(); uint _amt = getUint(getId, amt); DaiJoinInterface daiJoinContract = DaiJoinInterface(daiJoin); VatLike vat = daiJoinContract.vat(); PotLike potContract = PotLike(getMcdPot()); uint chi = potContract.drip(); uint pie; if (_amt == uint(-1)) { pie = potContract.pie(address(this)); _amt = mul(chi, pie) / RAY; } else { pie = mul(_amt, RAY) / chi; } potContract.exit(pie); uint bal = vat.dai(address(this)); if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } daiJoinContract.exit( address(this), bal >= mul(_amt, RAY) ? _amt : bal / RAY ); setUint(setId, _amt); emit LogWithdrawDai(_amt, getId, setId); bytes32 _eventCode = keccak256("LogWithdrawDai(uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(_amt, getId, setId); emitEvent(_eventCode, _eventParam); } } contract ConnectMaker is DsrResolver { string public constant name = "MakerDao-v1.3"; }
Borrow DAI. vault Vault ID. amt token amount to borrow. getId Get token amount at this ID from `InstaMemory` Contract. setId Set token amount at this ID in `InstaMemory` Contract./
function borrow( uint vault, uint amt, uint getId, uint setId ) external payable { ManagerLike managerContract = ManagerLike(getMcdManager()); uint _amt = getUint(getId, amt); uint _vault = getVault(managerContract, vault); (bytes32 ilk, address urn) = getVaultData(managerContract, _vault); address daiJoin = getMcdDaiJoin(); VatLike vatContract = VatLike(managerContract.vat()); managerContract.frob( _vault, 0, _getBorrowAmt( address(vatContract), urn, ilk, _amt ) ); managerContract.move( _vault, address(this), toRad(_amt) ); if (vatContract.can(address(this), address(daiJoin)) == 0) { vatContract.hope(daiJoin); } DaiJoinInterface(daiJoin).exit(address(this), _amt); setUint(setId, _amt); emitLogBorrow(_vault, ilk, _amt, getId, setId); }
2,430,015
./partial_match/1/0x7B9a3a9F8cdE5582b7639eeE88225d4D59476e45/sources/XCEO.sol
generate the uniswap pair path of token -> weth make the swap
function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); }
2,630,528
pragma solidity ^0.4.18; contract MyToken { string public name = "Test"; string public symbol = "TEST"; uint8 public decimals = 8; uint256 public initialSupply = 200000000; uint256 public totalSupply; mapping (address => uint256) public balanceOf; /* Initializes contract with initial supply tokens to the creator of the contract */ function MyToken() public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; } /* Send coins */ function transfer(address _to, uint256 _value) public { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient } }
Initializes contract with initial supply tokens to the creator of the contract /
function MyToken() public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; }
2,396,849
pragma solidity 0.6.1; import "./ownable.sol"; /** * @dev The contract has an owner address, and provides basic authorization control which * simplifies the implementation of user permissions. This contract upgrades Ownable contracts with * additional claim step which makes ownership transfers less prone to errors. */ contract Claimable is Ownable { /** * @dev Error constants. */ string constant NOT_PENDING_OWNER = "019001"; /** * @dev Address of pending owner or zero address if there is no pending owner. */ address public pendingOwner; /** * @dev An event which is triggered when the owner is changed. * @param previousOwner The address of the previous owner. * @param newOwner The address of the new owner. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Allows the current owner to give new owner the ability to claim the ownership of the contract. * This differs from the Owner's function in that it allows setting pedingOwner address to 0x0, * which effectively cancels an active claim. * @param _newOwner The address which can claim ownership of the contract. */ function transferOwnership( address _newOwner ) public override onlyOwner { pendingOwner = _newOwner; } /** * @dev Allows the current pending owner to claim the ownership of the contract. It emits * OwnershipTransferred event and resets pending owner to 0. */ function claimOwnership() public { require(msg.sender == pendingOwner, NOT_PENDING_OWNER); address previousOwner = owner; owner = pendingOwner; pendingOwner = address(0); emit OwnershipTransferred(previousOwner, owner); } }
Allows the current pending owner to claim the ownership of the contract. It emits OwnershipTransferred event and resets pending owner to 0./
function claimOwnership() public { require(msg.sender == pendingOwner, NOT_PENDING_OWNER); address previousOwner = owner; owner = pendingOwner; pendingOwner = address(0); emit OwnershipTransferred(previousOwner, owner); }
1,012,121
pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./PLGToken.sol"; import "./Whitelist.sol"; /// @title Pledgecamp Crowdsale /// @author Sam Pullman /// @notice Capped crowdsale with bonuses for the Pledgecamp platform contract PLGCrowdsale is Ownable { using SafeMath for uint256; /// @notice Indicates successful token purchase /// @param buyer Fund provider for the token purchase. Must either be `owner` or equal to `beneficiary` /// @param beneficiary Account that ultimately receives purchased tokens /// @param value Amount in wei of investment /// @param tokenAmount Number of tokens purchased (not including bonus) /// @param bonusAmount Number of bonus tokens received event TokenPurchase(address indexed buyer, address indexed beneficiary, uint256 value, uint256 tokenAmount, uint256 bonusAmount); /// @notice Emitted when the ETH to PLG exchange rate has been updated /// @param oldRate The previous exchange rate /// @param newRate The new exchange rate event ExchangeRateUpdated(uint256 oldRate, uint256 newRate); /// @notice Emitted when the crowdsale ends event Closed(); /// True if the sale is active bool public saleActive; /// ERC20 token the crowdsale is based on PLGToken plgToken; /// Timestamp for when the crowdsale may start uint256 public startTime; /// Timestamp set when crowdsale purchasing stops uint256 public endTime; /// Token to ether conversion rate uint256 public tokensPerEther; /// Amount raised so far in wei uint256 public amountRaised; /// The minimum purchase amount in wei uint256 public minimumPurchase; /// The address from which bonus tokens are distributed address public bonusPool; /// The strategy for assigning bonus tokens from bonusPool and assigning vesting contracts Whitelist whitelist; /// @notice Constructor for the Pledgecamp crowdsale contract /// @param _plgToken ERC20 token contract used in the crowdsale /// @param _startTime Timestamp for when the crowdsale may start /// @param _rate Token to ether conversion rate /// @param _minimumPurchase The minimum purchase amount in wei constructor(address _plgToken, uint256 _startTime, uint256 _rate, uint256 _minimumPurchase) public { require(_startTime >= now); require(_rate > 0); require(_plgToken != address(0)); startTime = _startTime; tokensPerEther = _rate; minimumPurchase = _minimumPurchase; plgToken = PLGToken(_plgToken); } /// @notice Set the address of the bonus pool, which provides tokens /// @notice during bonus periods if it contains sufficient PLG /// @param _bonusPool Address of PLG holder function setBonusPool(address _bonusPool) public onlyOwner { bonusPool = _bonusPool; } /// @notice Set the contract that whitelists and calculates how many bonus tokens to award each purchase. /// @param _whitelist The address of the whitelist, which must be a `Whitelist` function setWhitelist(address _whitelist) public onlyOwner { require(_whitelist != address(0)); whitelist = Whitelist(_whitelist); } /// @notice Starts the crowdsale under appropriate conditions function start() public onlyOwner { require(!saleActive); require(now > startTime); require(endTime == 0); require(plgToken.initialized()); require(plgToken.lockExceptions(address(this))); require(bonusPool != address(0)); require(whitelist != address(0)); saleActive = true; } /// @notice End the crowdsale if the sale is active /// @notice Transfer remaining tokens to reserve pool function end() public onlyOwner { require(saleActive); require(bonusPool != address(0)); saleActive = false; endTime = now; withdrawTokens(); owner.transfer(address(this).balance); } /// @notice Withdraw crowdsale ETH to owner wallet function withdrawEth() public onlyOwner { owner.transfer(address(this).balance); } /// @notice Send remaining crowdsale tokens to `bonusPool` after sale is over function withdrawTokens() public onlyOwner { require(!saleActive); uint256 remainingTokens = plgToken.balanceOf(this); plgToken.transfer(bonusPool, remainingTokens); } /// Default function tries to make a token purchase function () external payable { buyTokensInternal(msg.sender); } /// @notice Public crowdsale purchase method function buyTokens() external payable { buyTokensInternal(msg.sender); } /// @notice Owner only method for purchasing on behalf of another person /// @param beneficiary Address to receive the tokens function buyTokensFor(address beneficiary) external payable onlyOwner { require(beneficiary != address(0)); buyTokensInternal(beneficiary); } /// @notice Main crowdsale purchase method, which validates the purchase and assigns bonuses /// @param beneficiary Address to receive the tokens function buyTokensInternal(address beneficiary) private { require(whitelist != address(0)); require(bonusPool != address(0)); require(validPurchase(msg.value)); uint256 weiAmount = msg.value; // This is the whitelist/max purchase check require(whitelist.isValidPurchase(beneficiary, weiAmount)); // Calculate the amount of PLG that's been purchased uint256 tokens = weiAmount.mul(tokensPerEther); // update state amountRaised = amountRaised.add(weiAmount); // Record the purchase in the whitelist contract whitelist.recordPurchase(beneficiary, weiAmount); plgToken.transfer(beneficiary, tokens); uint256 bonusPercent = whitelist.getBonusPercent(beneficiary); uint256 bonusTokens = tokens.mul(bonusPercent) / 100; if(bonusTokens > 0) { plgToken.transferFrom(bonusPool, beneficiary, bonusTokens); } emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, bonusTokens); } /// @notice Set a new ETH to PLG exchange rate /// @param _tokensPerEther Exchange rate function setExchangeRate(uint256 _tokensPerEther) external onlyOwner { emit ExchangeRateUpdated(tokensPerEther, _tokensPerEther); tokensPerEther = _tokensPerEther; } /// @notice Check various conditions to determine whether a purchase is currently valid /// @param amount The amount of tokens to be purchased function validPurchase(uint256 amount) public view returns (bool) { bool nonZeroPurchase = amount != 0; bool isMinPurchase = (amount >= minimumPurchase); return saleActive && nonZeroPurchase && isMinPurchase; } }
Check various conditions to determine whether a purchase is currently valid amount The amount of tokens to be purchased
function validPurchase(uint256 amount) public view returns (bool) { bool nonZeroPurchase = amount != 0; bool isMinPurchase = (amount >= minimumPurchase); return saleActive && nonZeroPurchase && isMinPurchase; }
6,427,167
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../../openzeppelin/contracts-upgradeable/math/SignedSafeMathUpgradeable.sol"; import "../../openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "../interface/IAccessControl.sol"; import "../interface/IPoolCreator.sol"; import "../interface/IGovernor.sol"; import "../interface/ISymbolService.sol"; import "../libraries/SafeMathExt.sol"; import "../libraries/OrderData.sol"; import "../libraries/Utils.sol"; import "./AMMModule.sol"; import "./CollateralModule.sol"; import "./MarginAccountModule.sol"; import "./PerpetualModule.sol"; import "../Type.sol"; library LiquidityPoolModule { using SafeCastUpgradeable for uint256; using SafeCastUpgradeable for int256; using SafeMathExt for int256; using SafeMathUpgradeable for uint256; using SignedSafeMathUpgradeable for int256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using OrderData for uint32; using AMMModule for LiquidityPoolStorage; using CollateralModule for LiquidityPoolStorage; using MarginAccountModule for PerpetualStorage; using PerpetualModule for PerpetualStorage; uint256 public constant OPERATOR_CHECK_IN_TIMEOUT = 10 days; uint256 public constant MAX_PERPETUAL_COUNT = 48; event AddLiquidity( address indexed trader, int256 addedCash, int256 mintedShare, int256 addedPoolMargin ); event RemoveLiquidity( address indexed trader, int256 returnedCash, int256 burnedShare, int256 removedPoolMargin ); event UpdatePoolMargin(int256 poolMargin); event TransferOperatorTo(address indexed newOperator); event ClaimOperator(address indexed newOperator); event RevokeOperator(); event SetLiquidityPoolParameter(int256[2] value); event CreatePerpetual( uint256 perpetualIndex, address governor, address shareToken, address operator, address oracle, address collateral, int256[9] baseParams, int256[8] riskParams ); event RunLiquidityPool(); event OperatorCheckIn(address indexed operator); event DonateInsuranceFund(int256 amount); event TransferExcessInsuranceFundToLP(int256 amount); event SetTargetLeverage(address indexed trader, int256 targetLeverage); event SetKeeper(address indexed previousKeeper, address indexed newKeeper); /** * @dev Get the vault's address of the liquidity pool * * @param liquidityPool The reference of liquidity pool storage. * @return vault The vault's address of the liquidity pool */ function getVault(LiquidityPoolStorage storage liquidityPool) public view returns (address vault) { vault = IPoolCreator(liquidityPool.creator).getVault(); } function getOperator(LiquidityPoolStorage storage liquidityPool) internal view returns (address operator) { return block.timestamp <= liquidityPool.operatorExpiration ? liquidityPool.operator : address(0); } /** * @dev Get the vault fee rate of the liquidity pool * * @param liquidityPool The reference of liquidity pool storage. * @return vaultFeeRate The vault fee rate. */ function getVaultFeeRate(LiquidityPoolStorage storage liquidityPool) public view returns (int256 vaultFeeRate) { vaultFeeRate = IPoolCreator(liquidityPool.creator).getVaultFeeRate(); } /** * @dev Get the available pool cash(collateral) of the liquidity pool excluding the specific perpetual. Available cash * in a perpetual means: margin - initial margin * * @param liquidityPool The reference of liquidity pool storage. * @param exclusiveIndex The index of perpetual in the liquidity pool to exclude, * set to liquidityPool.perpetualCount to skip excluding. * @return availablePoolCash The available pool cash(collateral) of the liquidity pool excluding the specific perpetual */ function getAvailablePoolCash( LiquidityPoolStorage storage liquidityPool, uint256 exclusiveIndex ) public view returns (int256 availablePoolCash) { uint256 length = liquidityPool.perpetualCount; for (uint256 i = 0; i < length; i++) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[i]; if (i == exclusiveIndex || perpetual.state != PerpetualState.NORMAL) { continue; } int256 markPrice = perpetual.getMarkPrice(); availablePoolCash = availablePoolCash.add( perpetual.getMargin(address(this), markPrice).sub( perpetual.getInitialMargin(address(this), markPrice) ) ); } return availablePoolCash.add(liquidityPool.poolCash); } /** * @dev Get the available pool cash(collateral) of the liquidity pool. * Sum of available cash of AMM in every perpetual in the liquidity pool, and add the pool cash. * * @param liquidityPool The reference of liquidity pool storage. * @return availablePoolCash The available pool cash(collateral) of the liquidity pool */ function getAvailablePoolCash(LiquidityPoolStorage storage liquidityPool) public view returns (int256 availablePoolCash) { return getAvailablePoolCash(liquidityPool, liquidityPool.perpetualCount); } /** * @dev Check if AMM is maintenance margin safe in the perpetual, need to rebalance before checking. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in the liquidity pool. * @return isSafe True if AMM is maintenance margin safe in the perpetual. */ function isAMMMaintenanceMarginSafe( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex ) public returns (bool isSafe) { rebalance(liquidityPool, perpetualIndex); PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; isSafe = liquidityPool.perpetuals[perpetualIndex].isMaintenanceMarginSafe( address(this), perpetual.getMarkPrice() ); } /** * @dev Check if Trader is maintenance margin safe in the perpetual, need to rebalance before checking. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in the liquidity pool. * @param trader The address of the trader * @param tradeAmount The amount of positions actually traded in the transaction * @return isSafe True if Trader is maintenance margin safe in the perpetual. */ function isTraderMarginSafe( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 tradeAmount ) public view returns (bool isSafe) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; bool hasOpened = Utils.hasOpenedPosition(perpetual.getPosition(trader), tradeAmount); int256 markPrice = perpetual.getMarkPrice(); return hasOpened ? perpetual.isInitialMarginSafe(trader, markPrice) : perpetual.isMarginSafe(trader, markPrice); } /** * @dev Initialize the liquidity pool and set up its configuration. * * @param liquidityPool The reference of liquidity pool storage. * @param collateral The collateral's address of the liquidity pool. * @param collateralDecimals The collateral's decimals of the liquidity pool. * @param operator The operator's address of the liquidity pool. * @param governor The governor's address of the liquidity pool. * @param initData The byte array contains data to initialze new created liquidity pool. */ function initialize( LiquidityPoolStorage storage liquidityPool, address creator, address collateral, uint256 collateralDecimals, address operator, address governor, bytes memory initData ) public { require(collateral != address(0), "collateral is invalid"); require(governor != address(0), "governor is invalid"); (bool isFastCreationEnabled, int256 insuranceFundCap) = abi.decode(initData, (bool, int256)); liquidityPool.initializeCollateral(collateral, collateralDecimals); liquidityPool.creator = creator; IPoolCreator poolCreator = IPoolCreator(creator); liquidityPool.accessController = poolCreator.getAccessController(); liquidityPool.operator = operator; liquidityPool.operatorExpiration = block.timestamp.add(OPERATOR_CHECK_IN_TIMEOUT); liquidityPool.governor = governor; liquidityPool.shareToken = governor; liquidityPool.isFastCreationEnabled = isFastCreationEnabled; liquidityPool.insuranceFundCap = insuranceFundCap; } /** * @dev Create and initialize new perpetual in the liquidity pool. Can only called by the operator * if the liquidity pool is running or isFastCreationEnabled is set to true. * Otherwise can only called by the governor * @param liquidityPool The reference of liquidity pool storage. * @param oracle The oracle's address of the perpetual * @param baseParams The base parameters of the perpetual * @param riskParams The risk parameters of the perpetual, must between minimum value and maximum value * @param minRiskParamValues The risk parameters' minimum values of the perpetual * @param maxRiskParamValues The risk parameters' maximum values of the perpetual */ function createPerpetual( LiquidityPoolStorage storage liquidityPool, address oracle, int256[9] calldata baseParams, int256[8] calldata riskParams, int256[8] calldata minRiskParamValues, int256[8] calldata maxRiskParamValues ) public { require( liquidityPool.perpetualCount < MAX_PERPETUAL_COUNT, "perpetual count exceeds limit" ); uint256 perpetualIndex = liquidityPool.perpetualCount; PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; perpetual.initialize( perpetualIndex, oracle, baseParams, riskParams, minRiskParamValues, maxRiskParamValues ); ISymbolService service = ISymbolService(IPoolCreator(liquidityPool.creator).getSymbolService()); service.allocateSymbol(address(this), perpetualIndex); if (liquidityPool.isRunning) { perpetual.setNormalState(); } liquidityPool.perpetualCount++; emit CreatePerpetual( perpetualIndex, liquidityPool.governor, liquidityPool.shareToken, getOperator(liquidityPool), oracle, liquidityPool.collateralToken, baseParams, riskParams ); } /** * @dev Run the liquidity pool. Can only called by the operator. The operator can create new perpetual before running * or after running if isFastCreationEnabled is set to true * * @param liquidityPool The reference of liquidity pool storage. */ function runLiquidityPool(LiquidityPoolStorage storage liquidityPool) public { uint256 length = liquidityPool.perpetualCount; require(length > 0, "there should be at least 1 perpetual to run"); for (uint256 i = 0; i < length; i++) { liquidityPool.perpetuals[i].setNormalState(); } liquidityPool.isRunning = true; emit RunLiquidityPool(); } /** * @dev Set the parameter of the liquidity pool. Can only called by the governor. * * @param liquidityPool The reference of liquidity pool storage. * @param params The new value of the parameter */ function setLiquidityPoolParameter( LiquidityPoolStorage storage liquidityPool, int256[2] memory params ) public { validateLiquidityPoolParameter(params); liquidityPool.isFastCreationEnabled = (params[0] != 0); liquidityPool.insuranceFundCap = params[1]; emit SetLiquidityPoolParameter(params); } /** * @dev Validate the liquidity pool parameter: * 1. insurance fund cap >= 0 * @param liquidityPoolParams The parameters of the liquidity pool. */ function validateLiquidityPoolParameter(int256[2] memory liquidityPoolParams) public pure { require(liquidityPoolParams[1] >= 0, "insuranceFundCap < 0"); } /** * @dev Set an account as new keeper of liquidit pool. * Keeper is the role to be able to call liquidateByAMM. * When keeper is set to zero address, any one is able to call liquidateByAMM. * * @param newKeeper The account of keeper. */ function setKeeper(LiquidityPoolStorage storage liquidityPool, address newKeeper) public { require(newKeeper != liquidityPool.keeper, "new keeper is current keeper"); emit SetKeeper(liquidityPool.keeper, newKeeper); liquidityPool.keeper = newKeeper; } function setPerpetualOracle( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address newOracle ) public { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; perpetual.setOracle(newOracle); } /** * @dev Set the base parameter of the perpetual. Can only called by the governor * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of perpetual in the liquidity pool * @param baseParams The new value of the base parameter */ function setPerpetualBaseParameter( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, int256[9] memory baseParams ) public { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; perpetual.setBaseParameter(baseParams); } /** * @dev Set the risk parameter of the perpetual, including minimum value and maximum value. * Can only called by the governor * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of perpetual in the liquidity pool * @param riskParams The new value of the risk parameter, must between minimum value and maximum value * @param minRiskParamValues The minimum value of the risk parameter * @param maxRiskParamValues The maximum value of the risk parameter */ function setPerpetualRiskParameter( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, int256[8] memory riskParams, int256[8] memory minRiskParamValues, int256[8] memory maxRiskParamValues ) public { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; perpetual.setRiskParameter(riskParams, minRiskParamValues, maxRiskParamValues); } /** * @dev Set the risk parameter of the perpetual. Can only called by the governor * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of perpetual in the liquidity pool * @param riskParams The new value of the risk parameter, must between minimum value and maximum value */ function updatePerpetualRiskParameter( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, int256[8] memory riskParams ) public { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; perpetual.updateRiskParameter(riskParams); } /** * @dev Set the state of the perpetual to "EMERGENCY". Must rebalance first. * After that the perpetual is not allowed to trade, deposit and withdraw. * The price of the perpetual is freezed to the settlement price * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in the liquidity pool */ function setEmergencyState(LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex) public { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); rebalance(liquidityPool, perpetualIndex); liquidityPool.perpetuals[perpetualIndex].setEmergencyState(); } /** * @dev Set the state of all the perpetuals to "EMERGENCY". Use special type of rebalance. * After rebalance, pool cash >= 0 and margin / initialMargin is the same in all perpetuals. * Can only called when AMM is not maintenance margin safe in all perpetuals. * After that all the perpetuals are not allowed to trade, deposit and withdraw. * The price of every perpetual is freezed to the settlement price * @param liquidityPool The reference of liquidity pool storage. */ function setAllPerpetualsToEmergencyState(LiquidityPoolStorage storage liquidityPool) public { int256 margin; int256 maintenanceMargin; int256 initialMargin; uint256 length = liquidityPool.perpetualCount; for (uint256 i = 0; i < length; i++) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[i]; if (perpetual.state != PerpetualState.NORMAL) { continue; } int256 markPrice = perpetual.getMarkPrice(); maintenanceMargin = maintenanceMargin.add( perpetual.getMaintenanceMargin(address(this), markPrice) ); initialMargin = initialMargin.add(perpetual.getInitialMargin(address(this), markPrice)); margin = margin.add(perpetual.getMargin(address(this), markPrice)); } margin = margin.add(liquidityPool.poolCash); require(margin < maintenanceMargin, "AMM's margin >= maintenance margin"); // rebalance for settle all perps // Floor to make poolCash >= 0 int256 rate = margin.wdiv(initialMargin, Round.FLOOR); for (uint256 i = 0; i < length; i++) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[i]; if (perpetual.state != PerpetualState.NORMAL) { continue; } int256 markPrice = perpetual.getMarkPrice(); // Floor to make poolCash >= 0 int256 newMargin = perpetual.getInitialMargin(address(this), markPrice).wmul(rate, Round.FLOOR); margin = perpetual.getMargin(address(this), markPrice); int256 deltaMargin = newMargin.sub(margin); if (deltaMargin > 0) { // from pool to perp perpetual.updateCash(address(this), deltaMargin); transferFromPoolToPerpetual(liquidityPool, i, deltaMargin); } else if (deltaMargin < 0) { // from perp to pool perpetual.updateCash(address(this), deltaMargin); transferFromPerpetualToPool(liquidityPool, i, deltaMargin.neg()); } liquidityPool.perpetuals[i].setEmergencyState(); } require(liquidityPool.poolCash >= 0, "negative poolCash after settle all"); } /** * @dev Set the state of the perpetual to "CLEARED". Add the collateral of AMM in the perpetual to the pool cash. * Can only called when all the active accounts in the perpetual are cleared * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in the liquidity pool */ function setClearedState(LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex) public { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; perpetual.countMargin(address(this)); perpetual.setClearedState(); int256 marginToReturn = perpetual.settle(address(this)); transferFromPerpetualToPool(liquidityPool, perpetualIndex, marginToReturn); } /** * @dev Specify a new address to be operator. See transferOperator in Governance.sol. * @param liquidityPool The liquidity pool storage. * @param newOperator The address of new operator to transfer to */ function transferOperator(LiquidityPoolStorage storage liquidityPool, address newOperator) public { require(newOperator != address(0), "new operator is invalid"); require(newOperator != getOperator(liquidityPool), "cannot transfer to current operator"); liquidityPool.transferringOperator = newOperator; emit TransferOperatorTo(newOperator); } /** * @dev A lease mechanism to check if the operator is alive as the pool manager. * After OPERATOR_CHECK_IN_TIMEOUT, the operator will no longer be the operator. * New operator will only be raised by voting. * Transfer operator to another account will renew the expiration. * * @param liquidityPool The liquidity pool storage. */ function checkIn(LiquidityPoolStorage storage liquidityPool) public { liquidityPool.operatorExpiration = block.timestamp.add(OPERATOR_CHECK_IN_TIMEOUT); emit OperatorCheckIn(getOperator(liquidityPool)); } /** * @dev Claim the ownership of the liquidity pool to claimer. See `transferOperator` in Governance.sol. * @param liquidityPool The liquidity pool storage. * @param claimer The address of claimer */ function claimOperator(LiquidityPoolStorage storage liquidityPool, address claimer) public { require(claimer == liquidityPool.transferringOperator, "caller is not qualified"); liquidityPool.operator = claimer; liquidityPool.operatorExpiration = block.timestamp.add(OPERATOR_CHECK_IN_TIMEOUT); liquidityPool.transferringOperator = address(0); IPoolCreator(liquidityPool.creator).registerOperatorOfLiquidityPool(address(this), claimer); emit ClaimOperator(claimer); } /** * @dev Revoke operatorship of the liquidity pool. * @param liquidityPool The liquidity pool object */ function revokeOperator(LiquidityPoolStorage storage liquidityPool) public { liquidityPool.operator = address(0); IPoolCreator(liquidityPool.creator).registerOperatorOfLiquidityPool( address(this), address(0) ); emit RevokeOperator(); } /** * @dev Update the funding state of each perpetual of the liquidity pool. Funding payment of every account in the * liquidity pool is updated * @param liquidityPool The reference of liquidity pool storage. * @param currentTime The current timestamp */ function updateFundingState(LiquidityPoolStorage storage liquidityPool, uint256 currentTime) public { if (liquidityPool.fundingTime >= currentTime) { // invalid time return; } int256 timeElapsed = currentTime.sub(liquidityPool.fundingTime).toInt256(); uint256 length = liquidityPool.perpetualCount; for (uint256 i = 0; i < length; i++) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[i]; if (perpetual.state != PerpetualState.NORMAL) { continue; } perpetual.updateFundingState(timeElapsed); } liquidityPool.fundingTime = currentTime; } /** * @dev Update the funding rate of each perpetual of the liquidity pool * @param liquidityPool The reference of liquidity pool storage. */ function updateFundingRate(LiquidityPoolStorage storage liquidityPool) public { (int256 poolMargin, bool isAMMSafe) = liquidityPool.getPoolMargin(); emit UpdatePoolMargin(poolMargin); if (!isAMMSafe) { poolMargin = 0; } uint256 length = liquidityPool.perpetualCount; for (uint256 i = 0; i < length; i++) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[i]; if (perpetual.state != PerpetualState.NORMAL) { continue; } perpetual.updateFundingRate(poolMargin); } } /** * @dev Update the oracle price of each perpetual of the liquidity pool. * If oracle is terminated, set market to EMERGENCY. * * @param liquidityPool The liquidity pool object * @param currentTime The current timestamp */ function updatePrice( LiquidityPoolStorage storage liquidityPool, uint256 currentTime, bool ignoreTerminated ) public { if (liquidityPool.priceUpdateTime >= currentTime) { return; } uint256 length = liquidityPool.perpetualCount; for (uint256 i = 0; i < length; i++) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[i]; if (perpetual.state != PerpetualState.NORMAL) { continue; } perpetual.updatePrice(); if (IOracle(perpetual.oracle).isTerminated() && !ignoreTerminated) { setEmergencyState(liquidityPool, perpetual.id); } } liquidityPool.priceUpdateTime = currentTime; } /** * @dev Donate collateral to the insurance fund of the liquidity pool to make the liquidity pool safe. * * @param liquidityPool The liquidity pool object * @param amount The amount of collateral to donate */ function donateInsuranceFund( LiquidityPoolStorage storage liquidityPool, address donator, int256 amount ) public { require(amount > 0, "invalid amount"); liquidityPool.transferFromUser(donator, amount); liquidityPool.donatedInsuranceFund = liquidityPool.donatedInsuranceFund.add(amount); emit DonateInsuranceFund(amount); } /** * @dev Update the collateral of the insurance fund in the liquidity pool. * If the collateral of the insurance fund exceeds the cap, the extra part of collateral belongs to LP. * If the collateral of the insurance fund < 0, the donated insurance fund will cover it. * * @param liquidityPool The liquidity pool object * @param deltaFund The update collateral amount of the insurance fund in the perpetual * @return penaltyToLP The extra part of collateral if the collateral of the insurance fund exceeds the cap */ function updateInsuranceFund(LiquidityPoolStorage storage liquidityPool, int256 deltaFund) public returns (int256 penaltyToLP) { if (deltaFund != 0) { int256 newInsuranceFund = liquidityPool.insuranceFund.add(deltaFund); if (deltaFund > 0) { if (newInsuranceFund > liquidityPool.insuranceFundCap) { penaltyToLP = newInsuranceFund.sub(liquidityPool.insuranceFundCap); newInsuranceFund = liquidityPool.insuranceFundCap; emit TransferExcessInsuranceFundToLP(penaltyToLP); } } else { if (newInsuranceFund < 0) { liquidityPool.donatedInsuranceFund = liquidityPool.donatedInsuranceFund.add( newInsuranceFund ); require( liquidityPool.donatedInsuranceFund >= 0, "negative donated insurance fund" ); newInsuranceFund = 0; } } liquidityPool.insuranceFund = newInsuranceFund; } } /** * @dev Deposit collateral to the trader's account of the perpetual. The trader's cash will increase. * Activate the perpetual for the trader if the account in the perpetual is empty before depositing. * Empty means cash and position are zero. * * @param liquidityPool The liquidity pool object * @param perpetualIndex The index of the perpetual in the liquidity pool * @param trader The address of the trader * @param amount The amount of collateral to deposit */ function deposit( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 amount ) public { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); transferFromUserToPerpetual(liquidityPool, perpetualIndex, trader, amount); if (liquidityPool.perpetuals[perpetualIndex].deposit(trader, amount)) { IPoolCreator(liquidityPool.creator).activatePerpetualFor(trader, perpetualIndex); } } /** * @dev Withdraw collateral from the trader's account of the perpetual. The trader's cash will decrease. * Trader must be initial margin safe in the perpetual after withdrawing. * Deactivate the perpetual for the trader if the account in the perpetual is empty after withdrawing. * Empty means cash and position are zero. * * @param liquidityPool The liquidity pool object * @param perpetualIndex The index of the perpetual in the liquidity pool * @param trader The address of the trader * @param amount The amount of collateral to withdraw */ function withdraw( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 amount ) public { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; rebalance(liquidityPool, perpetualIndex); if (perpetual.withdraw(trader, amount)) { IPoolCreator(liquidityPool.creator).deactivatePerpetualFor(trader, perpetualIndex); } transferFromPerpetualToUser(liquidityPool, perpetualIndex, trader, amount); } /** * @dev If the state of the perpetual is "CLEARED", anyone authorized withdraw privilege by trader can settle * trader's account in the perpetual. Which means to calculate how much the collateral should be returned * to the trader, return it to trader's wallet and clear the trader's cash and position in the perpetual. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in the liquidity pool. * @param trader The address of the trader. */ function settle( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader ) public { require(trader != address(0), "invalid trader"); int256 marginToReturn = liquidityPool.perpetuals[perpetualIndex].settle(trader); require(marginToReturn > 0, "no margin to settle"); transferFromPerpetualToUser(liquidityPool, perpetualIndex, trader, marginToReturn); } /** * @dev Clear the next active account of the perpetual which state is "EMERGENCY" and send gas reward of collateral * to sender. If all active accounts are cleared, the clear progress is done and the perpetual's state will * change to "CLEARED". Active means the trader's account is not empty in the perpetual. * Empty means cash and position are zero. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in the liquidity pool */ function clear( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader ) public { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; if ( perpetual.keeperGasReward > 0 && perpetual.totalCollateral >= perpetual.keeperGasReward ) { transferFromPerpetualToUser( liquidityPool, perpetualIndex, trader, perpetual.keeperGasReward ); } if ( perpetual.activeAccounts.length() == 0 || perpetual.clear(perpetual.getNextActiveAccount()) ) { setClearedState(liquidityPool, perpetualIndex); } } /** * @dev Add collateral to the liquidity pool and get the minted share tokens. * The share token is the credential and use to get the collateral back when removing liquidity. * Can only called when at least 1 perpetual is in NORMAL state. * * @param liquidityPool The reference of liquidity pool storage. * @param trader The address of the trader that adding liquidity * @param cashToAdd The cash(collateral) to add */ function addLiquidity( LiquidityPoolStorage storage liquidityPool, address trader, int256 cashToAdd ) public { require(cashToAdd > 0, "cash amount must be positive"); uint256 length = liquidityPool.perpetualCount; bool allowAdd; for (uint256 i = 0; i < length; i++) { if (liquidityPool.perpetuals[i].state == PerpetualState.NORMAL) { allowAdd = true; break; } } require(allowAdd, "not all perpetuals are in NORMAL state"); liquidityPool.transferFromUser(trader, cashToAdd); IGovernor shareToken = IGovernor(liquidityPool.shareToken); int256 shareTotalSupply = shareToken.totalSupply().toInt256(); (int256 shareToMint, int256 addedPoolMargin) = liquidityPool.getShareToMint(shareTotalSupply, cashToAdd); require(shareToMint > 0, "received share must be positive"); // pool cash cannot be added before calculation, DO NOT use transferFromUserToPool increasePoolCash(liquidityPool, cashToAdd); shareToken.mint(trader, shareToMint.toUint256()); emit AddLiquidity(trader, cashToAdd, shareToMint, addedPoolMargin); } /** * @dev Remove collateral from the liquidity pool and redeem the share tokens when the liquidity pool is running. * Only one of shareToRemove or cashToReturn may be non-zero. * * @param liquidityPool The reference of liquidity pool storage. * @param trader The address of the trader that removing liquidity. * @param shareToRemove The amount of the share token to redeem. * @param cashToReturn The amount of cash(collateral) to return. */ function removeLiquidity( LiquidityPoolStorage storage liquidityPool, address trader, int256 shareToRemove, int256 cashToReturn ) public { IGovernor shareToken = IGovernor(liquidityPool.shareToken); int256 shareTotalSupply = shareToken.totalSupply().toInt256(); int256 removedInsuranceFund; int256 removedDonatedInsuranceFund; int256 removedPoolMargin; if (cashToReturn == 0 && shareToRemove > 0) { ( cashToReturn, removedInsuranceFund, removedDonatedInsuranceFund, removedPoolMargin ) = liquidityPool.getCashToReturn(shareTotalSupply, shareToRemove); require(cashToReturn > 0, "cash to return must be positive"); } else if (cashToReturn > 0 && shareToRemove == 0) { ( shareToRemove, removedInsuranceFund, removedDonatedInsuranceFund, removedPoolMargin ) = liquidityPool.getShareToRemove(shareTotalSupply, cashToReturn); require(shareToRemove > 0, "share to remove must be positive"); } else { revert("invalid parameter"); } require( shareToRemove.toUint256() <= shareToken.balanceOf(trader), "insufficient share balance" ); int256 removedCashFromPool = cashToReturn.sub(removedInsuranceFund).sub(removedDonatedInsuranceFund); require( removedCashFromPool <= getAvailablePoolCash(liquidityPool), "insufficient pool cash" ); shareToken.burn(trader, shareToRemove.toUint256()); liquidityPool.transferToUser(trader, cashToReturn); liquidityPool.insuranceFund = liquidityPool.insuranceFund.sub(removedInsuranceFund); liquidityPool.donatedInsuranceFund = liquidityPool.donatedInsuranceFund.sub( removedDonatedInsuranceFund ); decreasePoolCash(liquidityPool, removedCashFromPool); emit RemoveLiquidity(trader, cashToReturn, shareToRemove, removedPoolMargin); } /** * @dev Add collateral to the liquidity pool without getting share tokens. * * @param liquidityPool The reference of liquidity pool storage. * @param trader The address of the trader that adding liquidity * @param cashToAdd The cash(collateral) to add */ function donateLiquidity( LiquidityPoolStorage storage liquidityPool, address trader, int256 cashToAdd ) public { require(cashToAdd > 0, "cash amount must be positive"); (, int256 addedPoolMargin) = liquidityPool.getShareToMint(0, cashToAdd); liquidityPool.transferFromUser(trader, cashToAdd); // pool cash cannot be added before calculation, DO NOT use transferFromUserToPool increasePoolCash(liquidityPool, cashToAdd); emit AddLiquidity(trader, cashToAdd, 0, addedPoolMargin); } /** * @dev To keep the AMM's margin equal to initial margin in the perpetual as posiible. * Transfer collateral between the perpetual and the liquidity pool's cash, then * update the AMM's cash in perpetual. The liquidity pool's cash can be negative, * but the available cash can't. If AMM need to transfer and the available cash * is not enough, transfer all the rest available cash of collateral. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in the liquidity pool * @return The amount of rebalanced margin. A positive amount indicates the collaterals * are moved from perpetual to pool, and a negative amount indicates the opposite. * 0 means no rebalance happened. */ function rebalance(LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex) public returns (int256) { require(perpetualIndex < liquidityPool.perpetualCount, "perpetual index out of range"); PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; if (perpetual.state != PerpetualState.NORMAL) { return 0; } int256 rebalanceMargin = perpetual.getRebalanceMargin(); if (rebalanceMargin == 0) { // nothing to rebalance return 0; } else if (rebalanceMargin > 0) { // from perp to pool perpetual.updateCash(address(this), rebalanceMargin.neg()); transferFromPerpetualToPool(liquidityPool, perpetualIndex, rebalanceMargin); } else { // from pool to perp int256 availablePoolCash = getAvailablePoolCash(liquidityPool, perpetualIndex); if (availablePoolCash <= 0) { // pool has no more collateral, nothing to rebalance return 0; } rebalanceMargin = rebalanceMargin.abs().min(availablePoolCash); perpetual.updateCash(address(this), rebalanceMargin); transferFromPoolToPerpetual(liquidityPool, perpetualIndex, rebalanceMargin); } return rebalanceMargin; } /** * @dev Increase the liquidity pool's cash(collateral). * @param liquidityPool The reference of liquidity pool storage. * @param amount The amount of cash(collateral) to increase. */ function increasePoolCash(LiquidityPoolStorage storage liquidityPool, int256 amount) internal { require(amount >= 0, "increase negative pool cash"); liquidityPool.poolCash = liquidityPool.poolCash.add(amount); } /** * @dev Decrease the liquidity pool's cash(collateral). * @param liquidityPool The reference of liquidity pool storage. * @param amount The amount of cash(collateral) to decrease. */ function decreasePoolCash(LiquidityPoolStorage storage liquidityPool, int256 amount) internal { require(amount >= 0, "decrease negative pool cash"); liquidityPool.poolCash = liquidityPool.poolCash.sub(amount); } // user <=> pool (addLiquidity/removeLiquidity) function transferFromUserToPool( LiquidityPoolStorage storage liquidityPool, address account, int256 amount ) public { liquidityPool.transferFromUser(account, amount); increasePoolCash(liquidityPool, amount); } function transferFromPoolToUser( LiquidityPoolStorage storage liquidityPool, address account, int256 amount ) public { if (amount == 0) { return; } liquidityPool.transferToUser(account, amount); decreasePoolCash(liquidityPool, amount); } // user <=> perpetual (deposit/withdraw) function transferFromUserToPerpetual( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address account, int256 amount ) public { liquidityPool.transferFromUser(account, amount); liquidityPool.perpetuals[perpetualIndex].increaseTotalCollateral(amount); } function transferFromPerpetualToUser( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address account, int256 amount ) public { if (amount == 0) { return; } liquidityPool.transferToUser(account, amount); liquidityPool.perpetuals[perpetualIndex].decreaseTotalCollateral(amount); } // pool <=> perpetual (fee/rebalance) function transferFromPerpetualToPool( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, int256 amount ) public { if (amount == 0) { return; } liquidityPool.perpetuals[perpetualIndex].decreaseTotalCollateral(amount); increasePoolCash(liquidityPool, amount); } function transferFromPoolToPerpetual( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, int256 amount ) public { if (amount == 0) { return; } liquidityPool.perpetuals[perpetualIndex].increaseTotalCollateral(amount); decreasePoolCash(liquidityPool, amount); } /** * @dev Check if the trader is authorized the privilege by the grantee. Any trader is authorized by himself * @param liquidityPool The reference of liquidity pool storage. * @param trader The address of the trader * @param grantee The address of the grantee * @param privilege The privilege * @return isGranted True if the trader is authorized */ function isAuthorized( LiquidityPoolStorage storage liquidityPool, address trader, address grantee, uint256 privilege ) public view returns (bool isGranted) { isGranted = trader == grantee || IAccessControl(liquidityPool.accessController).isGranted(trader, grantee, privilege); } /** * @dev Deposit or withdraw to let effective leverage == target leverage * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in the liquidity pool. * @param trader The address of the trader. * @param deltaPosition The update position of the trader's account in the perpetual. * @param deltaCash The update cash(collateral) of the trader's account in the perpetual. * @param totalFee The total fee collected from the trader after the trade. */ function adjustMarginLeverage( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 deltaPosition, int256 deltaCash, int256 totalFee ) public { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; // read perp int256 position = perpetual.getPosition(trader); int256 adjustCollateral; (int256 closePosition, int256 openPosition) = Utils.splitAmount(position.sub(deltaPosition), deltaPosition); if (closePosition != 0 && openPosition == 0) { // close only adjustCollateral = adjustClosedMargin( perpetual, trader, closePosition, deltaCash, totalFee ); } else { // open only or close + open adjustCollateral = adjustOpenedMargin( perpetual, trader, deltaPosition, deltaCash, closePosition, openPosition, totalFee ); } // real deposit/withdraw if (adjustCollateral > 0) { deposit(liquidityPool, perpetualIndex, trader, adjustCollateral); } else if (adjustCollateral < 0) { withdraw(liquidityPool, perpetualIndex, trader, adjustCollateral.neg()); } } function adjustClosedMargin( PerpetualStorage storage perpetual, address trader, int256 closePosition, int256 deltaCash, int256 totalFee ) public view returns (int256 adjustCollateral) { int256 markPrice = perpetual.getMarkPrice(); int256 position2 = perpetual.getPosition(trader); // when close, keep the margin ratio // -withdraw == (availableCash2 * close - (deltaCash - fee) * position2 + reservedValue) / position1 // reservedValue = 0 if position2 == 0 else keeperGasReward * (-deltaPos) adjustCollateral = perpetual.getAvailableCash(trader).wmul(closePosition); adjustCollateral = adjustCollateral.sub(deltaCash.sub(totalFee).wmul(position2)); if (position2 != 0) { adjustCollateral = adjustCollateral.sub(perpetual.keeperGasReward.wmul(closePosition)); } adjustCollateral = adjustCollateral.wdiv(position2.sub(closePosition)); // withdraw only when IM is satisfied adjustCollateral = adjustCollateral.max( perpetual.getAvailableMargin(trader, markPrice).neg() ); // never deposit when close positions adjustCollateral = adjustCollateral.min(0); } // open only or close + open function adjustOpenedMargin( PerpetualStorage storage perpetual, address trader, int256 deltaPosition, int256 deltaCash, int256 closePosition, int256 openPosition, int256 totalFee ) public view returns (int256 adjustCollateral) { int256 markPrice = perpetual.getMarkPrice(); int256 oldMargin = perpetual.getMargin(trader, markPrice); int256 leverage = perpetual.getTargetLeverage(trader); require(leverage > 0, "target leverage = 0"); // openPositionMargin adjustCollateral = openPosition.abs().wfrac(markPrice, leverage); if (perpetual.getPosition(trader).sub(deltaPosition) != 0 && closePosition == 0) { // open from non-zero position // adjustCollateral = openPositionMargin + fee - pnl adjustCollateral = adjustCollateral .add(totalFee) .sub(markPrice.wmul(deltaPosition)) .sub(deltaCash); } else { // open from 0 or close + open adjustCollateral = adjustCollateral.sub(oldMargin); } // make sure after adjust: trader is initial margin safe adjustCollateral = adjustCollateral.max( perpetual.getAvailableMargin(trader, markPrice).neg() ); } function setTargetLeverage( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 targetLeverage ) public { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; require(perpetual.initialMarginRate != 0, "initialMarginRate is not set"); require( targetLeverage != perpetual.marginAccounts[trader].targetLeverage, "targetLeverage is already set" ); int256 maxLeverage = Constant.SIGNED_ONE.wdiv(perpetual.initialMarginRate); require(targetLeverage <= maxLeverage, "targetLeverage exceeds maxLeverage"); perpetual.setTargetLeverage(trader, targetLeverage); emit SetTargetLeverage(trader, targetLeverage); } }
A lease mechanism to check if the operator is alive as the pool manager. After OPERATOR_CHECK_IN_TIMEOUT, the operator will no longer be the operator. New operator will only be raised by voting. Transfer operator to another account will renew the expiration. liquidityPool The liquidity pool storage./
function checkIn(LiquidityPoolStorage storage liquidityPool) public { liquidityPool.operatorExpiration = block.timestamp.add(OPERATOR_CHECK_IN_TIMEOUT); emit OperatorCheckIn(getOperator(liquidityPool)); }
5,505,386
pragma ton-solidity >=0.44.0; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; //================================================================================ // /// @title DexDebot /// @author Augual.Team /// @notice Debot for Augual.DEX (LiquiSOR) service //================================================================================ // import "../interfaces/IDexFactory.sol"; import "../interfaces/ISymbolPair.sol"; import "../interfaces/ILiquidFTRoot.sol"; import "../interfaces/ILiquidFTWallet.sol"; import "../interfaces/IDebot.sol"; import "../interfaces/IUpgradable.sol"; import "../interfaces/debot/address.sol"; import "../interfaces/debot/amount.sol"; import "../interfaces/debot/menu.sol"; import "../interfaces/debot/number.sol"; import "../interfaces/debot/sdk.sol"; import "../interfaces/debot/terminal.sol"; //================================================================================ // interface IMsig { /// @dev Allows custodian if she is the only owner of multisig to transfer funds with minimal fees. /// @param dest Transfer target address. /// @param value Amount of funds to transfer. /// @param bounce Bounce flag. Set true if need to transfer funds to existing account; /// set false to create new account. /// @param flags `sendmsg` flags. /// @param payload Tree of cells used as body of outbound internal message. function sendTransaction( address dest, uint128 value, bool bounce, uint8 flags, TvmCell payload) external view; } //================================================================================ // contract DexDebot is Debot, Upgradable { //TvmCell _domainCode; //TvmCell _deployerCode; address _factoryAddress; address _symbolPairAddress; int8 _symbolPairAccState; address _msigAddress; Symbol[] _symbolsList; Symbol _selectedSymbol1; Symbol _selectedSymbol2; address _lpWalletAddress; uint128 _depositAmount1; uint128 _depositAmount2; uint16 _depositSlippage; // Provide liquidity Symbol _provideLiquiditySymbol; address _provideLiquidityWalletAddress; // Trade Symbol _tradeSellSymbol; Symbol _tradeBuySymbol; address _tradeSellWalletAddress; address _tradeBuyWalletAddress; uint128 _sellAmount; uint128 _buyAmount; /*string ctx_name; address ctx_domain; DnsWhois ctx_whois; int8 ctx_accState; uint8 ctx_segments; address ctx_parent;*/ optional(uint256) _emptyPk; uint128 constant ATTACH_VALUE = 0.5 ton; //======================================== // constructor(address ownerAddress) public { _ownerAddress = ownerAddress; tvm.accept(); } //======================================== // function setFactoryAddress(address factoryAddress) public { require(msg.pubkey() == tvm.pubkey() || senderIsOwner(), 100); tvm.accept(); _factoryAddress = factoryAddress; } //======================================== // function getRequiredInterfaces() public pure returns (uint256[] interfaces) { return [Terminal.ID, AddressInput.ID, NumberInput.ID, AmountInput.ID, Menu.ID]; } //======================================== // function getDebotInfo() public functionID(0xDEB) view returns(string name, string version, string publisher, string key, string author, address support, string hello, string language, string dabi, bytes icon) { name = "LiquiSOR DEX DeBot (Augual.TEAM)"; version = "0.2.0"; publisher = "Augual.TEAM"; key = "LiquiSOR DEX from Augual.TEAM"; author = "Augual.TEAM"; support = addressZero; hello = "Welcome to LiquiSOR DEX DeBot!"; language = "en"; dabi = m_debotAbi.hasValue() ? m_debotAbi.get() : ""; icon = m_icon.hasValue() ? m_icon.get() : ""; } //======================================== /// @notice Define DeBot version and title here. function getVersion() public override returns (string name, uint24 semver) { (name, semver) = ("DexDebot", _version(0, 2, 0)); } function _version(uint24 major, uint24 minor, uint24 fix) private pure inline returns (uint24) { return (major << 16) | (minor << 8) | (fix); } //======================================== // Implementation of Upgradable function onCodeUpgrade() internal override { tvm.resetStorage(); } //======================================== // function onError(uint32 sdkError, uint32 exitCode) public { // if (exitCode == ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER) { Terminal.print(0, "Failed! You're not the owner of this domain."); } //else if (exitCode == ERROR_REQUIRE_INTERNAL_MESSAGE_WITH_VALUE) { Terminal.print(0, "Failed! No value attached."); } //else if (exitCode == ERROR_DOMAIN_IS_EXPIRED) { Terminal.print(0, "Failed! Domain is expired."); } //else if (exitCode == ERROR_DOMAIN_IS_NOT_EXPIRED) { Terminal.print(0, "Failed! Domain is not expired."); } //else if (exitCode == ERROR_CAN_NOT_PROLONGATE_YET) { Terminal.print(0, "Failed! Can't prolong yet."); } //else if (exitCode == ERROR_NOT_ENOUGH_MONEY) { Terminal.print(0, "Failed! Not enough value attached to cover domain price."); } //else { Terminal.print(0, format("Failed! SDK Error: {}. Exit Code: {}", sdkError, exitCode)); } mainMenu(0); } //======================================== // Inline functions function _sortSymbols(Symbol sym1, Symbol sym2) internal inline pure returns (Symbol, Symbol) { return (sym1.addressRTW < sym2.addressRTW ? (sym1, sym2) : (sym2, sym1)); } //======================================== /// @notice Entry point function for DeBot. function start() public override { mainMenu(0); } //======================================== // function _eraseCtx() internal { _msigAddress = addressZero; delete _symbolsList; /*ctx_domain = addressZero; ctx_name = ""; ctx_accState = 0; ctx_segments = 0; ctx_parent = addressZero; delete ctx_whois; // reset custom struct without specifying all the members*/ } //======================================== // function getSymbolRepresentation(Symbol symbol) public pure returns (string) { string text; text.append("("); text.append(symbol.symbol); text.append(") "); text.append(symbol.name); return text; } //======================================== // function mainMenu(uint32 index) public { _eraseCtx(); index = 0; // shut a warning if(_factoryAddress == addressZero) { //Terminal.print(0, "DeBot is being upgraded.\nPlease come back in a minute.\nSorry for inconvenience."); return; } AddressInput.get(tvm.functionId(onMsigEnter), "Let's start with entering your Multisig Wallet address: "); } //======================================== // function onMsigEnter(address value) public { _msigAddress = value; _refreshSymbols_1(0); } //======================================== //======================================== //======================================== //======================================== //======================================== // function _refreshSymbols_1(uint32 index) public view { index = 0; // shut a warning IDexFactory(_factoryAddress).getSymbolsList{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_refreshSymbols_2), onErrorId: tvm.functionId(onError) }(); } function _refreshSymbols_2(Symbol[] symbols) public { _symbolsList = symbols; _mainLoop(0); } //======================================== //======================================== //======================================== //======================================== //======================================== // function _mainLoop(uint32 index) public { index = 0; // shut a warning MenuItem[] mi; mi.push(MenuItem("List Symbols", "", tvm.functionId(_listSymbols_1) )); mi.push(MenuItem("Refresh Symbols", "", tvm.functionId(_refreshSymbols_1) )); mi.push(MenuItem("Add Symbol", "", tvm.functionId(_addSymbol_1) )); mi.push(MenuItem("Get Symbol Pair", "", tvm.functionId(_getSymbolPair_1) )); mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) )); Menu.select("Enter your choice: ", "", mi); } //======================================== //======================================== //======================================== //======================================== //======================================== // function _listSymbols_1(uint32 index) public { index = 0; // shut a warning string text; for(Symbol symbol : _symbolsList) { if(text.byteLength() > 0){ text.append("\n"); } text.append(getSymbolRepresentation(symbol)); } Terminal.print(0, text); _mainLoop(0); } //======================================== //======================================== //======================================== //======================================== //======================================== // function _addSymbol_1(uint32 index) public { index = 0; // shut a warning AddressInput.get(tvm.functionId(_addSymbol_2), "Please enter TRC-6 RTW address: "); } function _addSymbol_2(address value) public { TvmCell body = tvm.encodeBody(IDexFactory.addSymbol, value); _sendTransact(_msigAddress, _factoryAddress, body, ATTACH_VALUE); _addSymbol_3(0); } function _addSymbol_3(uint32 index) public { index = 0; // shut a warning Terminal.print(0, "Adding symbol, please wait for ~10 seconds and refresh Symbols list"); _mainLoop(0); } //======================================== //======================================== //======================================== //======================================== //======================================== // function _getSymbolPair_1(uint32 index) public { index = 0; // shut a warning delete _selectedSymbol1; delete _selectedSymbol2; Terminal.print(0, "Please choose the first Symbol:"); MenuItem[] mi; for(Symbol symbol : _symbolsList) { mi.push(MenuItem(getSymbolRepresentation(symbol), "", tvm.functionId(_getSymbolPair_2))); } Menu.select("Enter your choice: ", "", mi); } function _getSymbolPair_2(uint32 index) public { _selectedSymbol1 = _symbolsList[index]; Terminal.print(0, "Please choose the second Symbol:"); MenuItem[] mi; for(Symbol symbol : _symbolsList) { //if(symbol.addressRTW == _selectedSymbol1.addressRTW) { continue; } mi.push(MenuItem(getSymbolRepresentation(symbol), "", tvm.functionId(_getSymbolPair_3))); } Menu.select("Enter your choice: ", "", mi); } function _getSymbolPair_3(uint32 index) public { _selectedSymbol2 = _symbolsList[index]; if(_selectedSymbol2.addressRTW == _selectedSymbol1.addressRTW) { Terminal.print(0, "You can't choose same Symbol twice!"); _getSymbolPair_1(0); return; } //(_selectedSymbol1, _selectedSymbol2) = _sortSymbols(_selectedSymbol1, _selectedSymbol2); IDexFactory(_factoryAddress).getPairAddress{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_getSymbolPair_4), onErrorId: tvm.functionId(onError) }(_selectedSymbol1.addressRTW, _selectedSymbol2.addressRTW); } function _getSymbolPair_4(address value) public { _symbolPairAddress = value; Sdk.getAccountType(tvm.functionId(_getSymbolPair_5), _symbolPairAddress); } function _getSymbolPair_5(int8 acc_type) public { _symbolPairAccState = acc_type; _getSymbolPair_6(0); } function _getSymbolPair_6(uint32 index) public { index = 0; // shut a warning if (_symbolPairAccState == -1 || _symbolPairAccState == 0) { Terminal.print(0, format("Symbol Pair does not exist!")); MenuItem[] mi; mi.push(MenuItem("Deploy Pair", "", tvm.functionId(_symbolPairDeploy_1))); mi.push(MenuItem("<- Go back", "", tvm.functionId(_mainLoop) )); mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) )); Menu.select("Enter your choice: ", "", mi); } else if (_symbolPairAccState == 1) { _symbolPairMenu_1(0); } else if (_symbolPairAccState == 2) { Terminal.print(0, format("Symbol Pair is FROZEN.")); _mainLoop(0); } } //======================================== //======================================== //======================================== //======================================== //======================================== // function _symbolPairDeploy_1(uint32 index) public { index = 0; // shut a warning TvmCell body = tvm.encodeBody(IDexFactory.addPair, _selectedSymbol1.addressRTW, _selectedSymbol2.addressRTW); _sendTransact(_msigAddress, _factoryAddress, body, ATTACH_VALUE * 2); _symbolPairDeploy_2(1); } function _symbolPairDeploy_2(uint32 index) public { index = 0; // shut a warning Sdk.getAccountType(tvm.functionId(_symbolPairDeploy_3), _symbolPairAddress); } function _symbolPairDeploy_3(int8 acc_type) public { // Loop like crazy until we get the Pair if(acc_type == 1) { _symbolPairMenu_1(0); } else { _symbolPairDeploy_2(0); } } //======================================== //======================================== //======================================== //======================================== //======================================== // function _symbolPairMenu_1(uint32 index) public view { index = 0; // shut a warning ISymbolPair(_symbolPairAddress).getPairLiquidity{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairMenu_2), onErrorId: tvm.functionId(onError) }(); } function _symbolPairMenu_2(Symbol symbol1, Symbol symbol2, uint256 liquidity, uint8 decimals) public { _selectedSymbol1 = symbol1; _selectedSymbol2 = symbol2; // TODO: show Pair info; string text1 = format("SYMBOL 1\nName: {}\nSymbol: {}\nDecimals: {}\nIn Pool: {}", symbol1.name, symbol1.symbol, symbol1.decimals, symbol1.balance); string text2 = format("SYMBOL 2\nName: {}\nSymbol: {}\nDecimals: {}\nIn Pool: {}", symbol2.name, symbol2.symbol, symbol2.decimals, symbol2.balance); string text3 = format("Liquidity: {}\nLiquidity decimals: {}", liquidity, decimals); Terminal.print(0, text1); Terminal.print(0, text2); Terminal.print(0, text3); MenuItem[] mi; mi.push(MenuItem("Trade", "", tvm.functionId(_symbolPairTrade_1) )); mi.push(MenuItem("Provide liquidity", "", tvm.functionId(_symbolPairProvideLiquidity_1) )); mi.push(MenuItem("Get liquidity limbo", "", tvm.functionId(_symbolPairGetLiquidityLimbo_1) )); mi.push(MenuItem("Deposit liquidity", "", tvm.functionId(_symbolPairDepositLiquidity_1) )); mi.push(MenuItem("Withdraw liquidity", "", tvm.functionId(_symbolPairWithdrawLiquidity_1) )); mi.push(MenuItem("Withdraw leftovers", "", tvm.functionId(_symbolPairWithdrawLiquidityLeftovers_1))); mi.push(MenuItem("<- Go back", "", tvm.functionId(_mainLoop) )); mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) )); Menu.select("Enter your choice: ", "", mi); } //======================================== //======================================== //======================================== //======================================== //======================================== // function _symbolPairGetLiquidityLimbo_1(uint32 index) public view { index = 0; // shut a warning ISymbolPair(_symbolPairAddress).getUserLimbo{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairGetLiquidityLimbo_2), onErrorId: tvm.functionId(onError) }(_msigAddress); } function _symbolPairGetLiquidityLimbo_2(uint128 amount1, uint128 amount2) public { Terminal.print(0, format("Symbol1: {}\nSymbol2: {}", amount1, amount2)); _symbolPairMenu_1(0); } //======================================== //======================================== //======================================== //======================================== //======================================== // TODO: including wallet deployment function _symbolPairTrade_1(uint32 index) public { index = 0; // shut a warning delete _tradeSellSymbol; delete _tradeBuySymbol; Terminal.print(0, format("Select a symbol to sell:")); MenuItem[] mi; mi.push(MenuItem(getSymbolRepresentation(_selectedSymbol1), "", tvm.functionId(_symbolPairTrade_2) )); mi.push(MenuItem(getSymbolRepresentation(_selectedSymbol2), "", tvm.functionId(_symbolPairTrade_2) )); mi.push(MenuItem("<- Go back", "", tvm.functionId(_mainLoop) )); mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) )); Menu.select("Enter your choice: ", "", mi); } function _symbolPairTrade_2(uint32 index) public { _tradeSellSymbol = (index == 0 ? _selectedSymbol1 : _selectedSymbol2); _tradeBuySymbol = (index == 0 ? _selectedSymbol2 : _selectedSymbol1); ILiquidFTRoot(_tradeSellSymbol.addressRTW).getWalletAddress{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairTrade_3), onErrorId: tvm.functionId(onError) }(_msigAddress); } function _symbolPairTrade_3(address value) public { _tradeSellWalletAddress = value; Sdk.getAccountType(tvm.functionId(_symbolPairTrade_4), _tradeSellWalletAddress); } function _symbolPairTrade_4(int8 acc_type) public { if (acc_type == -1 || acc_type == 0) { Terminal.print(0, format("You don't have a Token wallet, you can't trade!")); _symbolPairMenu_1(0); } else if (acc_type == 1) { _symbolPairTrade_5(0); } else if (acc_type == 2) { Terminal.print(0, format("Your Token wallet Wallet is FROZEN.")); _mainLoop(0); } } function _symbolPairTrade_5(uint32 index) public view { index = 0; // shut a warning ILiquidFTRoot(_tradeBuySymbol.addressRTW).getWalletAddress{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairTrade_6), onErrorId: tvm.functionId(onError) }(_msigAddress); } function _symbolPairTrade_6(address value) public { _tradeBuyWalletAddress = value; Sdk.getAccountType(tvm.functionId(_symbolPairTrade_7), _tradeBuyWalletAddress); } function _symbolPairTrade_7(int8 acc_type) public { if (acc_type == -1 || acc_type == 0) { Terminal.print(0, format("Deploy receiver TTW first!")); TvmCell body = tvm.encodeBody(ILiquidFTRoot.createWallet, _msigAddress, addressZero, 0); _sendTransact(_msigAddress, _tradeBuySymbol.addressRTW, body, ATTACH_VALUE); _symbolPairTrade_8(0); } else if (acc_type == 1) { _symbolPairTrade_8(0); } else if (acc_type == 2) { Terminal.print(0, format("Your Token wallet Wallet is FROZEN.")); _mainLoop(0); } } function _symbolPairTrade_8(uint32 index) public { index = 0; // shut a warning AmountInput.get(tvm.functionId(_symbolPairTrade_9), format("Enter amount of {} to sell: ", _tradeSellSymbol.symbol), _tradeSellSymbol.decimals, 0, 999999999999999999999999999999); } function _symbolPairTrade_9(uint256 value) public { _sellAmount = uint128(value); ISymbolPair(_symbolPairAddress).getPrice{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairTrade_10), onErrorId: tvm.functionId(onError) }(_tradeSellSymbol.addressRTW, _sellAmount); } function _symbolPairTrade_10(uint128 amount, uint8 decimals) public { _buyAmount = amount; decimals = 0; // shut a warning Terminal.print(0, format("You are selling {} amount of {} and will get {} amount of {} in return. OK?", _sellAmount, _tradeSellSymbol.symbol, _buyAmount, _tradeBuySymbol.symbol)); MenuItem[] mi; mi.push(MenuItem("YES", "", tvm.functionId(_symbolPairTrade_11) )); mi.push(MenuItem("Nah, get me out", "", tvm.functionId(_symbolPairMenu_1) )); Menu.select("Enter your choice: ", "", mi); } function _symbolPairTrade_11(uint32 index) public view { index = 0; // shut a warning TvmBuilder builder; builder.store(uint8(0), _buyAmount, uint16(500)); // TODO: slippage is forced to 5%, ash user to enter number instead TvmCell body = tvm.encodeBody(ILiquidFTWallet.transfer, uint128(_sellAmount), _symbolPairAddress, _msigAddress, addressZero, builder.toCell()); _sendTransact(_msigAddress, _tradeSellWalletAddress, body, ATTACH_VALUE); _symbolPairMenu_1(0); } //======================================== //======================================== //======================================== //======================================== //======================================== // function _symbolPairProvideLiquidity_1(uint32 index) public { index = 0; // shut a warning delete _provideLiquiditySymbol; MenuItem[] mi; mi.push(MenuItem(getSymbolRepresentation(_selectedSymbol1), "", tvm.functionId(_symbolPairProvideLiquidity_2) )); mi.push(MenuItem(getSymbolRepresentation(_selectedSymbol2), "", tvm.functionId(_symbolPairProvideLiquidity_2) )); mi.push(MenuItem("<- Go back", "", tvm.functionId(_mainLoop) )); mi.push(MenuItem("<- Restart", "", tvm.functionId(mainMenu) )); Menu.select("Enter your choice: ", "", mi); } function _symbolPairProvideLiquidity_2(uint32 index) public { _provideLiquiditySymbol = (index == 0 ? _selectedSymbol1 : _selectedSymbol2); ILiquidFTRoot(_provideLiquiditySymbol.addressRTW).getWalletAddress{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairProvideLiquidity_3), onErrorId: tvm.functionId(onError) }(_msigAddress); } function _symbolPairProvideLiquidity_3(address value) public { _provideLiquidityWalletAddress = value; Sdk.getAccountType(tvm.functionId(_symbolPairProvideLiquidity_4), _provideLiquidityWalletAddress); } function _symbolPairProvideLiquidity_4(int8 acc_type) public { if (acc_type == -1 || acc_type == 0) { Terminal.print(0, format("You don't have a Token wallet!")); _symbolPairMenu_1(0); } else if (acc_type == 1) { _symbolPairProvideLiquidity_5(0); } else if (acc_type == 2) { Terminal.print(0, format("Your Token wallet Wallet is FROZEN.")); _mainLoop(0); } } function _symbolPairProvideLiquidity_5(uint32 index) public { index = 0; // shut a warning AmountInput.get(tvm.functionId(_symbolPairProvideLiquidity_6), format("Enter amount of {} to deposit: ", _provideLiquiditySymbol.symbol), _provideLiquiditySymbol.decimals, 0, 999999999999999999999999999999); } function _symbolPairProvideLiquidity_6(uint256 value) public view { TvmBuilder builder; builder.store(uint8(1), uint128(0), uint16(0)); TvmCell body = tvm.encodeBody(ILiquidFTWallet.transfer, uint128(value), _symbolPairAddress, _msigAddress, addressZero, builder.toCell()); _sendTransact(_msigAddress, _provideLiquidityWalletAddress, body, ATTACH_VALUE); _symbolPairMenu_1(0); } //======================================== //======================================== //======================================== //======================================== //======================================== // TODO: including LP wallet deployment function _symbolPairDepositLiquidity_1(uint32 index) public view { index = 0; // shut a warning ILiquidFTRoot(_symbolPairAddress).getWalletAddress{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairDepositLiquidity_2), onErrorId: tvm.functionId(onError) }(_msigAddress); } function _symbolPairDepositLiquidity_2(address value) public { _lpWalletAddress = value; Sdk.getAccountType(tvm.functionId(_symbolPairDepositLiquidity_3), _lpWalletAddress); } function _symbolPairDepositLiquidity_3(int8 acc_type) public { if (acc_type == -1 || acc_type == 0) { // TODO: notify that we are deploying LP wallet; + // also, check that wallet was created; Terminal.print(0, "You don't have LP wallet, deploy?"); TvmCell body = tvm.encodeBody(ILiquidFTRoot.createWallet, _msigAddress, addressZero, 0); _sendTransact(_msigAddress, _symbolPairAddress, body, ATTACH_VALUE); _symbolPairDepositLiquidity_4(0); } else if (acc_type == 1) { _symbolPairDepositLiquidity_4(0); } else if (acc_type == 2) { Terminal.print(0, format("Your LP Wallet is FROZEN.")); _mainLoop(0); } } function _symbolPairDepositLiquidity_4(uint32 index) public { index = 0; // shut a warning AmountInput.get(tvm.functionId(_symbolPairDepositLiquidity_5), format("Enter amount of {} to deposit: ", _selectedSymbol1.symbol), _selectedSymbol1.decimals, 0, 999999999999999999999999999999); } function _symbolPairDepositLiquidity_5(uint256 value) public { _depositAmount1 = uint128(value); AmountInput.get(tvm.functionId(_symbolPairDepositLiquidity_6), format("Enter amount of {} to deposit: ", _selectedSymbol2.symbol), _selectedSymbol2.decimals, 0, 999999999999999999999999999999); } function _symbolPairDepositLiquidity_6(uint256 value) public { _depositAmount2 = uint128(value); AmountInput.get(tvm.functionId(_symbolPairDepositLiquidity_7), "Enter Slippage in %: ", 2, 0, 10000); } function _symbolPairDepositLiquidity_7(uint256 value) public { _depositSlippage = uint16(value); // TODO: text? TvmCell body = tvm.encodeBody(ISymbolPair.depositLiquidity, _depositAmount1, _depositAmount2, uint16(_depositSlippage)); _sendTransact(_msigAddress, _symbolPairAddress, body, ATTACH_VALUE); _symbolPairMenu_1(0); } //======================================== //======================================== //======================================== //======================================== //======================================== // TODO: we catually can be missing TTWs if we just bought liquidity tokens function _symbolPairWithdrawLiquidity_1(uint32 index) public view { index = 0; // shut a warning ILiquidFTRoot(_symbolPairAddress).getWalletAddress{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairWithdrawLiquidity_2), onErrorId: tvm.functionId(onError) }(_msigAddress); } function _symbolPairWithdrawLiquidity_2(address value) public { _lpWalletAddress = value; Sdk.getAccountType(tvm.functionId(_symbolPairWithdrawLiquidity_3), _lpWalletAddress); } function _symbolPairWithdrawLiquidity_3(int8 acc_type) public { if (acc_type == -1 || acc_type == 0) { // TODO: notify that we are deploying LP wallet; + // also, check that wallet was created; Terminal.print(0, "Oops, looks like you don't have LP wallet, that means you don't have liquidity to withdraw (sorry bout that)."); _symbolPairMenu_1(0); } else if (acc_type == 1) { _symbolPairWithdrawLiquidity_4(0); } else if (acc_type == 2) { Terminal.print(0, format("Your LP Wallet is FROZEN (oopsie).")); _symbolPairMenu_1(0); } } function _symbolPairWithdrawLiquidity_4(uint32 index) public view { index = 0; // shut a warning ILiquidFTWallet(_lpWalletAddress).getBalance{ abiVer: 2, extMsg: true, sign: false, time: uint64(now), expire: 0, pubkey: _emptyPk, callbackId: tvm.functionId(_symbolPairWithdrawLiquidity_5), onErrorId: tvm.functionId(onError) }(); } function _symbolPairWithdrawLiquidity_5(uint128 balance) public { Terminal.print(0, format("You currently have {} Liquidity tokens.", balance)); AmountInput.get(tvm.functionId(_symbolPairWithdrawLiquidity_6), "Enter amount to withdraw: ", 18, 0, 999999999999999999999999999999); } function _symbolPairWithdrawLiquidity_6(int256 value) public view { TvmCell body = tvm.encodeBody(ILiquidFTWallet.burn, uint128(value)); _sendTransact(_msigAddress, _lpWalletAddress, body, ATTACH_VALUE); _symbolPairMenu_1(0); // TODO: other menu? maybe some message? } //======================================== //======================================== //======================================== //======================================== //======================================== // function _symbolPairWithdrawLiquidityLeftovers_1(uint32 index) public view { index = 0; // shut a warning TvmCell body = tvm.encodeBody(ISymbolPair.collectLiquidityLeftovers); _sendTransact(_msigAddress, _symbolPairAddress, body, ATTACH_VALUE); _symbolPairMenu_1(0); // TODO: other menu? maybe some message? } //======================================== // // 1. main menu: add symbol, get symbol pair to trade // 2.1. if adding symbol, enter rtw address; // 2.2. after entering send transaction and go to main menu // 3.1. if getting symbol, show list of symbols to choose 1st // 3.2. show list of symbols to choose 2nd // 3.3. check if pair exists, if it doesn't ask to deploy it // 3.4. if pair exists get pair information and show current info. // 4. get three wallets silently (we need to know if user has wallet A, wallet B and liquidity wallet) // 4. you need to choose, buy, sell, deposit, finalize or withdraw leftovers; // 4.1. if depositing, if walletA or walletB doesn't exist, say you can't deposit without wallets and go to menu 4; // 4.3. ask to send amount of symbol A // 4.4. ask to send amount of symbol B // 4.5. if finalizing, ask to create LP wallet if it doesn't exist; // 4.6. if finalizing, show current leftovers and pair ratio ask the amount symbol A to deposit; // 4.7. calculate symbol B based on amount, ask what slippage is good; // 4.8. send finalize; // 5. if buying, ask to create wallets that you don't have before that; // 5.1. after that ask for the amount to buy; // 5.2. ask for the slippage to buy; // 5.3. send transaction; // 6. if withdraw leftovers, we know that both wallets exist, just do that; //======================================== // function _sendTransact(address msigAddr, address dest, TvmCell payload, uint128 grams) internal pure { IMsig(msigAddr).sendTransaction{ abiVer: 2, extMsg: true, sign: true, callbackId: 0, onErrorId: tvm.functionId(onError), time: uint32(now), expire: 0, pubkey: 0x00 }(dest, grams, false, 1, payload); } } //================================================================================ //
======================================== Inline functions
function _sortSymbols(Symbol sym1, Symbol sym2) internal inline pure returns (Symbol, Symbol) { return (sym1.addressRTW < sym2.addressRTW ? (sym1, sym2) : (sym2, sym1)); }
6,478,815
./full_match/3/0x103E9df0BF772478b0031F57C424CD856B34EDa9/sources/demo2.sol
See {IaNFTEnumerable-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < aNFT.balanceOf(owner), "aNFTEnumerable: owner index out of bounds"); return _ownedTokens[owner][index]; }
14,157,462
./partial_match/1/0xDe74Bd8cE7b7e4F1418Ba235ab1b774d4717d61a/sources/FishiesToken.sol
Only the contract owner can use this function
function setExemptStatus(address account, bool _isExempt) public onlyOwner { isExempt[account] = _isExempt; }
2,638,730
/** *Submitted for verification at polygonscan.com on 2021-06-23 */ import "@Uniswap/contracts/libraries/Math.sol"; //import "@Uniswap/contracts/interfaces/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // File: contracts/lib/SafeMath.sol pragma solidity ^0.5.16; /** * @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 SafeMathCometh { /** * @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; } } // File: contracts/lib/Address.sol /*pragma solidity ^0.5.16; * * @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. * * > 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } */ // File: contracts/lib/SafeERC20.sol //pragma solidity ^0.5.16; /** * @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 SafeMathCometh 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 ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } */ /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } */ // File: contracts/ERC20Detailed.sol pragma solidity ^0.5.16; /** * @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; } } // File: contracts/ReentrancyGuard.sol pragma solidity ^0.5.16; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require( localCounter == _guardCounter, "ReentrancyGuard: reentrant call" ); } } // File: contracts/interfaces/IStakingMultiRewards.sol pragma solidity ^0.5.16; // Inheritancea interface IStakingMultiRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardsPerToken() external view returns (uint256[] memory); function earned(address account) external view returns (uint256[] memory); function getRewardsForDuration() external view returns (uint256[] memory); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } import "@Uniswap/contracts/interfaces/IUniswapV2ERC20.sol"; // File: contracts/StakingMultiRewards.sol /** *Submitted for verification at Etherscan.io on 2020-09-16 */ pragma solidity ^0.5.16; contract MultiRewardsDistributionRecipient { address public rewardsDistribution; function notifyRewardAmount(uint256[] calldata reward) external; modifier onlyRewardsDistribution() { require( msg.sender == rewardsDistribution, "Caller is not MultiRewardsDistribution contract" ); _; } } contract StakingMultiRewards is IStakingMultiRewards, MultiRewardsDistributionRecipient, ReentrancyGuard { using SafeMathCometh for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20[] public rewardsTokens; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256[] public rewardRates; uint256 public rewardsDuration = 7 days; uint256 public lastUpdateTime; uint256[] public rewardsPerTokenStored; mapping(address => uint256[]) public userRewardPerTokenPaid; mapping(address => uint256[]) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _rewardsDistribution, IERC20[] memory _rewardsTokens, address _stakingToken ) public { rewardsTokens = _rewardsTokens; rewardRates = new uint256[](_rewardsTokens.length); rewardsPerTokenStored = new uint256[](_rewardsTokens.length); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function getRewardsPerTokenStored() external view returns (uint256[] memory) { return rewardsPerTokenStored; } function getRewardsTokens() external view returns (IERC20[] memory) { return rewardsTokens; } function getRewardRates() external view returns (uint256[] memory) { return rewardRates; } function getUserRewardPerTokenPaid(address user) external view returns (uint256[] memory) { return userRewardPerTokenPaid[user]; } function getRewards(address user) external view returns (uint256[] memory) { return rewards[user]; } function rewardsPerToken() public view returns (uint256[] memory) { if (_totalSupply == 0) { return rewardsPerTokenStored; } uint256[] memory _rewards = rewardsPerTokenStored; for (uint256 i = 0; i < rewardsPerTokenStored.length; i++) { _rewards[i] = _rewards[i].add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRates[i]) .mul(1e18) .div(_totalSupply) ); } return _rewards; } function earned(address account) public view returns (uint256[] memory) { uint256[] memory _rewards = rewardsPerToken(); uint256[] memory earnings = new uint256[](_rewards.length); uint256 balance = _balances[account]; uint256[] memory paidRewards = userRewardPerTokenPaid[account]; uint256[] memory accountRewards = rewards[account]; for (uint256 i = 0; i < _rewards.length; i++) { uint256 paid = 0; if (paidRewards.length > 0) { paid = paidRewards[i]; } uint256 reward = 0; if (accountRewards.length > 0) { reward = accountRewards[i]; } earnings[i] = balance.mul(_rewards[i].sub(paid)).div(1e18).add( reward ); } return earnings; } function getRewardsForDuration() external view returns (uint256[] memory) { uint256[] memory copy = rewardRates; for (uint256 i = 0; i < copy.length; i++) { copy[i] = copy[i].mul(rewardsDuration); } return copy; } /* ========== MUTATIVE FUNCTIONS ========== */ function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant updateRewards(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); // permit IUniswapV2ERC20(address(stakingToken)).permit( msg.sender, address(this), amount, deadline, v, r, s ); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function stake(uint256 amount) external nonReentrant updateRewards(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateRewards(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateRewards(msg.sender) { uint256[] memory _rewards = rewards[msg.sender]; for (uint256 i = 0; i < _rewards.length; i++) { uint256 reward = _rewards[i]; if (reward > 0) { rewards[msg.sender][i] = 0; rewardsTokens[i].safeTransfer(msg.sender, reward); } } emit RewardPaid(msg.sender, _rewards); } function exit() external { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256[] calldata addedRewards) external onlyRewardsDistribution updateRewards(address(0)) { require( rewardsTokens.length == addedRewards.length, "Added rewards and rewards length not equal" ); for (uint256 i = 0; i < addedRewards.length; i++) { if (block.timestamp >= periodFinish) { rewardRates[i] = addedRewards[i].div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRates[i]); rewardRates[i] = addedRewards[i].add(leftover).div( rewardsDuration ); } // Ensure 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 = rewardsTokens[i].balanceOf(address(this)); require( rewardRates[i] <= balance.div(rewardsDuration), "Provided reward too high" ); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(addedRewards); } /* ========== MODIFIERS ========== */ modifier updateRewards(address account) { rewardsPerTokenStored = rewardsPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardsPerTokenStored; } _; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardAdded(uint256[] reward); event RewardPaid(address indexed user, uint256[] rewards); }
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. solhint-disable-next-line no-inline-assembly
function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; }
13,005,828
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; //pragma experimental ABIEncoderV2; //pragma solidity ^0.5.0; import "./base/Ownable.sol"; import "./SupplychainHub.sol"; import "./registration/StandardRegisterUserHub.sol"; // Controller contract for product interaction & workflow contract ProductHub is Ownable { SupplychainHub supplychainProductStateContract; StandardRegisterUserHub standardRegisterUserHubContract; struct product { uint256 universalProductCode; bytes32 cropName; uint256 quantity; uint256 expectedPrice; uint256 requiredFunding; uint256 availableFunding; address payable ownerAccount; } mapping(uint256 => product) productIdToProductMapping; constructor( SupplychainHub _supplychainProductStateContract, StandardRegisterUserHub _standardRegisterUserHubContract ) public Ownable() { supplychainProductStateContract = _supplychainProductStateContract; standardRegisterUserHubContract = _standardRegisterUserHubContract; require( _standardRegisterUserHubContract.registerUserInternal( "Crowdfunded Agriculture Marketplace Manager", 6, //StandardRegisterUserHub.UserRoleType.MarketplaceManager msg.sender // Sent as argument as it gets overridden by this contract address in upper call stack ), "Failed to register deploying account in Marketplace manager role" ); } /** * Get universal product code counter * Used to list all products * */ function upc() public view returns (uint256) { return supplychainProductStateContract.upc(); } /** * Get supply chain state of a product by productID * */ function getSupplychainStage(uint256 _upc) public view returns (uint256) { return uint256(supplychainProductStateContract.getSupplychainStatus(_upc)); } /** * Modifier for funder(Investor/Donor) user verification * */ modifier isFunder(uint8 _userRoleType) { require(_userRoleType == 2 || _userRoleType == 3); _; } /** * Fund product identified by productID, * for userRoleType & receiver address - receives the fund */ function fundProduct( address payable receiver, uint8 userRoleType, uint8 _universalProductCode ) public payable isFunder(userRoleType) returns (bool) { require(msg.sender.balance >= msg.value); product storage p = productIdToProductMapping[_universalProductCode]; uint256 amount = msg.value; if (p.requiredFunding <= amount) { //Required funding amount = p.requiredFunding; } p.requiredFunding -= amount; //Required funding p.availableFunding += amount; //Available funding require(receiver.send(amount)); if (amount < msg.value) { require(msg.sender.send(msg.value - amount)); } require( supplychainProductStateContract.acceptFundsFromSender( _universalProductCode, userRoleType, msg.sender, amount ) ); if (p.requiredFunding == 0) { require( supplychainProductStateContract.updateSupplychainStatus( p.universalProductCode, SupplychainHub.SupplychainStage.ProductFunded ) ); } return true; } /** * Move product identified by product code to harvest state * */ function harvestProduct(uint256 _upc) public payable returns (bool) { require( supplychainProductStateContract.getSupplychainStatus(_upc) == SupplychainHub.SupplychainStage.ProductFunded ); product storage p = productIdToProductMapping[_upc]; // Transfer obtained funds to market place to perform settlement later address payable marketplaceOwner = supplychainProductStateContract .getOwner(); // Ensure sent value is more than available funding // TODO: Implement payment channel contract between parties require(msg.value >= p.availableFunding); // Transfer crowd funded amount to market owner require(marketplaceOwner.send(p.availableFunding)); //Return change to sender require(msg.sender.send(msg.value - p.availableFunding)); require( supplychainProductStateContract.updateSupplychainStatus( _upc, SupplychainHub.SupplychainStage.Harvested ) ); return true; } /** * Move product to market place and pay out investors * Supplychain hub makes the purchase * Read: https://docs.soliditylang.org/en/v0.6.0/common-patterns.html?highlight=transfer#withdrawal-from-contracts */ function markProductForSale(uint256 _upc) public payable returns (bool) { require( supplychainProductStateContract.getSupplychainStatus(_upc) == SupplychainHub.SupplychainStage.Harvested ); product storage p = productIdToProductMapping[_upc]; // Sell to Supply chain hub address payable marketplaceOwner = supplychainProductStateContract .getOwner(); require(msg.sender == marketplaceOwner); // Supplychain hub makes owner transfer & pays farmer expected price require(msg.value >= p.expectedPrice); // Farmers(owner) receive expected price address payable seller = p.ownerAccount; require(seller.send(p.expectedPrice)); //Change ownership to market place p.ownerAccount = marketplaceOwner; require( supplychainProductStateContract.updateSupplychainStatus( _upc, SupplychainHub.SupplychainStage.OnSale ) ); return true; } /** * Receive Payout from Marketplace by investor * */ function sendMarketplacePayoutToInvestor( uint256 _upc, address payable investor ) public payable returns (bool) { uint256 payoutAmount = supplychainProductStateContract .getPayoutAmountForContributor(_upc, investor); require( msg.value >= payoutAmount, "Sent amount less than total payout amount" ); require(investor.send(payoutAmount)); require( supplychainProductStateContract.markFundsReleasedToContributor( _upc, investor ) ); return true; } /** * Move product to market place and pay out investors * Supplychain hub makes the purchase */ function saleToCustomer(uint256 _upc) public payable returns (bool) { require( supplychainProductStateContract.getSupplychainStatus(_upc) == SupplychainHub.SupplychainStage.OnSale ); product storage p = productIdToProductMapping[_upc]; require(msg.value >= p.expectedPrice); // Supply chain hub paid address payable marketOwner = p.ownerAccount; require(marketOwner.send(msg.value)); //TransferOwnership p.ownerAccount = msg.sender; require(p.ownerAccount == msg.sender); require( supplychainProductStateContract.updateSupplychainStatus( _upc, SupplychainHub.SupplychainStage.Sold ) ); return true; } /** * Get balance amount of user address * */ function getBalance(address addr) public view returns (uint256) { return addr.balance; //balances[addr]; } /** * Publish a product campaign onto portal * */ function produce( bytes32 cropName, uint256 quantity, uint256 expectedPrice, uint256 requiredFunding ) public returns (bool) { uint256 currentUPC = supplychainProductStateContract.upc(); ProductHub.product memory fnew = product( currentUPC, cropName, quantity, expectedPrice, requiredFunding, 0, msg.sender ); productIdToProductMapping[currentUPC] = fnew; require(supplychainProductStateContract.incrementProductCodeCounter()); supplychainProductStateContract.updateSupplychainStatus( currentUPC, SupplychainHub.SupplychainStage.ProductPublished ); return true; } /** * Get product details by productID * */ function getproduce(uint256 universalProductCode) public view returns ( uint256, bytes32, uint256, uint256, uint256, uint256, address ) { return ( productIdToProductMapping[universalProductCode] .universalProductCode, productIdToProductMapping[universalProductCode].cropName, productIdToProductMapping[universalProductCode].quantity, productIdToProductMapping[universalProductCode].expectedPrice, productIdToProductMapping[universalProductCode].requiredFunding, productIdToProductMapping[universalProductCode].availableFunding, productIdToProductMapping[universalProductCode].ownerAccount ); } /** * Get payout amount for given contributor to given product * */ function getPayoutAmountForContributorToAProduct( uint256 _upc, address payable contributor ) public view returns (uint256) { require(_upc > 0); require(contributor != address(0)); return supplychainProductStateContract.getPayoutAmountForContributor( _upc, contributor ); } /** * Get list of contributors for given product * */ function getContributorFromListForAProduct(uint256 _upc, uint256 entryNum) public view returns (address) { require(_upc > 0); return supplychainProductStateContract.getFromListOfPayblesForProduct( _upc, entryNum ); } /** * Get total number of investors for a product * */ function getNumberOfInvestorsForAProduct(uint256 _universalProductCode) public view returns (uint256) { require(_universalProductCode > 0); return supplychainProductStateContract.getNumberOfPayblesForProduct( _universalProductCode ); } // event Received(address, uint256); // receive() external payable { // emit Received(msg.sender, msg.value); // } // // Investors paid out by market place,i.e. current owner of product // address[] memory investors = supplychainProductStateContract // .getListOfPayblesForProduct(_upc); // for (uint8 i = 0; i < investors.length; ++i) { // uint256 amount = supplychainProductStateContract // .getPaybleOwedAmountForProduct(_upc, investors[i]); // //require((payable(investors[i])).send(amount)); // require( // supplychainProductStateContract.markFundsReleasedToContributor( // _upc, // payable(investors[i]) // ) // ); // } }
Get total number of investors for a product/
function getNumberOfInvestorsForAProduct(uint256 _universalProductCode) public view returns (uint256) { require(_universalProductCode > 0); return supplychainProductStateContract.getNumberOfPayblesForProduct( _universalProductCode ); }
15,817,031
// File: contracts/token/GovernanceStorage.sol pragma solidity 0.5.16; /* Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ contract GovernanceStorage { /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/token/TokenStorage.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; contract TokenStorage { using SafeMath for uint256; /** * @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 Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Approved token emitter for this contract */ address public emission; /** * @notice Approved token guardian for this contract */ address public guardian; /** * @notice Total supply of LIFE */ uint256 public totalSupply; /** * @notice Used for pausing and unpausing */ bool internal _paused = false; /** * @notice Used for checking validity of Guardian */ uint256 public guardianExpiration = block.timestamp.add(78 weeks); // Guardian expires in 1.5 years /** * @notice used for tracking freeze timestamp */ mapping(address => uint256) internal lastFrozen; uint256 public freezeDelay = 14 days; // Delay between freezing the same target multiple times to avoid abuse /** * @notice Used for balance of the users and allowances */ mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowedBalances; bool public initialized = false; uint256 public currentSupply; } // File: contracts/token/TokenInterface.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; contract TokenInterface is TokenStorage, GovernanceStorage { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Event emitted when Emssion is changed */ event NewEmission(address oldEmission, address newEmission); /** * @notice Event emitted when Guardian is changed */ event NewGuardian(address oldGuardian, address newGuardian); /** * @notice Event emitted when the pause is triggered. */ event Paused(address account); /** * @dev Event emitted when the pause is lifted. */ event Unpaused(address account); /* - ERC20 Events - */ /** * @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); /* - Extra Events - */ /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); event Burn(address from, uint256 amount); // Public functions function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /* - Governance Functions - */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256); // function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function mint(address to, uint256 amount) external returns (bool); function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } // File: contracts/token/Governance.sol pragma solidity 0.5.16; /* Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ contract GovernanceToken is TokenInterface { /// @notice An event emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Get delegatee for an address delegating * @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 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, "LIFE::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 = _balances[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, "LIFE::_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); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/access/Roles.sol 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]; } } // File: Modifier from : @openzeppelin/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract Frozen { using Roles for Roles.Role; event AccountFrozen(address indexed account); event AccountUnfrozen(address indexed account); Roles.Role private _frozen; modifier checkFrozen(address from) { require(!isFrozen(from), "Frozen: Sender's tranfers are frozen"); _; } function isFrozen(address account) public view returns (bool) { return _frozen.has(account); } function _freezeAccount(address account) internal { _frozen.add(account); emit AccountFrozen(account); } function _unfreezeAccount(address account) internal { _frozen.remove(account); emit AccountUnfrozen(account); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/LIFE.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.5.16; contract LIFEToken is GovernanceToken, Frozen { // Modifiers modifier onlyGov() { require(msg.sender == gov, "only governance"); _; } modifier onlyMinter() { require( msg.sender == emission || msg.sender == gov, "not minter" ); _; } modifier onlyEmergency() { require( msg.sender == guardian || msg.sender == gov, "not guardian or governor" ); _; } modifier whenNotPaused() { require(_paused == false, "Pausable: paused"); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(initialized == false, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Allows the pausing and unpausing of certain functions . * @dev Limited to onlyMinter modifier */ function pause() public onlyEmergency { _paused = true; emit Paused(msg.sender); } function unpause() public onlyEmergency { _paused = false; emit Unpaused(msg.sender); } /** * @notice Mints new tokens, increasing currentSupply . * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter whenNotPaused returns (bool) { _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { require(currentSupply.add(amount) <= totalSupply, "Emission exceeds total supply"); // increase currentSupply currentSupply = currentSupply.add(amount); // add balance _balances[to] = _balances[to].add(amount); // add delegates to the minter _moveDelegates(address(0), _delegates[to], amount); emit Mint(to, amount); emit Transfer(address(0), to, amount); } /** * @notice Burns tokens, decreasing totalSupply, currentSupply, and a users balance. */ function burn(uint256 amount) external returns (bool) { _burn(msg.sender, amount); return true; } function _burn(address from, uint256 amount) internal { // decrease totalSupply totalSupply = totalSupply.sub(amount); // decrease currentSupply currentSupply = currentSupply.sub(amount); // sub balance, will revert on underflow _balances[from] = _balances[from].sub(amount); // remove delegates from the minter _moveDelegates(_delegates[from], address(0), amount); emit Burn(from, amount); emit Transfer(from, address(0), amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) checkFrozen(msg.sender) whenNotPaused returns (bool) { // sub from balance of sender _balances[msg.sender] = _balances[msg.sender].sub(value); // add to balance of receiver _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], value); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) checkFrozen(from) whenNotPaused returns (bool) { // decrease allowance _allowedBalances[from][msg.sender] = _allowedBalances[from][msg.sender].sub(value); // sub from balance _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], value); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _balances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedBalances[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedBalances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedBalances[msg.sender][spender] = _allowedBalances[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedBalances[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedBalances[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedBalances[msg.sender][spender] = 0; } else { _allowedBalances[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedBalances[msg.sender][spender]); return true; } /* - Governance Functions - */ /** @notice sets the emission * @param emission_ The address of the emission contract to use for authentication. */ function _setEmission(address emission_) external onlyGov { address oldEmission = emission; emission = emission_; emit NewEmission(oldEmission, emission_); } /** @notice sets the emission * @param guardian_ The address of the guardian contract to use for authentication. */ function _setGuardian(address guardian_) external onlyEmergency { require(block.timestamp < guardianExpiration); // Can only set new guardian if guardian powers havn't expired yet address oldGuardian = guardian; guardian = guardian_; emit NewGuardian(oldGuardian, guardian_); } function freezeTargetFunds(address target) external onlyEmergency { require(lastFrozen[target].add(freezeDelay) < block.timestamp, "Target was Frozen recently"); lastFrozen[target] = block.timestamp; _freezeAccount(target); } function unfreezeTargetFunds(address target) external onlyEmergency { _unfreezeAccount(target); } /** @notice lets msg.sender abolish guardian * */ function abolishGuardian() external { require(msg.sender == guardian || block.timestamp >= guardianExpiration); // Can be abolished by anyone after expiration or anytime by guardian themselves guardian = address(0); } /** @notice sets the pendingGov * @param pendingGov_ The address of the governor contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Rescue tokens function rescueTokens( address token, address to, uint256 amount ) external onlyGov returns (bool) { // transfer to SafeERC20.safeTransfer(IERC20(token), to, amount); return true; } } contract LIFE is LIFEToken { constructor() public {} /** * @notice Initialize the new money market * @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( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_, uint256 totalSupply_ ) public { super.initialize(name_, symbol_, decimals_); initialized = true; currentSupply = initSupply_; totalSupply = totalSupply_; _balances[initial_owner] = currentSupply; gov = initial_owner; guardian = initial_owner; } }
Decrease the amount of tokens that an owner has allowed to a spender. spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by./
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedBalances[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedBalances[msg.sender][spender] = 0; _allowedBalances[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedBalances[msg.sender][spender]); return true; }
7,016,254
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./ModuleMapConsumer.sol"; import "../interfaces/IKernel.sol"; abstract contract Controlled is Initializable, ModuleMapConsumer { // controller address => is a controller mapping(address => bool) internal _controllers; address[] public controllers; function __Controlled_init(address[] memory controllers_, address moduleMap_) public initializer { for (uint256 i; i < controllers_.length; i++) { _controllers[controllers_[i]] = true; } controllers = controllers_; __ModuleMapConsumer_init(moduleMap_); } function addController(address controller) external onlyOwner { _controllers[controller] = true; bool added; for (uint256 i; i < controllers.length; i++) { if (controller == controllers[i]) { added = true; } } if (!added) { controllers.push(controller); } } modifier onlyOwner() { require( IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isOwner(msg.sender), "Controlled::onlyOwner: Caller is not owner" ); _; } modifier onlyManager() { require( IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isManager(msg.sender), "Controlled::onlyManager: Caller is not manager" ); _; } modifier onlyController() { require( _controllers[msg.sender], "Controlled::onlyController: Caller is not controller" ); _; } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IModuleMap.sol"; abstract contract ModuleMapConsumer is Initializable { IModuleMap public moduleMap; function __ModuleMapConsumer_init(address moduleMap_) internal initializer { moduleMap = IModuleMap(moduleMap_); } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./Controlled.sol"; import "./ModuleMapConsumer.sol"; import "../interfaces/ISushiSwapTrader.sol"; import "../interfaces/ISushiSwapFactory.sol"; import "../interfaces/ISushiSwapRouter.sol"; import "../interfaces/ISushiSwapPair.sol"; import "../interfaces/IIntegrationMap.sol"; /// @notice Integrates 0x Nodes to SushiSwap contract SushiSwapTrader is Initializable, ModuleMapConsumer, Controlled, ISushiSwapTrader { using SafeERC20Upgradeable for IERC20MetadataUpgradeable; uint24 private constant SLIPPAGE_DENOMINATOR = 1_000_000; uint24 private slippageNumerator; address private factoryAddress; address private swapRouterAddress; event ExecutedSwapExactInput( address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMin, uint256 amountOut ); event FailedSwapExactInput( address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMin ); event SushiSwapSlippageNumeratorUpdated(uint24 slippageNumerator); /// @param controllers_ The addresses of the controlling contracts /// @param moduleMap_ The address of the module map contract /// @param factoryAddress_ The address of the SushiSwap factory contract /// @param swapRouterAddress_ The address of the SushiSwap swap router contract /// @param slippageNumerator_ The number divided by the slippage denominator to get the slippage percentage function initialize( address[] memory controllers_, address moduleMap_, address factoryAddress_, address swapRouterAddress_, uint24 slippageNumerator_ ) public initializer { require( slippageNumerator <= SLIPPAGE_DENOMINATOR, "SushiSwapTrader::initialize: Slippage Numerator must be less than or equal to slippage denominator" ); __Controlled_init(controllers_, moduleMap_); __ModuleMapConsumer_init(moduleMap_); factoryAddress = factoryAddress_; swapRouterAddress = swapRouterAddress_; slippageNumerator = slippageNumerator_; } /// @param slippageNumerator_ The number divided by the slippage denominator to get the slippage percentage function updateSlippageNumerator(uint24 slippageNumerator_) external override onlyManager { require( slippageNumerator_ != slippageNumerator, "SushiSwapTrader::setSlippageNumerator: Slippage numerator must be set to a new value" ); require( slippageNumerator <= SLIPPAGE_DENOMINATOR, "SushiSwapTrader::setSlippageNumerator: Slippage Numerator must be less than or equal to slippage denominator" ); slippageNumerator = slippageNumerator_; emit SushiSwapSlippageNumeratorUpdated(slippageNumerator_); } /// @notice Swaps all WETH held in this contract for BIOS and sends to the kernel /// @return Bool indicating whether the trade succeeded function biosBuyBack() external override onlyController returns (bool) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); address wethAddress = integrationMap.getWethTokenAddress(); address biosAddress = integrationMap.getBiosTokenAddress(); uint256 wethAmountIn = IERC20MetadataUpgradeable(wethAddress).balanceOf( address(this) ); uint256 biosAmountOutMin = getAmountOutMinimum( wethAddress, biosAddress, wethAmountIn ); return swapExactInput( wethAddress, integrationMap.getBiosTokenAddress(), moduleMap.getModuleAddress(Modules.Kernel), wethAmountIn, biosAmountOutMin ); } /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address of the token out recipient /// @param amountIn The exact amount of the input to swap /// @param amountOutMin The minimum amount of tokenOut to receive from the swap /// @return bool Indicates whether the swap succeeded function swapExactInput( address tokenIn, address tokenOut, address recipient, uint256 amountIn, uint256 amountOutMin ) public override onlyController returns (bool) { require( IERC20MetadataUpgradeable(tokenIn).balanceOf(address(this)) >= amountIn, "SushiSwapTrader::swapExactInput: Balance is less than trade amount" ); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; uint256 deadline = block.timestamp; if ( IERC20MetadataUpgradeable(tokenIn).allowance( address(this), swapRouterAddress ) == 0 ) { IERC20MetadataUpgradeable(tokenIn).safeApprove( swapRouterAddress, type(uint256).max ); } uint256 tokenOutBalanceBefore = IERC20MetadataUpgradeable(tokenOut) .balanceOf(recipient); try ISushiSwapRouter(swapRouterAddress).swapExactTokensForTokens( amountIn, amountOutMin, path, recipient, deadline ) { emit ExecutedSwapExactInput( tokenIn, tokenOut, amountIn, amountOutMin, IERC20MetadataUpgradeable(tokenOut).balanceOf(recipient) - tokenOutBalanceBefore ); return true; } catch { emit FailedSwapExactInput(tokenIn, tokenOut, amountIn, amountOutMin); return false; } } /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param amountIn The exact amount of the input to swap /// @return amountOutMinimum The minimum amount of tokenOut to receive, factoring in allowable slippage function getAmountOutMinimum( address tokenIn, address tokenOut, uint256 amountIn ) public view returns (uint256 amountOutMinimum) { amountOutMinimum = (getAmountOut(tokenIn, tokenOut, amountIn) * (SLIPPAGE_DENOMINATOR - slippageNumerator)) / SLIPPAGE_DENOMINATOR; } /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param amountIn The exact amount of the input to swap /// @return amountOut The estimated amount of tokenOut to receive function getAmountOut( address tokenIn, address tokenOut, uint256 amountIn ) public view returns (uint256 amountOut) { require( amountIn > 0, "SushiSwapTrader::getAmountOut: amountIn must be greater than zero" ); (uint256 reserveIn, uint256 reserveOut) = getReserves(tokenIn, tokenOut); require( reserveIn > 0 && reserveOut > 0, "SushiSwapTrader::getAmountOut: No liquidity in pool reserves" ); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * (reserveOut); uint256 denominator = reserveIn * 1000 + amountInWithFee; amountOut = numerator / denominator; } /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return reserveA The reserve balance of tokenA in the pool /// @return reserveB The reserve balance of tokenB in the pool function getReserves(address tokenA, address tokenB) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = getTokensSorted(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = ISushiSwapPair( getPairFor(tokenA, tokenB) ).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return token0 The address of sorted token0 /// @return token1 The address of sorted token1 function getTokensSorted(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require( tokenA != tokenB, "SushiSwapTrader::sortToken: Identical token addresses" ); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "SushiSwapTrader::sortToken: Zero address"); } /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return pair The address of the SushiSwap pool contract function getPairFor(address tokenA, address tokenB) internal view returns (address pair) { pair = ISushiSwapFactory(factoryAddress).getPair(tokenA, tokenB); } /// @return SushiSwap Factory address function getFactoryAddress() public view returns (address) { return factoryAddress; } /// @return The slippage numerator function getSlippageNumerator() public view returns (uint24) { return slippageNumerator; } /// @return The slippage denominator function getSlippageDenominator() public pure returns (uint24) { return SLIPPAGE_DENOMINATOR; } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IIntegrationMap { struct Integration { bool added; string name; } struct Token { uint256 id; bool added; bool acceptingDeposits; bool acceptingWithdrawals; uint256 biosRewardWeight; uint256 reserveRatioNumerator; } /// @param contractAddress The address of the integration contract /// @param name The name of the protocol being integrated to function addIntegration(address contractAddress, string memory name) external; /// @param tokenAddress The address of the ERC20 token contract /// @param acceptingDeposits Whether token deposits are enabled /// @param acceptingWithdrawals Whether token withdrawals are enabled /// @param biosRewardWeight Token weight for BIOS rewards /// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio function addToken( address tokenAddress, bool acceptingDeposits, bool acceptingWithdrawals, uint256 biosRewardWeight, uint256 reserveRatioNumerator ) external; /// @param tokenAddress The address of the token ERC20 contract function enableTokenDeposits(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function disableTokenDeposits(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function enableTokenWithdrawals(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function disableTokenWithdrawals(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract /// @param rewardWeight The updated token BIOS reward weight function updateTokenRewardWeight(address tokenAddress, uint256 rewardWeight) external; /// @param tokenAddress the address of the token ERC20 contract /// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio function updateTokenReserveRatioNumerator( address tokenAddress, uint256 reserveRatioNumerator ) external; /// @param integrationId The ID of the integration /// @return The address of the integration contract function getIntegrationAddress(uint256 integrationId) external view returns (address); /// @param integrationAddress The address of the integration contract /// @return The name of the of the protocol being integrated to function getIntegrationName(address integrationAddress) external view returns (string memory); /// @return The address of the WETH token function getWethTokenAddress() external view returns (address); /// @return The address of the BIOS token function getBiosTokenAddress() external view returns (address); /// @param tokenId The ID of the token /// @return The address of the token ERC20 contract function getTokenAddress(uint256 tokenId) external view returns (address); /// @param tokenAddress The address of the token ERC20 contract /// @return The index of the token in the tokens array function getTokenId(address tokenAddress) external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The token BIOS reward weight function getTokenBiosRewardWeight(address tokenAddress) external view returns (uint256); /// @return rewardWeightSum reward weight of depositable tokens function getBiosRewardWeightSum() external view returns (uint256 rewardWeightSum); /// @param tokenAddress The address of the token ERC20 contract /// @return bool indicating whether depositing this token is currently enabled function getTokenAcceptingDeposits(address tokenAddress) external view returns (bool); /// @param tokenAddress The address of the token ERC20 contract /// @return bool indicating whether withdrawing this token is currently enabled function getTokenAcceptingWithdrawals(address tokenAddress) external view returns (bool); // @param tokenAddress The address of the token ERC20 contract // @return bool indicating whether the token has been added function getIsTokenAdded(address tokenAddress) external view returns (bool); // @param integrationAddress The address of the integration contract // @return bool indicating whether the integration has been added function getIsIntegrationAdded(address tokenAddress) external view returns (bool); /// @notice get the length of supported tokens /// @return The quantity of tokens added function getTokenAddressesLength() external view returns (uint256); /// @notice get the length of supported integrations /// @return The quantity of integrations added function getIntegrationAddressesLength() external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The value that gets divided by the reserve ratio denominator function getTokenReserveRatioNumerator(address tokenAddress) external view returns (uint256); /// @return The token reserve ratio denominator function getReserveRatioDenominator() external view returns (uint32); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IKernel { /// @param account The address of the account to check if they are a manager /// @return Bool indicating whether the account is a manger function isManager(address account) external view returns (bool); /// @param account The address of the account to check if they are an owner /// @return Bool indicating whether the account is an owner function isOwner(address account) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; enum Modules { Kernel, // 0 UserPositions, // 1 YieldManager, // 2 IntegrationMap, // 3 BiosRewards, // 4 EtherRewards, // 5 SushiSwapTrader, // 6 UniswapTrader, // 7 StrategyMap, // 8 StrategyManager // 9 } interface IModuleMap { function getModuleAddress(Modules key) external view returns (address); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapFactory { function getPair(address tokenA, address tokenB) external view returns (address pair); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapPair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function token0() external view returns (address); function token1() external view returns (address); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapRouter { 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 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 removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function swapETHForExactTokens( uint amountOut, address[] calldata path, address to, uint deadline ) external payable returns (uint[] memory amounts); function swapExactETHForTokens( uint amountOut, address[] calldata path, address to, uint deadline ) external payable returns (uint[] memory amounts); function WETH() external pure returns (address); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapTrader { /// @param slippageNumerator_ The number divided by the slippage denominator to get the slippage percentage function updateSlippageNumerator(uint24 slippageNumerator_) external; /// @notice Swaps all WETH held in this contract for BIOS and sends to the kernel /// @return Bool indicating whether the trade succeeded function biosBuyBack() external returns (bool); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address of the token out recipient /// @param amountIn The exact amount of the input to swap /// @param amountOutMin The minimum amount of tokenOut to receive from the swap /// @return bool Indicates whether the swap succeeded function swapExactInput( address tokenIn, address tokenOut, address recipient, uint256 amountIn, uint256 amountOutMin ) external returns (bool); }
return The slippage denominator
function getSlippageDenominator() public pure returns (uint24) { return SLIPPAGE_DENOMINATOR; }
9,947,468
./full_match/5/0x393c146c8824Ab2a0A96cf2Ab949ab7Ded9D6238/sources/project_/contracts/TCR.sol
entities wanting to be on the list can apply to it via this function. They must send an amount of ether equal to the challengerStake and specify an incumbent that they wish to displace (or an empty string if there is a position on the list that is unfilled) calls initiateVote if there are no empty slots remaining and the string passed is an incumbent on the list _challengerName name of the entity applying to the list _incumbentName name of the incumbent the applicant wants to displace
function applyToList(string _challengerName, string _incumbentName) external payable setupRequired() atStage(Stages.PreVote) smoothSailing() { require(msg.value == challengerStake); require(bytes(_challengerName).length <= 20); require(bytes(_incumbentName).length <= 20); challenger = _challengerName; address incumbentAddress = linkNameToMemberAdr[_incumbentName]; if (keccak256(_incumbentName) == keccak256("")) { require(replaceIncumbent(msg.sender,0)); emit EmptySlotFilled(_challengerName); } else if (incumbentAddress != 0) { initiateVote(msg.sender,incumbentAddress); } else{ revert(); } }
1,919,671
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "./interfaces/IPlushApps.sol"; /// @custom:security-contact security@plush.family contract PlushApps is Initializable, PausableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable, IPlushApps { mapping(address => Apps) public appsList; /** * @dev Roles definitions */ bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE"); /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __Pausable_init(); __AccessControl_init(); __UUPSUpgradeable_init(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(PAUSER_ROLE, msg.sender); _grantRole(OPERATOR_ROLE, msg.sender); _grantRole(UPGRADER_ROLE, msg.sender); } /// @notice Pause contract function pause() public onlyRole(PAUSER_ROLE) { _pause(); } /// @notice Unpause contract function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } /** * @notice Add new app to PlushApps * @param name App name in bytes32 * @param controllerAddress App controller address * @param fee App ecosystem fee in wei */ function addNewApp(bytes32 name, address controllerAddress, uint256 fee) external onlyRole(OPERATOR_ROLE) { require(!appsList[controllerAddress].exists, "Application already exists"); appsList[controllerAddress] = Apps(name, fee, true, true); emit AppAdded(name, controllerAddress, fee); } /** * @notice Check if the application exists * @param controllerAddress App controller address * @return boolean exists status */ function getAppExists(address controllerAddress) public view returns (bool) { if (appsList[controllerAddress].exists) { return true; } return false; } /** * @notice Delete app from PlushApps * @param controllerAddress App controller address */ function deleteApp(address controllerAddress) external onlyRole(OPERATOR_ROLE) { require(appsList[controllerAddress].exists, "Application doesn't exist"); delete appsList[controllerAddress]; emit AppDeleted(controllerAddress); } /** * @notice Get app fee * @param controllerAddress controller address * @return App fee */ function getFeeApp(address controllerAddress) public view returns (uint256) { require(appsList[controllerAddress].exists, "Application doesn't exist"); return appsList[controllerAddress].fee; } /** * @notice Change fee app * @param controllerAddress App controller address * @param fee App ecosystem fee in wei */ function setFeeApp(address controllerAddress, uint256 fee) external onlyRole(OPERATOR_ROLE) { require(appsList[controllerAddress].exists, "Application doesn't exist"); appsList[controllerAddress].fee = fee; emit AppFeeChanged(controllerAddress, fee); } /** * @notice Activating the application * @param controllerAddress App controller address */ function setAppEnable(address controllerAddress) external onlyRole(OPERATOR_ROLE) { require(appsList[controllerAddress].exists, "Application doesn't exist"); require(!appsList[controllerAddress].active, "Application already enable"); appsList[controllerAddress].active = true; emit AppEnabled(controllerAddress); } /** * @notice Disabling the application * @param controllerAddress App controller address */ function setAppDisable(address controllerAddress) external onlyRole(OPERATOR_ROLE) { require(appsList[controllerAddress].exists, "Application doesn't exist"); require(appsList[controllerAddress].active, "Application already disable"); appsList[controllerAddress].active = false; emit AppDisabled(controllerAddress); } /** * @notice Update application controller address * @param oldControllerAddress exist controller application address * @param newControllerAddress new controller application address */ function setNewController(address oldControllerAddress, address newControllerAddress) external onlyRole(OPERATOR_ROLE) { require(appsList[oldControllerAddress].exists, "Application doesn't exist"); require(!appsList[newControllerAddress].exists, "New controller address is already in use"); appsList[newControllerAddress] = appsList[oldControllerAddress]; delete appsList[oldControllerAddress]; emit AppControllerAddressUpdated(oldControllerAddress, newControllerAddress); } /** * @notice Get app status (enable/disable) * @param controllerAddress app controller address * @return app enable status in boolean */ function getAppStatus(address controllerAddress) public view returns (bool) { require(appsList[controllerAddress].exists, "Application doesn't exist"); return appsList[controllerAddress].active; } function _authorizeUpgrade(address newImplementation) internal onlyRole(UPGRADER_ROLE) override {} }
Disabling the application controllerAddress App controller address/
function setAppDisable(address controllerAddress) external onlyRole(OPERATOR_ROLE) { require(appsList[controllerAddress].exists, "Application doesn't exist"); require(appsList[controllerAddress].active, "Application already disable"); appsList[controllerAddress].active = false; emit AppDisabled(controllerAddress); }
1,079,545
./full_match/1/0x084F0B509cb0d4dd473D84520944950E1d6FafaF/sources/contracts/BatchTransfer.sol
Requires 'setApprovalForAll' before transfer
function transferERC721( IERC721 collection, address recipient, uint256[] calldata tokenIds ) external { for (uint256 i; i < tokenIds.length; i++) { collection.safeTransferFrom(msg.sender, recipient, tokenIds[i]); } }
2,934,294
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/AddressUtils.sol"; import "./CvcEscrowInterface.sol"; import "../pricing/CvcPricingInterface.sol"; import "../upgradeability/Initializable.sol"; import "../upgradeability/EternalStorage.sol"; import "../upgradeability/Pausable.sol"; /** * @title CvcEscrow * @dev This contract provides escrow service functionality for the Identity.com marketplace. * It controls an escrow placement's lifecycle which involves transferring a pre-approved amount funds * from the Identity Requester account to its own account and keeping them until the marketplace deal is complete. * * Glossary: * Identity Requester (IDR) - Business entities requesting verifiable Credentials from a user in order to authenticate them. * Identity Validator (IDV) - Businesses or organizations that validate a user's identity and provide verifiable credentials. * Scope Request - A request for identity information about a user from an IDR to an IDV. * Credential Item - A single item in a set of verifiable credentials that an IDR can specify within a scope request. * * The marketplace flow has 2 possible outcomes: * 1. release - when user's personally identifiable information (PII) has been delivered to Identity Requester. * In this case the release functionality is triggered and the contract transfers escrowed funds * to the Identity Validator account, excluding the marketplace fee (if applied). * * 2. cancellation - when user's personally identifiable information (PII) has NOT been delivered to Identity Requester. * In this case the refund procedure can be executed and all the escrowed funds will be returned * back to Identity Requester account. * * The escrow contract depends on other marketplace contracts, such as: * CvcToken - to perform CVC transfers. * CvcPricing - to check the actual marketplace prices and ensure that placed amount of tokens * covers the Credential Items price and matches the expectation of all involved parties. */ contract CvcEscrow is EternalStorage, Initializable, Pausable, CvcEscrowInterface { using SafeMath for uint256; /** Data structures and storage layout: struct EscrowPlacement { uint256 state; uint256 amount; uint256 credentialItemIdsCount; bytes32[] credentialItemIds; uint256 blockNumber; } uint256 timeoutThreshold; uint256 platformFeeRate; address cvcToken; address cvcPricing; address platform; mapping(bytes32 => EscrowPlacement) placements; **/ /// The divisor for calculating platform fee rate. /// Solidity does not support floats, /// so we provide rather big unsigned integer and then divide it by this constant uint256 constant public RATE_PRECISION = 1e8; /** * @dev Constructor * @param _token CVC Token contract address * @param _platform Platform address to send retained fee to * @param _pricing Pricing contract address to lookup for escrow amount before placing */ constructor(address _token, address _platform, address _pricing) public { initialize(_token, _platform, _pricing, msg.sender); } /** * @dev Handles escrow placement for a single scope request. * @param _idv Address of Identity Validator * @param _scopeRequestId Scope request identifier * @param _amount CVC token amount in creds (CVC x 10e-8) * @param _credentialItemIds Array of credential item IDs * @return bytes32 New Placement ID */ function place( address _idv, bytes32 _scopeRequestId, uint256 _amount, bytes32[] _credentialItemIds ) external onlyInitialized whenNotPaused returns (bytes32) { // Prepare a batch with single scope request ID. bytes32[] memory scopeRequestIds = new bytes32[](1); scopeRequestIds[0] = _scopeRequestId; return makePlacement(_idv, scopeRequestIds, _amount, _credentialItemIds); } /** * @dev Handles escrow placement for multiple scope requests grouped by credential item IDs. * @param _idv Address of Identity Validator * @param _scopeRequestIds Array of scope request IDs * @param _amount CVC token amount in creds (CVC x 10e-8) * @param _credentialItemIds Array of credential item IDs * @return bytes32 New Placement ID */ function placeBatch(address _idv, bytes32[] _scopeRequestIds, uint256 _amount, bytes32[] _credentialItemIds) external onlyInitialized whenNotPaused returns (bytes32) { return makePlacement(_idv, _scopeRequestIds, _amount, _credentialItemIds); } /** * @dev Releases escrow placement and distributes funds. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _scopeRequestId Scope request identifier */ function release(address _idr, address _idv, bytes32 _scopeRequestId) external onlyOwner onlyInitialized whenNotPaused { // Prepare a batch with single scope request ID. bytes32[] memory scopeRequestIdsToRelease = new bytes32[](1); scopeRequestIdsToRelease[0] = _scopeRequestId; // itemsToKeep is empty to indicate full release. makePartialRelease(_idr, _idv, scopeRequestIdsToRelease, new bytes32[](0)); } /** * @dev Releases escrow placement for multiple scope requests and distributes funds. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _scopeRequestIdsToRelease Array of scope request IDs which will be released * @param _scopeRequestIdsToKeep Array of scope request IDs which will be kept in escrow * @return bytes32 Placement ID of remaining part of the batch. Empty when the placement was fully released */ function releaseBatch( address _idr, address _idv, bytes32[] _scopeRequestIdsToRelease, bytes32[] _scopeRequestIdsToKeep ) external onlyOwner onlyInitialized whenNotPaused returns (bytes32) { return makePartialRelease(_idr, _idv, _scopeRequestIdsToRelease, _scopeRequestIdsToKeep); } /** * @dev Refunds escrowed tokens for a single scope request back to Identity Requester. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _scopeRequestId Scope request ID */ function refund(address _idr, address _idv, bytes32 _scopeRequestId) external onlyInitialized whenNotPaused { // Prepare a batch with single scope request ID. bytes32[] memory scopeRequestIds = new bytes32[](1); scopeRequestIds[0] = _scopeRequestId; makeFullRefund(_idr, _idv, scopeRequestIds); } /** * @dev Refunds escrowed tokens for for multiple scope requests back to Identity Requester. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _scopeRequestIds Array of scope request IDs */ function refundBatch(address _idr, address _idv, bytes32[] _scopeRequestIds) external onlyInitialized whenNotPaused { makeFullRefund(_idr, _idv, _scopeRequestIds); } /** * @dev Returns placement details. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _scopeRequestId Scope request ID * @return uint256 CVC token amount in creds (CVC x 10e-8) * @return PlacementState One of the CvcEscrowInterface.PlacementState values * @return bytes32[] Array of credential item IDs * @return uint256 Block confirmations since escrow was placed * @return bool True if placement can be refunded otherwise false */ function verify(address _idr, address _idv, bytes32 _scopeRequestId) external view returns ( uint256 placementAmount, PlacementState placementState, bytes32[] credentialItemIds, uint256 confirmations, bool refundable ) { // Prepare a batch with single scope request ID. bytes32[] memory scopeRequestIds = new bytes32[](1); scopeRequestIds[0] = _scopeRequestId; return getPlacement(calculatePlacementId(_idr, _idv, scopeRequestIds)); } /** * @dev Returns placement details. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _scopeRequestIds Array of scope request IDs * @return uint256 CVC token amount in creds (CVC x 10e-8) * @return PlacementState One of the CvcEscrowInterface.PlacementState values * @return bytes32[] Array of credential item IDs * @return uint256 Block confirmations since escrow was placed * @return bool True if placement can be refunded otherwise false */ function verifyBatch(address _idr, address _idv, bytes32[] _scopeRequestIds) external view returns ( uint256 placementAmount, PlacementState placementState, bytes32[] credentialItemIds, uint256 confirmations, bool refundable ) { return getPlacement(calculatePlacementId(_idr, _idv, _scopeRequestIds)); } /** * @dev Returns placement details. * @param _placementId Escrow Placement identifier. * @return uint256 CVC token amount in creds (CVC x 10e-8) * @return PlacementState One of the CvcEscrowInterface.PlacementState values. * @return bytes32[] Array of credential item IDs. * @return uint256 Block confirmations since escrow was placed. * @return bool True if placement can be refunded otherwise false */ function verifyPlacement(bytes32 _placementId) external view returns ( uint256 placementAmount, PlacementState placementState, bytes32[] credentialItemIds, uint256 confirmations, bool refundable ) { return getPlacement(_placementId); } /** * @dev Contract initialization method. * @param _token CVC Token contract address * @param _platform Platform address to send retained fee to * @param _pricing Pricing contract address to lookup for escrow amount before placing * @param _owner Owner address, used for release */ function initialize(address _token, address _platform, address _pricing, address _owner) public initializes { // Ensure contracts. require(AddressUtils.isContract(_token), "Initialization error: no contract code at token contract address"); require(AddressUtils.isContract(_pricing), "Initialization error: no contract code at pricing contract address"); /// Timeout value for escrowed funds before refund is available. /// Currently represents number of blocks for approx 24 hours. // timeoutThreshold = 5800; uintStorage[keccak256("timeout.threshold")] = 5800; /// The percentage of escrowed funds retained as a platform fee. /// The default rate is 10% (0.1 * 10^8). // platformFeeRate = 1e7; uintStorage[keccak256("platform.fee.rate")] = 1e7; // Initialize current implementation owner address. setOwner(_owner); // CVC Token contract address to transfer CVC tokens. // cvcToken = _token; addressStorage[keccak256("cvc.token")] = _token; // Pricing contract address to lookup attestation prices. // cvcPricing = _pricing; addressStorage[keccak256("cvc.pricing")] = _pricing; // Platform address is used to transfer platform usage fee. // platform = _platform; addressStorage[keccak256("platform")] = _platform; } /** * @dev Calculates escrow placement identifier. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _scopeRequestIds An array of scope request identifiers * @return bytes32 Placement ID */ function calculatePlacementId(address _idr, address _idv, bytes32[] _scopeRequestIds) public pure returns (bytes32) { require(_idr != address(0), "Cannot calculate placement ID with IDR being a zero address"); require(_idv != address(0), "Cannot calculate placement ID with IDV being a zero address"); return keccak256(abi.encodePacked(_idr, _idv, calculateBatchReference(_scopeRequestIds))); } /** * @dev Returns platform fee amount based on given placement amount and current platform fee rate. * @param _amount Escrow placement total amount. * @return uint256 */ function calculatePlatformFee(uint256 _amount) public view returns (uint256) { return (_amount.mul(platformFeeRate()).add(RATE_PRECISION.div(2))).div(RATE_PRECISION); } /** * @dev Sets timeout threshold. Ensures it's more than 0. * @param _threshold New timeout threshold value */ function setTimeoutThreshold(uint256 _threshold) public onlyOwner onlyInitialized { require(_threshold > 0, "Timeout threshold cannot be zero"); // timeoutThreshold = _threshold; uintStorage[keccak256("timeout.threshold")] = _threshold; } /** * @dev Returns actual escrow timeout threshold value. * @return uint256 */ function timeoutThreshold() public view returns (uint256) { // return timeoutThreshold; return uintStorage[keccak256("timeout.threshold")]; } /** * @dev Allows to change platform fee rate. * @param _feeRate A platform fee rate in percentage, e.g. 1e7 (10%). */ function setFeeRate(uint256 _feeRate) public onlyOwner onlyInitialized { require(_feeRate <= RATE_PRECISION, "Platform fee rate cannot be more than 100%"); // platformFeeRate = _feeRate; uintStorage[keccak256("platform.fee.rate")] = _feeRate; } /** * @dev Returns actual platform fee rate value. * @return uint256 */ function platformFeeRate() public view returns (uint256) { // return platformFeeRate; return uintStorage[keccak256("platform.fee.rate")]; } /** * @dev Returns CvcToken contact instance. * @return ERC20 */ function token() public view returns (ERC20) { // return ERC20(cvcToken); return ERC20(addressStorage[keccak256("cvc.token")]); } /** * @dev Returns CvcPricing contact instance. * @return CvcPricingInterface */ function pricing() public view returns (CvcPricingInterface) { // return CvcPricingInterface(cvcPricing); return CvcPricingInterface(addressStorage[keccak256("cvc.pricing")]); } /** * @dev Returns platform address. * @return address */ function platformAddress() public view returns (address) { // return platform; return addressStorage[keccak256("platform")]; } /** * @dev Stores placement data against the placement ID. * @param _placementId Unique placement identifier * @param _amount CVC token amount in creds (CVC x 10e-8) * @param _credentialItemIds Array of credential item IDs * @param _blockNumber Block number at which the placement is received */ function saveNewPlacement(bytes32 _placementId, uint256 _amount, bytes32[] _credentialItemIds, uint256 _blockNumber) internal { // Verify current state for given placementId to ensure operation is allowed. PlacementState placementState = getPlacementState(_placementId); // Placement is allowed when: // 1. it is a completely new escrow placement with fresh ID (Empty state) // 2. the placement with given ID was refunded (Canceled state) require( placementState == PlacementState.Empty || placementState == PlacementState.Canceled, "Invalid placement state: must be new or canceled" ); // Write placement data into the contract storage. setPlacementState(_placementId, PlacementState.Placed); setPlacementCredentialItemIds(_placementId, _credentialItemIds); setPlacementAmount(_placementId, _amount); setPlacementBlockNumber(_placementId, _blockNumber); } /** * @dev Returns placement total price based on number of credential items and their current market prices. * @param _idv Identity Validator address * @param _credentialItemIds Array of credential item IDs * @param _batchSize Number of scope request IDs in placement * @return uint256 */ function getPlacementPrice(address _idv, bytes32[] _credentialItemIds, uint256 _batchSize) internal view returns (uint256) { uint256 price = 0; uint256 credentialItemPrice; CvcPricingInterface cvcPricing = pricing(); for (uint256 i = 0; i < _credentialItemIds.length; i++) { (, credentialItemPrice, , , , ,) = cvcPricing.getPriceByCredentialItemId(_idv, _credentialItemIds[i]); price = price.add(credentialItemPrice); } return price.mul(_batchSize); } /** * @dev Check if the escrow placement can be refunded back to Identity Requester. * @param _placementState The escrow placement state. * @param _placementBlockNumber The escrow placement block number. * @return bool Whether escrow can be refunded. */ function isRefundable(PlacementState _placementState, uint256 _placementBlockNumber) internal view returns (bool) { // Refund is allowed if the escrowed placement is still in "Placed" state & timeout is reached. // Timeout reached when number of blocks after the escrow was placed is greater than timeout threshold. return _placementState == PlacementState.Placed && block.number.sub(_placementBlockNumber) > timeoutThreshold(); } /** * @dev Transfers funds from IRD account and stores the placement data. * @param _idv Address of Identity Validator * @param _scopeRequestIds Array of scope request IDs * @param _amount CVC token amount in creds (CVC x 10e-8) * @param _credentialItemIds Array of credential item IDs * @return bytes32 New Placement ID */ function makePlacement(address _idv, bytes32[] _scopeRequestIds, uint256 _amount, bytes32[] _credentialItemIds) internal returns (bytes32) { // Calculate placement ID to validate arguments. bytes32 placementId = calculatePlacementId(msg.sender, _idv, _scopeRequestIds); // Ensure escrow amount is matching the total price of all credential items. require( _amount == getPlacementPrice(_idv, _credentialItemIds, _scopeRequestIds.length), "Placement amount does not match credential item total price" ); // Store new placement data. saveNewPlacement(placementId, _amount, _credentialItemIds, block.number); // Transferring funds from IDR to escrow contract address. require(token().transferFrom(msg.sender, this, _amount), "Token transfer from IDR account failed"); // Emitting escrow placement event for each individual scope request ID. uint256 amountPerItem = _amount.div(_scopeRequestIds.length); for (uint256 i = 0; i < _scopeRequestIds.length; i++) { emit EscrowPlaced(msg.sender, _idv, _scopeRequestIds[i], amountPerItem, _credentialItemIds, placementId); } return placementId; } /** * @dev Calculates scope request batch reference. * @param _scopeRequestIds An array of scope request identifiers * @return bytes32 Batch reference */ function calculateBatchReference(bytes32[] _scopeRequestIds) internal pure returns (bytes32 batchReference) { // In order to increase batch reference entropy and prevent potential collision // caused by small difference between two or more scope request IDs from the same batch // we hash the scope request ID before adding to the batch reference. for (uint256 i = 0; i < _scopeRequestIds.length; i++) { // Ensure scopeRequestId is not empty & add its hash to batch reference. require(_scopeRequestIds[i] != 0x0, "Cannot calculate batch reference with empty scope request ID"); batchReference = batchReference ^ keccak256(abi.encodePacked(_scopeRequestIds[i])); } } /** * @dev Releases placed batch items. * In case of partial release keeps the remaining part in escrow under new placement ID. * If the entire batch is release, empty bytes returned instead. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _itemsToRelease Array of scope request IDs to be released * @param _itemsToKeep Array of scope request IDs to keep in escrow * @return bytes32 Placement ID of remaining part of the batch. Empty when the placement was fully released */ function makePartialRelease(address _idr, address _idv, bytes32[] _itemsToRelease, bytes32[] _itemsToKeep) internal returns (bytes32) { // Restore initial placement ID. bytes32 batchReference = calculateBatchReference(_itemsToRelease); if (_itemsToKeep.length > 0) { batchReference = batchReference ^ calculateBatchReference(_itemsToKeep); } bytes32 placementId = keccak256(abi.encodePacked(_idr, _idv, batchReference)); // Allow release only when the escrow exists and it is not refundable yet. // If placement found by ID, we can be sure two arrays of scope request IDs together formed the initial batch. PlacementState placementState = getPlacementState(placementId); require(placementState == PlacementState.Placed, "Invalid placement state: must be placed"); require(!isRefundable(placementState, getPlacementBlockNumber(placementId)), "Timed out: release is not possible anymore"); // Change placement state to released. setPlacementState(placementId, PlacementState.Released); // Calculate released token amount. uint256 totalBatchSize = _itemsToRelease.length.add(_itemsToKeep.length); uint256 placementAmount = getPlacementAmount(placementId); uint256 amountToRelease = placementAmount.mul(_itemsToRelease.length).div(totalBatchSize); // Release batch items and distribute escrowed funds. releaseEscrowedFunds(placementId, _idr, _idv, _itemsToRelease, amountToRelease); // Return empty bytes when the entire batch released. if (_itemsToKeep.length == 0) return 0x0; // Keep the remaining part of the batch in escrow. uint256 amountToKeep = placementAmount.mul(_itemsToKeep.length).div(totalBatchSize); return keepPlacement(placementId, _idr, _idv, _itemsToKeep, amountToKeep); } /** * @dev Refunds escrowed tokens for for multiple scope requests back to Identity Requester. * @param _idr Address of Identity Requester * @param _idv Address of Identity Validator * @param _itemsToRefund Array of scope request IDs to be refunded */ function makeFullRefund(address _idr, address _idv, bytes32[] _itemsToRefund) internal { // Calculate placement ID to validate arguments. bytes32 placementId = calculatePlacementId(_idr, _idv, _itemsToRefund); // Check if refund is allowed. require( isRefundable(getPlacementState(placementId), getPlacementBlockNumber(placementId)), "Placement is not refundable yet" ); // Mark the escrow placement Canceled. setPlacementState(placementId, PlacementState.Canceled); // Transfer funds from the escrow contract balance to IDR account. uint256 placementAmount = getPlacementAmount(placementId); require(token().transfer(_idr, placementAmount), "Token transfer to IDR account failed"); // Emitting escrow cancellation event for each individual scope request ID. uint256 amountPerItem = placementAmount.div(_itemsToRefund.length); bytes32[] memory credentialItemIds = getPlacementCredentialItemIds(placementId); for (uint256 i = 0; i < _itemsToRefund.length; i++) { emit EscrowCanceled(_idr, _idv, _itemsToRefund[i], amountPerItem, credentialItemIds, placementId); } } /** * @dev Stores items as a new placement. * @param _placementId Current placement identifier. * @param _idr Address of Identity Requester. * @param _idv Address of Identity Validator. * @param _itemsToKeep Array of scope request IDs to keep in escrow. * @param _amount New Placement amount. * @return bytes32 New Placement ID. */ function keepPlacement(bytes32 _placementId, address _idr, address _idv, bytes32[] _itemsToKeep, uint256 _amount) internal returns (bytes32) { // Calculate new placement ID. bytes32 newPlacementId = calculatePlacementId(_idr, _idv, _itemsToKeep); // Store data against new placement ID. Copy unchanged data from old placement. bytes32[] memory credentialItemIds = getPlacementCredentialItemIds(_placementId); saveNewPlacement(newPlacementId, _amount, credentialItemIds, getPlacementBlockNumber(_placementId)); uint256 amountPerItem = _amount.div(_itemsToKeep.length); for (uint256 i = 0; i < _itemsToKeep.length; i++) { emit EscrowMoved(_idr, _idv, _itemsToKeep[i], amountPerItem, credentialItemIds, _placementId, newPlacementId); } return newPlacementId; } /** * @dev Transfers funds to IDV withholding platform fee (if applied). * @param _placementId Released placement identifier. * @param _idr Address of Identity Requester. * @param _idv Address of Identity Validator. * @param _releasedItems Array of released scope request IDs. * @param _amount Amount to release. */ function releaseEscrowedFunds(bytes32 _placementId, address _idr, address _idv, bytes32[] _releasedItems, uint256 _amount) internal { // Calculate token distribution. uint256 platformFee = calculatePlatformFee(_amount); uint256 idvFee = platformFee > 0 ? _amount.sub(platformFee) : _amount; // Transfer tokens from escrow to IDV. ERC20 cvcToken = token(); require(cvcToken.transfer(_idv, idvFee), "Token transfer to IDV account failed"); // Transfer tokens from escrow to platform operator address. if (platformFee > 0) { require(cvcToken.transfer(platformAddress(), platformFee), "Token transfer to platform account failed"); } logBatchRelease( _placementId, _idr, _idv, _releasedItems, platformFee.div(_releasedItems.length), idvFee.div(_releasedItems.length) ); } /** * @dev Emits EscrowReleased event for each released item. * @param _placementId Released placement identifier. * @param _idr Address of Identity Requester. * @param _idv Address of Identity Validator. * @param _releasedItems Array of released scope request IDs. * @param _itemPlatformFee Platform fee charged per one item. * @param _itemIdvFee Identity Validator fee charged per one item. */ function logBatchRelease( bytes32 _placementId, address _idr, address _idv, bytes32[] _releasedItems, uint256 _itemPlatformFee, uint256 _itemIdvFee ) internal { bytes32[] memory credentialItemIds = getPlacementCredentialItemIds(_placementId); for (uint256 i = 0; i < _releasedItems.length; i++) { emit EscrowReleased( _idr, _idv, _releasedItems[i], _itemPlatformFee, _itemIdvFee, credentialItemIds, _placementId ); } } /** * @dev Returns placement details. * @param _placementId Escrow Placement identifier. * @return uint256 CVC token amount in creds (CVC x 10e-8) * @return PlacementState One of the CvcEscrowInterface.PlacementState values. * @return bytes32[] Array of credential item IDs. * @return uint256 Block confirmations since escrow was placed. * @return bool True if placement can be refunded otherwise false */ function getPlacement(bytes32 _placementId) internal view returns ( uint256 placementAmount, PlacementState placementState, bytes32[] credentialItemIds, uint256 confirmations, bool refundable ) { placementState = getPlacementState(_placementId); // Placement amount value is returned for Placed placements, otherwise 0; placementAmount = placementState == PlacementState.Placed ? getPlacementAmount(_placementId) : 0; credentialItemIds = getPlacementCredentialItemIds(_placementId); // 0 when empty, number of blocks in other states uint256 placementBlockNumber = getPlacementBlockNumber(_placementId); confirmations = placementState == PlacementState.Empty ? 0 : block.number.sub(placementBlockNumber); refundable = isRefundable(placementState, placementBlockNumber); } /** * @dev Returns placement state. * @param _placementId The placement ID. * @return PlacementState */ function getPlacementState(bytes32 _placementId) internal view returns (PlacementState) { // return PlacementState(placements[_placementId].state); return PlacementState(uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".state"))]); } /** * @dev Saves placement state. * @param _placementId The placement ID. * @param state Placement state. */ function setPlacementState(bytes32 _placementId, PlacementState state) internal { // placements[_placementId].state = uint256(state); uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".state"))] = uint256(state); } /** * @dev Returns placement amount. * @param _placementId The placement ID. * @return uint256 */ function getPlacementAmount(bytes32 _placementId) internal view returns (uint256) { // return placements[_placementId].amount; return uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".amount"))]; } /** * @dev Saves placement amount. * @param _placementId The placement ID. * @param _amount Placement amount. */ function setPlacementAmount(bytes32 _placementId, uint256 _amount) internal { // placements[_placementId].amount = _amount; uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".amount"))] = _amount; } /** * @dev Returns placement credential item IDs. * @param _placementId The placement ID. * @return bytes32[] Array of credential item IDs. */ function getPlacementCredentialItemIds(bytes32 _placementId) internal view returns (bytes32[]) { // uint256 count = placements[_placementId].credentialItemIdsCount; uint256 count = uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".credentialItemIds"))]; bytes32[] memory credentialItemIds = new bytes32[](count); for (uint256 i = 0; i < count; i++) { // credentialItemIds[i] = placements[_placementId].credentialItemIds[i]; credentialItemIds[i] = bytes32Storage[keccak256(abi.encodePacked("placements.", _placementId, ".credentialItemIds.", i))]; } return credentialItemIds; } /** * @dev Saves placement credential item IDs. * @param _placementId The placement ID. * @param _credentialItemIds Array of credential item IDs. */ function setPlacementCredentialItemIds(bytes32 _placementId, bytes32[] _credentialItemIds) internal { // placements[_placementId].credentialItemIdsCount = _credentialItemIds.length; uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".credentialItemIds"))] = _credentialItemIds.length; for (uint256 i = 0; i < _credentialItemIds.length; i++) { // placements[_placementId].credentialItemIds[i] = _credentialItemIds[i]; bytes32Storage[keccak256(abi.encodePacked("placements.", _placementId, ".credentialItemIds.", i))] = _credentialItemIds[i]; } } /** * @dev Returns placement block number. * @param _placementId The placement ID. * @return uint256 */ function getPlacementBlockNumber(bytes32 _placementId) internal view returns (uint256) { // return placements[_placementId].blockNumber; return uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".blockNumber"))]; } /** * @dev Saves placement block number. * @param _placementId The placement ID. * @param _blockNumber Placement block number. */ function setPlacementBlockNumber(bytes32 _placementId, uint256 _blockNumber) internal { // placements[_placementId].blockNumber = _blockNumber; uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".blockNumber"))] = _blockNumber; } }
Stores placement data against the placement ID. _placementId Unique placement identifier _amount CVC token amount in creds (CVC x 10e-8) _credentialItemIds Array of credential item IDs _blockNumber Block number at which the placement is received/ Verify current state for given placementId to ensure operation is allowed. Placement is allowed when: 1. it is a completely new escrow placement with fresh ID (Empty state) 2. the placement with given ID was refunded (Canceled state) Write placement data into the contract storage.
function saveNewPlacement(bytes32 _placementId, uint256 _amount, bytes32[] _credentialItemIds, uint256 _blockNumber) internal { PlacementState placementState = getPlacementState(_placementId); require( placementState == PlacementState.Empty || placementState == PlacementState.Canceled, "Invalid placement state: must be new or canceled" ); setPlacementState(_placementId, PlacementState.Placed); setPlacementCredentialItemIds(_placementId, _credentialItemIds); setPlacementAmount(_placementId, _amount); setPlacementBlockNumber(_placementId, _blockNumber); }
6,411,412
pragma solidity ^0.4.23; /* * NamiMultiSigWallet smart contract------------------------------- */ /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. contract NamiMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { // Transaction tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } } /* * Contract that is working with ERC223 tokens */ /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public returns (bool success); function tokenFallbackBuyer(address _from, uint _value, address _buyer) public returns (bool success); function tokenFallbackExchange(address _from, uint _value, uint _price) public returns (bool success); } contract PresaleToken { mapping (address => uint256) public balanceOf; function burnTokens(address _owner) public; } // ERC20 token interface is implemented only partially. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract NamiCrowdSale { using SafeMath for uint256; /// NAC Broker Presale Token /// @dev Constructor constructor(address _escrow, address _namiMultiSigWallet, address _namiPresale) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; namiPresale = _namiPresale; } /*/ * Constants /*/ string public name = "Nami ICO"; string public symbol = "NAC"; uint public decimals = 18; bool public TRANSFERABLE = false; // default not transferable uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei); uint public binary = 0; /*/ * Token state /*/ enum Phase { Created, Running, Paused, Migrating, Migrated } Phase public currentPhase = Phase.Created; uint public totalSupply = 0; // amount of tokens already sold // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; // nami presale contract address public namiPresale; // Crowdsale manager has exclusive priveleges to burn presale tokens. address public crowdsaleManager; // binary option address address public binaryAddress; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; modifier onlyCrowdsaleManager() { require(msg.sender == crowdsaleManager); _; } modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyTranferable() { require(TRANSFERABLE); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } /*/ * Events /*/ event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); event LogPhaseSwitch(Phase newPhase); // Log migrate token event LogMigrate(address _from, address _to, uint256 amount); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /*/ * Public functions /*/ /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } // Transfer the balance from owner&#39;s account to another account // only escrow can send token (to send token private sale) function transferForTeam(address _to, uint256 _value) public onlyEscrow { _transfer(msg.sender, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyTranferable { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyTranferable returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyTranferable returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } // allows transfer token function changeTransferable () public onlyEscrow { TRANSFERABLE = !TRANSFERABLE; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // change binary value function changeBinary(uint _binary) public onlyEscrow { binary = _binary; } // change binary address function changeBinaryAddress(address _binaryAddress) public onlyEscrow { require(_binaryAddress != 0x0); binaryAddress = _binaryAddress; } /* * price in ICO: * first week: 1 ETH = 2400 NAC * second week: 1 ETH = 23000 NAC * 3rd week: 1 ETH = 2200 NAC * 4th week: 1 ETH = 2100 NAC * 5th week: 1 ETH = 2000 NAC * 6th week: 1 ETH = 1900 NAC * 7th week: 1 ETH = 1800 NAC * 8th week: 1 ETH = 1700 nac * time: * 1517443200: Thursday, February 1, 2018 12:00:00 AM * 1518048000: Thursday, February 8, 2018 12:00:00 AM * 1518652800: Thursday, February 15, 2018 12:00:00 AM * 1519257600: Thursday, February 22, 2018 12:00:00 AM * 1519862400: Thursday, March 1, 2018 12:00:00 AM * 1520467200: Thursday, March 8, 2018 12:00:00 AM * 1521072000: Thursday, March 15, 2018 12:00:00 AM * 1521676800: Thursday, March 22, 2018 12:00:00 AM * 1522281600: Thursday, March 29, 2018 12:00:00 AM */ function getPrice() public view returns (uint price) { if (now < 1517443200) { // presale return 3450; } else if (1517443200 < now && now <= 1518048000) { // 1st week return 2400; } else if (1518048000 < now && now <= 1518652800) { // 2nd week return 2300; } else if (1518652800 < now && now <= 1519257600) { // 3rd week return 2200; } else if (1519257600 < now && now <= 1519862400) { // 4th week return 2100; } else if (1519862400 < now && now <= 1520467200) { // 5th week return 2000; } else if (1520467200 < now && now <= 1521072000) { // 6th week return 1900; } else if (1521072000 < now && now <= 1521676800) { // 7th week return 1800; } else if (1521676800 < now && now <= 1522281600) { // 8th week return 1700; } else { return binary; } } function() payable public { buy(msg.sender); } function buy(address _buyer) payable public { // Available only if presale is running. require(currentPhase == Phase.Running); // require ICO time or binary option require(now <= 1522281600 || msg.sender == binaryAddress); require(msg.value != 0); uint newTokens = msg.value * getPrice(); require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT); // add new token to buyer balanceOf[_buyer] = balanceOf[_buyer].add(newTokens); // add new token to totalSupply totalSupply = totalSupply.add(newTokens); emit LogBuy(_buyer,newTokens); emit Transfer(this,_buyer,newTokens); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function burnTokens(address _owner) public onlyCrowdsaleManager { // Available only during migration phase require(currentPhase == Phase.Migrating); uint tokens = balanceOf[_owner]; require(tokens != 0); balanceOf[_owner] = 0; totalSupply -= tokens; emit LogBurn(_owner, tokens); emit Transfer(_owner, crowdsaleManager, tokens); // Automatically switch phase when migration is done. if (totalSupply == 0) { currentPhase = Phase.Migrated; emit LogPhaseSwitch(Phase.Migrated); } } /*/ * Administrative functions /*/ function setPresalePhase(Phase _nextPhase) public onlyEscrow { bool canSwitchPhase = (currentPhase == Phase.Created && _nextPhase == Phase.Running) || (currentPhase == Phase.Running && _nextPhase == Phase.Paused) // switch to migration phase only if crowdsale manager is set || ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running) // switch to migrated only if everyting is migrated || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated && totalSupply == 0); require(canSwitchPhase); currentPhase = _nextPhase; emit LogPhaseSwitch(_nextPhase); } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (address(this).balance > 0) { namiMultiSigWallet.transfer(_amount); } } function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } function setCrowdsaleManager(address _mgr) public onlyEscrow { // You can&#39;t change crowdsale contract when migration is in progress. require(currentPhase != Phase.Migrating); crowdsaleManager = _mgr; } // internal migrate migration tokens function _migrateToken(address _from, address _to) internal { PresaleToken presale = PresaleToken(namiPresale); uint256 newToken = presale.balanceOf(_from); require(newToken > 0); // burn old token presale.burnTokens(_from); // add new token to _to balanceOf[_to] = balanceOf[_to].add(newToken); // add new token to totalSupply totalSupply = totalSupply.add(newToken); emit LogMigrate(_from, _to, newToken); emit Transfer(this,_to,newToken); } // migate token function for Nami Team function migrateToken(address _from, address _to) public onlyEscrow { _migrateToken(_from, _to); } // migrate token for investor function migrateForInvestor() public { _migrateToken(msg.sender, msg.sender); } // Nami internal exchange // event for Nami exchange event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller); event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price); /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackExchange` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackExchange` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _price price to sell token. */ function transferToExchange(address _to, uint _value, uint _price) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackExchange(msg.sender, _value, _price); emit TransferToExchange(msg.sender, _to, _value, _price); } } /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackBuyer` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackBuyer` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _buyer address of seller. */ function transferToBuyer(address _to, uint _value, address _buyer) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackBuyer(msg.sender, _value, _buyer); emit TransferToBuyer(msg.sender, _to, _value, _buyer); } } //------------------------------------------------------------------------------------------------------- } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract NamiTrade{ using SafeMath for uint256; uint public minNac = 0; // min NAC deposit uint public minWithdraw = 10 * 10**18; uint public maxWithdraw = 1000000 * 10**18; // max NAC withdraw one time constructor(address _escrow, address _namiMultiSigWallet, address _namiAddress) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; NamiAddr = _namiAddress; } // balance of pool uint public NetfBalance; /** * NetfRevenueBalance: NetfRevenue[_roundIndex].currentNAC * NlfBalance: NLFunds[currentRound].currentNAC * NlfRevenueBalance: listSubRoundNLF[currentRound][_subRoundIndex].totalNacInSubRound */ // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; /// address of Nami token address public NamiAddr; modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyNami { require(msg.sender == NamiAddr); _; } modifier onlyNamiMultisig { require(msg.sender == namiMultiSigWallet); _; } modifier onlyController { require(isController[msg.sender] == true); _; } /* * * list setting function */ mapping(address => bool) public isController; // set controller address /** * make new controller * require input address is not a controller * execute any time in sc state */ function setController(address _controller) public onlyEscrow { require(!isController[_controller]); isController[_controller] = true; } /** * remove controller * require input address is a controller * execute any time in sc state */ function removeController(address _controller) public onlyEscrow { require(isController[_controller]); isController[_controller] = false; } // change minimum nac to deposit function changeMinNac(uint _minNAC) public onlyEscrow { require(_minNAC != 0); minNac = _minNAC; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // min and max for withdraw nac function changeMinWithdraw(uint _minWithdraw) public onlyEscrow { require(_minWithdraw != 0); minWithdraw = _minWithdraw; } function changeMaxWithdraw(uint _maxNac) public onlyEscrow { require(_maxNac != 0); maxWithdraw = _maxNac; } /// @dev withdraw ether to nami multisignature wallet, only escrow can call /// @param _amount value ether in wei to withdraw function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (address(this).balance > 0) { namiMultiSigWallet.transfer(_amount); } } /// @dev withdraw NAC to nami multisignature wallet, only escrow can call /// @param _amount value NAC to withdraw function withdrawNac(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); if (namiToken.balanceOf(address(this)) > 0) { namiToken.transfer(namiMultiSigWallet, _amount); } } /* * * * List event */ event Deposit(address indexed user, uint amount, uint timeDeposit); event Withdraw(address indexed user, uint amount, uint timeWithdraw); event PlaceBuyFciOrder(address indexed investor, uint amount, uint timePlaceOrder); event PlaceSellFciOrder(address indexed investor, uint amount, uint timePlaceOrder); event InvestToNLF(address indexed investor, uint amount, uint timeInvest); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////fci token function/////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// string public name = "Nami Trade"; string public symbol = "FCI-Test"; uint8 public decimals = 18; uint256 public totalSupply; // paus phrase to compute ratio fci bool public isPause; // time expires of price fci uint256 public timeExpires; // price fci : if 1 fci = 2 nac => priceFci = 2000000 uint public fciDecimals = 1000000; uint256 public priceFci; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); // This notifies someone buy fci by NAC event BuyFci(address investor, uint256 valueNac, uint256 valueFci, uint timeBuyFci); event SellFci(address investor, uint256 valueNac, uint256 valueFci, uint timeSellFci); modifier onlyRunning { require(isPause == false); _; } /** * controller update balance of Netf to smart contract */ function addNacToNetf(uint _valueNac) public onlyController { NetfBalance = NetfBalance.add(_valueNac); } /** * controller update balance of Netf to smart contract */ function removeNacFromNetf(uint _valueNac) public onlyController { NetfBalance = NetfBalance.sub(_valueNac); } //////////////////////////////////////////////////////buy and sell fci function////////////////////////////////////////////////////////// /** * Setup pause phrase */ function changePause() public onlyController { isPause = !isPause; } /** * * * update price fci daily */ function updatePriceFci(uint _price, uint _timeExpires) onlyController public { require(now > timeExpires); priceFci = _price; timeExpires = _timeExpires; } /** * before buy users need to place buy Order * function buy fci * only controller can execute in phrase running */ function buyFci(address _buyer, uint _valueNac) onlyController public { // require fci is Running require(isPause == false && now < timeExpires); // require buyer not is 0x0 address require(_buyer != 0x0); require( _valueNac * fciDecimals > priceFci); uint fciReceive = (_valueNac.mul(fciDecimals))/priceFci; // construct fci balanceOf[_buyer] = balanceOf[_buyer].add(fciReceive); totalSupply = totalSupply.add(fciReceive); NetfBalance = NetfBalance.add(_valueNac); emit Transfer(address(this), _buyer, fciReceive); emit BuyFci(_buyer, _valueNac, fciReceive, now); } /** * * before controller buy fci for user * user nead to place sell order */ function placeSellFciOrder(uint _valueFci) onlyRunning public { require(balanceOf[msg.sender] >= _valueFci && _valueFci > 0); _transfer(msg.sender, address(this), _valueFci); emit PlaceSellFciOrder(msg.sender, _valueFci, now); } /** * * function sellFci * only controller can execute in phare running */ function sellFci(address _seller, uint _valueFci) onlyController public { // require fci is Running require(isPause == false && now < timeExpires); // require buyer not is 0x0 address require(_seller != 0x0); require(_valueFci * priceFci > fciDecimals); uint nacReturn = (_valueFci.mul(priceFci))/fciDecimals; // destroy fci balanceOf[address(this)] = balanceOf[address(this)].sub(_valueFci); totalSupply = totalSupply.sub(_valueFci); // update NETF balance NetfBalance = NetfBalance.sub(nacReturn); // send NAC NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); namiToken.transfer(_seller, nacReturn); emit Transfer(_seller, address(this), _valueFci); emit SellFci(_seller, nacReturn, _valueFci, now); } /////////////////////////////////////////////////////NETF Revenue function/////////////////////////////////////////////////////////////// struct ShareHolderNETF { uint stake; bool isWithdrawn; } struct RoundNetfRevenue { bool isOpen; uint currentNAC; uint totalFci; bool withdrawable; } uint public currentNetfRound; mapping (uint => RoundNetfRevenue) public NetfRevenue; mapping (uint => mapping(address => ShareHolderNETF)) public usersNETF; // 1. open Netf round /** * first controller open one round for netf revenue */ function openNetfRevenueRound(uint _roundIndex) onlyController public { require(NetfRevenue[_roundIndex].isOpen == false); currentNetfRound = _roundIndex; NetfRevenue[_roundIndex].isOpen = true; } /** * * this function update balance of NETF revenue funds add NAC to funds * only executable if round open and round not withdraw yet */ function depositNetfRevenue(uint _valueNac) onlyController public { require(NetfRevenue[currentNetfRound].isOpen == true && NetfRevenue[currentNetfRound].withdrawable == false); NetfRevenue[currentNetfRound].currentNAC = NetfRevenue[currentNetfRound].currentNAC.add(_valueNac); } /** * * this function update balance of NETF Funds remove NAC from funds * only executable if round open and round not withdraw yet */ function withdrawNetfRevenue(uint _valueNac) onlyController public { require(NetfRevenue[currentNetfRound].isOpen == true && NetfRevenue[currentNetfRound].withdrawable == false); NetfRevenue[currentNetfRound].currentNAC = NetfRevenue[currentNetfRound].currentNAC.sub(_valueNac); } // switch to pause phrase here /** * after pause all investor to buy, sell and exchange fci on the market * controller or investor latch final fci of current round */ function latchTotalFci(uint _roundIndex) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); require(NetfRevenue[_roundIndex].withdrawable == false); NetfRevenue[_roundIndex].totalFci = totalSupply; } function latchFciUserController(uint _roundIndex, address _investor) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); require(NetfRevenue[_roundIndex].withdrawable == false); require(balanceOf[_investor] > 0); usersNETF[_roundIndex][_investor].stake = balanceOf[_investor]; } /** * investor can latch Fci by themself */ function latchFciUser(uint _roundIndex) public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); require(NetfRevenue[_roundIndex].withdrawable == false); require(balanceOf[msg.sender] > 0); usersNETF[_roundIndex][msg.sender].stake = balanceOf[msg.sender]; } /** * after all investor latch fci, controller change round state withdrawable * now investor can withdraw NAC from NetfRevenue funds of this round * and auto switch to unpause phrase */ function changeWithdrawableNetfRe(uint _roundIndex) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); NetfRevenue[_roundIndex].withdrawable = true; isPause = false; } // after latch all investor, unpause here /** * withdraw NAC for * run by controller */ function withdrawNacNetfReController(uint _roundIndex, address _investor) onlyController public { require(NetfRevenue[_roundIndex].withdrawable == true && isPause == false && _investor != 0x0); require(usersNETF[_roundIndex][_investor].stake > 0 && usersNETF[_roundIndex][_investor].isWithdrawn == false); require(NetfRevenue[_roundIndex].totalFci > 0); // withdraw NAC uint nacReturn = ( NetfRevenue[_roundIndex].currentNAC.mul(usersNETF[_roundIndex][_investor].stake) ) / NetfRevenue[_roundIndex].totalFci; NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); namiToken.transfer(_investor, nacReturn); usersNETF[_roundIndex][_investor].isWithdrawn = true; } /** * withdraw NAC for * run by investor */ function withdrawNacNetfRe(uint _roundIndex) public { require(NetfRevenue[_roundIndex].withdrawable == true && isPause == false); require(usersNETF[_roundIndex][msg.sender].stake > 0 && usersNETF[_roundIndex][msg.sender].isWithdrawn == false); require(NetfRevenue[_roundIndex].totalFci > 0); // withdraw NAC uint nacReturn = ( NetfRevenue[_roundIndex].currentNAC.mul(usersNETF[_roundIndex][msg.sender].stake) ) / NetfRevenue[_roundIndex].totalFci; NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); namiToken.transfer(msg.sender, nacReturn); usersNETF[_roundIndex][msg.sender].isWithdrawn = true; } /////////////////////////////////////////////////////token fci function////////////////////////////////////////////////////////////////// /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyRunning { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyRunning returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyRunning returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyRunning returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////end fci token function/////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////pool function//////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// uint public currentRound = 1; uint public currentSubRound = 1; struct shareHolderNLF { uint fciNLF; bool isWithdrawnRound; } struct SubRound { uint totalNacInSubRound; bool isOpen; bool isCloseNacPool; } struct Round { bool isOpen; bool isActivePool; bool withdrawable; uint currentNAC; uint finalNAC; } // NLF Funds mapping(uint => Round) public NLFunds; mapping(uint => mapping(address => mapping(uint => bool))) public isWithdrawnSubRoundNLF; mapping(uint => mapping(uint => SubRound)) public listSubRoundNLF; mapping(uint => mapping(address => shareHolderNLF)) public membersNLF; event ActivateRound(uint RoundIndex, uint TimeActive); event ActivateSubRound(uint RoundIndex, uint TimeActive); // ------------------------------------------------ /** * Admin function * Open and Close Round */ function activateRound(uint _roundIndex) onlyEscrow public { // require round not open require(NLFunds[_roundIndex].isOpen == false); NLFunds[_roundIndex].isOpen = true; currentRound = _roundIndex; emit ActivateRound(_roundIndex, now); } ///////////////////////deposit to NLF funds in tokenFallbackExchange/////////////////////////////// /** * after all user deposit to NLF pool */ function deactivateRound(uint _roundIndex) onlyEscrow public { // require round id is openning require(NLFunds[_roundIndex].isOpen == true); NLFunds[_roundIndex].isActivePool = true; NLFunds[_roundIndex].isOpen = false; NLFunds[_roundIndex].finalNAC = NLFunds[_roundIndex].currentNAC; } /** * before send NAC to subround controller need active subround */ function activateSubRound(uint _subRoundIndex) onlyController public { // require current round is not open and pool active require(NLFunds[currentRound].isOpen == false && NLFunds[currentRound].isActivePool == true); // require sub round not open require(listSubRoundNLF[currentRound][_subRoundIndex].isOpen == false); // currentSubRound = _subRoundIndex; require(listSubRoundNLF[currentRound][_subRoundIndex].isCloseNacPool == false); listSubRoundNLF[currentRound][_subRoundIndex].isOpen = true; emit ActivateSubRound(_subRoundIndex, now); } /** * every week controller deposit to subround to send NAC to all user have NLF fci */ function depositToSubRound(uint _value) onlyController public { // require sub round is openning require(currentSubRound != 0); require(listSubRoundNLF[currentRound][currentSubRound].isOpen == true); require(listSubRoundNLF[currentRound][currentSubRound].isCloseNacPool == false); // modify total NAC in each subround listSubRoundNLF[currentRound][currentSubRound].totalNacInSubRound = listSubRoundNLF[currentRound][currentSubRound].totalNacInSubRound.add(_value); } /** * every week controller deposit to subround to send NAC to all user have NLF fci */ function withdrawFromSubRound(uint _value) onlyController public { // require sub round is openning require(currentSubRound != 0); require(listSubRoundNLF[currentRound][currentSubRound].isOpen == true); require(listSubRoundNLF[currentRound][currentSubRound].isCloseNacPool == false); // modify total NAC in each subround listSubRoundNLF[currentRound][currentSubRound].totalNacInSubRound = listSubRoundNLF[currentRound][currentSubRound].totalNacInSubRound.sub(_value); } /** * controller close deposit subround phrase and user can withdraw NAC from subround */ function closeDepositSubRound() onlyController public { require(listSubRoundNLF[currentRound][currentSubRound].isOpen == true); require(listSubRoundNLF[currentRound][currentSubRound].isCloseNacPool == false); listSubRoundNLF[currentRound][currentSubRound].isCloseNacPool = true; } /** * user withdraw NAC from each subround of NLF funds for investor */ function withdrawSubRound(uint _subRoundIndex) public { // require close deposit to subround require(listSubRoundNLF[currentRound][_subRoundIndex].isCloseNacPool == true); // user not ever withdraw nac in this subround require(isWithdrawnSubRoundNLF[currentRound][msg.sender][_subRoundIndex] == false); // require user have fci require(membersNLF[currentRound][msg.sender].fciNLF > 0); // withdraw token NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint nacReturn = (listSubRoundNLF[currentRound][_subRoundIndex].totalNacInSubRound.mul(membersNLF[currentRound][msg.sender].fciNLF)).div(NLFunds[currentRound].finalNAC); namiToken.transfer(msg.sender, nacReturn); isWithdrawnSubRoundNLF[currentRound][msg.sender][_subRoundIndex] = true; } /** * controller of NLF add NAC to update NLF balance * this NAC come from 10% trading revenue */ function addNacToNLF(uint _value) public onlyController { require(NLFunds[currentRound].isActivePool == true); require(NLFunds[currentRound].withdrawable == false); NLFunds[currentRound].currentNAC = NLFunds[currentRound].currentNAC.add(_value); } /** * controller get NAC from NLF pool to send to trader */ function removeNacFromNLF(uint _value) public onlyController { require(NLFunds[currentRound].isActivePool == true); require(NLFunds[currentRound].withdrawable == false); NLFunds[currentRound].currentNAC = NLFunds[currentRound].currentNAC.sub(_value); } /** * end of round escrow run this to allow user sell fci to receive NAC */ function changeWithdrawableRound(uint _roundIndex) public onlyEscrow { require(NLFunds[currentRound].isActivePool == true); require(NLFunds[_roundIndex].withdrawable == false && NLFunds[_roundIndex].isOpen == false); NLFunds[_roundIndex].withdrawable = true; } /** * end of round user sell fci to receive NAC from NLF funds * function for investor */ function withdrawRound(uint _roundIndex) public { require(NLFunds[_roundIndex].withdrawable == true); require(membersNLF[currentRound][msg.sender].isWithdrawnRound == false); require(membersNLF[currentRound][msg.sender].fciNLF > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint nacReturn = NLFunds[currentRound].currentNAC.mul(membersNLF[currentRound][msg.sender].fciNLF).div(NLFunds[currentRound].finalNAC); namiToken.transfer(msg.sender, nacReturn); // update status round membersNLF[currentRound][msg.sender].isWithdrawnRound = true; membersNLF[currentRound][msg.sender].fciNLF = 0; } function withdrawRoundController(uint _roundIndex, address _investor) public onlyController { require(NLFunds[_roundIndex].withdrawable == true); require(membersNLF[currentRound][_investor].isWithdrawnRound == false); require(membersNLF[currentRound][_investor].fciNLF > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint nacReturn = NLFunds[currentRound].currentNAC.mul(membersNLF[currentRound][_investor].fciNLF).div(NLFunds[currentRound].finalNAC); namiToken.transfer(msg.sender, nacReturn); // update status round membersNLF[currentRound][_investor].isWithdrawnRound = true; membersNLF[currentRound][_investor].fciNLF = 0; } /** * fall back function call from nami crawsale smart contract * deposit NAC to NAMI TRADE broker, invest to NETF and NLF funds */ function tokenFallbackExchange(address _from, uint _value, uint _choose) onlyNami public returns (bool success) { require(_choose <= 2); if (_choose == 0) { // deposit NAC to nami trade broker require(_value >= minNac); emit Deposit(_from, _value, now); } else if(_choose == 1) { require(_value >= minNac && NLFunds[currentRound].isOpen == true); // invest to NLF funds membersNLF[currentRound][_from].fciNLF = membersNLF[currentRound][_from].fciNLF.add(_value); NLFunds[currentRound].currentNAC = NLFunds[currentRound].currentNAC.add(_value); emit InvestToNLF(_from, _value, now); } else if(_choose == 2) { // invest NAC to NETF Funds require(_value >= minNac); // msg.value >= 0.1 ether emit PlaceBuyFciOrder(_from, _value, now); } return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////end pool function/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // withdraw token function withdrawToken(address _account, uint _amount) public onlyController { require(_amount >= minWithdraw && _amount <= maxWithdraw); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(address(this)); require(previousBalances >= _amount); // transfer token namiToken.transfer(_account, _amount); // emit event emit Withdraw(_account, _amount, now); assert(previousBalances >= namiToken.balanceOf(address(this))); } }
after all investor latch fci, controller change round state withdrawable now investor can withdraw NAC from NetfRevenue funds of this round and auto switch to unpause phrase/
function changeWithdrawableNetfRe(uint _roundIndex) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); NetfRevenue[_roundIndex].withdrawable = true; isPause = false; }
2,024,894
// Sources flattened with hardhat v2.6.1 https://hardhat.org // File contracts/chainlink/interfaces/AuthorizedReceiverInterface.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AuthorizedReceiverInterface { function isAuthorizedSender( address sender ) external view returns (bool); function getAuthorizedSenders() external returns ( address[] memory ); function setAuthorizedSenders( address[] calldata senders ) external; } // File contracts/chainlink/AuthorizedReceiver.sol abstract contract AuthorizedReceiver is AuthorizedReceiverInterface { mapping(address => bool) private s_authorizedSenders; address[] private s_authorizedSenderList; event AuthorizedSendersChanged( address[] senders, address changedBy ); /** * @notice Sets the fulfillment permission for a given node. Use `true` to allow, `false` to disallow. * @param senders The addresses of the authorized Chainlink node */ function setAuthorizedSenders( address[] calldata senders ) external override validateAuthorizedSenderSetter() { require(senders.length > 0, "Must have at least 1 authorized sender"); // Set previous authorized senders to false uint256 authorizedSendersLength = s_authorizedSenderList.length; for (uint256 i = 0; i < authorizedSendersLength; i++) { s_authorizedSenders[s_authorizedSenderList[i]] = false; } // Set new to true for (uint256 i = 0; i < senders.length; i++) { s_authorizedSenders[senders[i]] = true; } // Replace list s_authorizedSenderList = senders; emit AuthorizedSendersChanged(senders, msg.sender); } /** * @notice Retrieve a list of authorized senders * @return array of addresses */ function getAuthorizedSenders() external view override returns ( address[] memory ) { return s_authorizedSenderList; } /** * @notice Use this to check if a node is authorized for fulfilling requests * @param sender The address of the Chainlink node * @return The authorization status of the node */ function isAuthorizedSender( address sender ) public view override returns (bool) { return s_authorizedSenders[sender]; } /** * @notice customizable guard of who can update the authorized sender list * @return bool whether sender can update authorized sender list */ function _canSetAuthorizedSenders() internal virtual returns (bool); /** * @notice validates the sender is an authorized sender */ function _validateIsAuthorizedSender() internal view { require(isAuthorizedSender(msg.sender), "Not authorized sender"); } /** * @notice prevents non-authorized addresses from calling this method */ modifier validateAuthorizedSender() { _validateIsAuthorizedSender(); _; } /** * @notice prevents non-authorized addresses from calling this method */ modifier validateAuthorizedSenderSetter() { require(_canSetAuthorizedSenders(), "Cannot set authorized senders"); _; } } // File contracts/chainlink/LinkTokenReceiver.sol abstract contract LinkTokenReceiver { /** * @notice Called when LINK is sent to the contract via `transferAndCall` * @dev The data payload's first 2 words will be overwritten by the `sender` and `amount` * values to ensure correctness. Calls oracleRequest. * @param sender Address of the sender * @param amount Amount of LINK sent (specified in wei) * @param data Payload of the transaction */ function onTokenTransfer( address sender, uint256 amount, bytes memory data ) public validateFromLINK() permittedFunctionsForLINK(data) { // solhint-disable-next-line no-inline-assembly assembly { // solhint-disable-next-line no-inline-assembly mstore(add(data, 36), sender) // ensure correct sender is passed // solhint-disable-next-line avoid-low-level-calls mstore(add(data, 68), amount) // ensure correct amount is passed } // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).delegatecall(data); // calls oracleRequest require(success, "Unable to create request"); } function getChainlinkToken() public view virtual returns ( address ); /** * @notice Validate the function called on token transfer */ function _validateTokenTransferAction( bytes4 funcSelector, bytes memory data ) internal virtual; /** * @dev Reverts if not sent from the LINK token */ modifier validateFromLINK() { require(msg.sender == getChainlinkToken(), "Must use LINK token"); _; } /** * @dev Reverts if the given data does not begin with the `oracleRequest` function selector * @param data The data payload of the request */ modifier permittedFunctionsForLINK( bytes memory data ) { bytes4 funcSelector; // solhint-disable-next-line no-inline-assembly assembly { // solhint-disable-next-line avoid-low-level-calls funcSelector := mload(add(data, 32)) } _validateTokenTransferAction(funcSelector, data); _; } } // File contracts/chainlink/interfaces/OwnableInterface.sol interface OwnableInterface { function owner() external returns ( address ); function transferOwnership( address recipient ) external; function acceptOwnership() external; } // File contracts/chainlink/ConfirmedOwnerWithProposal.sol /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwnerWithProposal is OwnableInterface { address private s_owner; address private s_pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor( address newOwner, address pendingOwner ) { require(newOwner != address(0), "Cannot set owner to zero"); s_owner = newOwner; if (pendingOwner != address(0)) { _transferOwnership(pendingOwner); } } /** * @notice Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership( address to ) public override onlyOwner() { _transferOwnership(to); } /** * @notice Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external override { require(msg.sender == s_pendingOwner, "Must be proposed owner"); address oldOwner = s_owner; s_owner = msg.sender; s_pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @notice Get the current owner */ function owner() public view override returns ( address ) { return s_owner; } /** * @notice validate, transfer ownership, and emit relevant events */ function _transferOwnership( address to ) private { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); } /** * @notice validate access */ function _validateOwnership() internal view { require(msg.sender == s_owner, "Only callable by owner"); } /** * @notice Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { _validateOwnership(); _; } } // File contracts/chainlink/ConfirmedOwner.sol /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwner is ConfirmedOwnerWithProposal { constructor( address newOwner ) ConfirmedOwnerWithProposal( newOwner, address(0) ) { } } // File contracts/chainlink/interfaces/LinkTokenInterface.sol interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // File contracts/chainlink/interfaces/ChainlinkRequestInterface.sol interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } // File contracts/chainlink/interfaces/OracleInterface.sol interface OracleInterface { function fulfillOracleRequest( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data ) external returns ( bool ); function withdraw( address recipient, uint256 amount ) external; function withdrawable() external view returns ( uint256 ); } // File contracts/chainlink/interfaces/OperatorInterface.sol interface OperatorInterface is ChainlinkRequestInterface, OracleInterface { function requestOracleData( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function fulfillOracleRequest2( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data ) external returns ( bool ); function ownerTransferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); } // File contracts/chainlink/interfaces/WithdrawalInterface.sol interface WithdrawalInterface { /** * @notice transfer LINK held by the contract belonging to msg.sender to * another address * @param recipient is the address to send the LINK to * @param amount is the amount of LINK to send */ function withdraw( address recipient, uint256 amount ) external; /** * @notice query the available amount of LINK to withdraw by msg.sender */ function withdrawable() external view returns ( uint256 ); } // File contracts/chainlink/vendor/Address.sol // From https://github.com/OpenZeppelin/openzeppelin-contracts v3.4.0(fa64a1ced0b70ab89073d5d0b6e01b0778f7e7d6) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/chainlink/vendor/SafeMathChainlink.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 SafeMathChainlink { /** * @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; } } // File contracts/chainlink/Operator.sol /** * @title The Chainlink Operator contract * @notice Node operators can deploy this contract to fulfill requests sent to them */ contract Operator is AuthorizedReceiver, ConfirmedOwner, LinkTokenReceiver, OperatorInterface, WithdrawalInterface { using Address for address; using SafeMathChainlink for uint256; struct Commitment { bytes31 paramsHash; uint8 dataVersion; } uint256 constant public GET_EXPIRY_TIME = 5 minutes; uint256 constant private MAXIMUM_DATA_VERSION = 256; uint256 constant private MINIMUM_CONSUMER_GAS_LIMIT = 400000; uint256 constant private SELECTOR_LENGTH = 4; uint256 constant private EXPECTED_REQUEST_WORDS = 2; uint256 constant private MINIMUM_REQUEST_LENGTH = SELECTOR_LENGTH + (32 * EXPECTED_REQUEST_WORDS); // We initialize fields to 1 instead of 0 so that the first invocation // does not cost more gas. uint256 constant private ONE_FOR_CONSISTENT_GAS_COST = 1; // oracleRequest is version 1, enabling single word responses bytes4 constant private ORACLE_REQUEST_SELECTOR = this.oracleRequest.selector; // requestOracleData is version 2, enabling multi-word responses bytes4 constant private OPERATOR_REQUEST_SELECTOR = this.requestOracleData.selector; LinkTokenInterface internal immutable linkToken; mapping(bytes32 => Commitment) private sCommitments; // Tokens sent for requests that have not been fulfilled yet uint256 private sTokensInEscrow = ONE_FOR_CONSISTENT_GAS_COST; event OracleRequest( bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data ); event CancelOracleRequest( bytes32 indexed requestId ); event OracleResponse( bytes32 indexed requestId ); event OwnableContractAccepted( address indexed accpetedContract ); event TargetsUpdatedAuthorizedSenders( address[] targets, address[] senders, address changedBy ); /** * @notice Deploy with the address of the LINK token * @dev Sets the LinkToken address for the imported LinkTokenInterface * @param link The address of the LINK token * @param owner The address of the owner */ constructor( address link, address owner ) ConfirmedOwner(owner) { linkToken = LinkTokenInterface(link); // external but already deployed and unalterable } function oracleRequest( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external override { requestOracleData( sender, payment, specId, callbackAddress, callbackFunctionId, nonce, dataVersion, data ); } /** * @notice Creates the Chainlink request * @dev Stores the hash of the params as the on-chain commitment for the request. * Emits OracleRequest event for the Chainlink node to detect. * @param sender The sender of the request * @param payment The amount of payment given (specified in wei) * @param specId The Job Specification ID * @param callbackAddress The callback address for the response * @param callbackFunctionId The callback function ID for the response * @param nonce The nonce sent by the requester * @param dataVersion The specified data version * @param data The CBOR payload of the request */ function requestOracleData( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) public override validateFromLINK() validateNotToLINK(callbackAddress) { (bytes32 requestId, uint256 expiration) = _verifyOracleRequest( sender, payment, callbackAddress, callbackFunctionId, nonce, dataVersion ); emit OracleRequest( specId, sender, requestId, payment, callbackAddress, callbackFunctionId, expiration, dataVersion, data); } /** * @notice Called by the Chainlink node to fulfill requests * @dev Given params must hash back to the commitment stored from `oracleRequest`. * Will call the callback address' callback function without bubbling up error * checking in a `require` so that the node can get paid. * @param requestId The fulfillment request ID that must match the requester's * @param payment The payment amount that will be released for the oracle (specified in wei) * @param callbackAddress The callback address to call for fulfillment * @param callbackFunctionId The callback function ID to use for fulfillment * @param expiration The expiration that the node should respond by before the requester can cancel * @param data The data to return to the consuming contract * @return Status if the external call was successful */ function fulfillOracleRequest( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data ) external override validateAuthorizedSender() validateRequestId(requestId) returns ( bool ) { _verifyOracleResponse( requestId, payment, callbackAddress, callbackFunctionId, expiration, 1 ); emit OracleResponse(requestId); require(gasleft() >= MINIMUM_CONSUMER_GAS_LIMIT, "Must provide consumer enough gas"); // All updates to the oracle's fulfillment should come before calling the // callback(addr+functionId) as it is untrusted. // See: https://solidity.readthedocs.io/en/develop/security-considerations.html#use-the-checks-effects-interactions-pattern (bool success, ) = callbackAddress.call(abi.encodeWithSelector(callbackFunctionId, requestId, data)); // solhint-disable-line avoid-low-level-calls return success; } /** * @notice Called by the Chainlink node to fulfill requests with multi-word support * @dev Given params must hash back to the commitment stored from `oracleRequest`. * Will call the callback address' callback function without bubbling up error * checking in a `require` so that the node can get paid. * @param requestId The fulfillment request ID that must match the requester's * @param payment The payment amount that will be released for the oracle (specified in wei) * @param callbackAddress The callback address to call for fulfillment * @param callbackFunctionId The callback function ID to use for fulfillment * @param expiration The expiration that the node should respond by before the requester can cancel * @param data The data to return to the consuming contract * @return Status if the external call was successful */ function fulfillOracleRequest2( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data ) external override validateAuthorizedSender() validateRequestId(requestId) validateMultiWordResponseId(requestId, data) returns ( bool ) { _verifyOracleResponse( requestId, payment, callbackAddress, callbackFunctionId, expiration, 2 ); emit OracleResponse(requestId); require(gasleft() >= MINIMUM_CONSUMER_GAS_LIMIT, "Must provide consumer enough gas"); // All updates to the oracle's fulfillment should come before calling the // callback(addr+functionId) as it is untrusted. // See: https://solidity.readthedocs.io/en/develop/security-considerations.html#use-the-checks-effects-interactions-pattern (bool success, ) = callbackAddress.call(abi.encodePacked(callbackFunctionId, data)); // solhint-disable-line avoid-low-level-calls return success; } /** * @notice Transfer the ownership of ownable contracts * @param ownable list of addresses to transfer * @param newOwner address to transfer ownership to */ function transferOwnableContracts( address[] calldata ownable, address newOwner ) external onlyOwner() { for (uint256 i = 0; i < ownable.length; i++) { OwnableInterface(ownable[i]).transferOwnership(newOwner); } } /** * @notice Accept the ownership of an ownable contract * @dev Must be the pending owner on the contract * @param ownable list of addresses of Ownable contracts to accept */ function acceptOwnableContracts( address[] calldata ownable ) public validateAuthorizedSenderSetter() { for (uint256 i = 0; i < ownable.length; i++) { OwnableInterface(ownable[i]).acceptOwnership(); emit OwnableContractAccepted(ownable[i]); } } /** * @notice Sets the fulfillment permission for * @param targets The addresses to set permissions on * @param senders The addresses that are allowed to send updates */ function setAuthorizedSendersOn( address[] calldata targets, address[] calldata senders ) public validateAuthorizedSenderSetter() { emit TargetsUpdatedAuthorizedSenders(targets, senders, msg.sender); for (uint256 i = 0; i < targets.length; i++) { AuthorizedReceiverInterface(targets[i]).setAuthorizedSenders(senders); } } /** * @notice Sets the fulfillment permission for * @param targets The addresses to set permissions on * @param senders The addresses that are allowed to send updates */ function acceptAuthorizedReceivers( address[] calldata targets, address[] calldata senders ) external validateAuthorizedSenderSetter() { acceptOwnableContracts(targets); setAuthorizedSendersOn(targets, senders); } /** * @notice Allows the node operator to withdraw earned LINK to a given address * @dev The owner of the contract can be another wallet and does not have to be a Chainlink node * @param recipient The address to send the LINK token to * @param amount The amount to send (specified in wei) */ function withdraw( address recipient, uint256 amount ) external override(OracleInterface, WithdrawalInterface) onlyOwner() validateAvailableFunds(amount) { assert(linkToken.transfer(recipient, amount)); } /** * @notice Displays the amount of LINK that is available for the node operator to withdraw * @dev We use `ONE_FOR_CONSISTENT_GAS_COST` in place of 0 in storage * @return The amount of withdrawable LINK on the contract */ function withdrawable() external view override(OracleInterface, WithdrawalInterface) returns (uint256) { return _fundsAvailable(); } /** * @notice Forward a call to another contract * @dev Only callable by the owner * @param to address * @param data to forward */ function ownerForward( address to, bytes calldata data ) external onlyOwner() validateNotToLINK(to) { require(to.isContract(), "Must forward to a contract"); // solhint-disable-next-line avoid-low-level-calls (bool status,) = to.call(data); require(status, "Forwarded call failed"); } /** * @notice Interact with other LinkTokenReceiver contracts by calling transferAndCall * @param to The address to transfer to. * @param value The amount to be transferred. * @param data The extra data to be passed to the receiving contract. * @return success bool */ function ownerTransferAndCall( address to, uint256 value, bytes calldata data ) external override onlyOwner() validateAvailableFunds(value) returns ( bool success ) { return linkToken.transferAndCall(to, value, data); } /** * @notice Distribute funds to multiple addresses using ETH send * to this payable function. * @dev Array length must be equal, ETH sent must equal the sum of amounts. * @param receivers list of addresses * @param amounts list of amounts */ function distributeFunds( address payable[] calldata receivers, uint[] calldata amounts ) external payable { require(receivers.length > 0 && receivers.length == amounts.length, "Invalid array length(s)"); uint256 valueRemaining = msg.value; for (uint256 i = 0; i < receivers.length; i++) { uint256 sendAmount = amounts[i]; valueRemaining = valueRemaining.sub(sendAmount); receivers[i].transfer(sendAmount); } require(valueRemaining == 0, "Too much ETH sent"); } /** * @notice Allows requesters to cancel requests sent to this oracle contract. Will transfer the LINK * sent for the request back to the requester's address. * @dev Given params must hash to a commitment stored on the contract in order for the request to be valid * Emits CancelOracleRequest event. * @param requestId The request ID * @param payment The amount of payment given (specified in wei) * @param callbackFunc The requester's specified callback address * @param expiration The time of the expiration for the request */ function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunc, uint256 expiration ) external override { bytes31 paramsHash = _buildFunctionHash(payment, msg.sender, callbackFunc, expiration); require(sCommitments[requestId].paramsHash == paramsHash, "Params do not match request ID"); // solhint-disable-next-line not-rely-on-time require(expiration <= block.timestamp, "Request is not expired"); delete sCommitments[requestId]; emit CancelOracleRequest(requestId); assert(linkToken.transfer(msg.sender, payment)); } /** * @notice Returns the address of the LINK token * @dev This is the public implementation for chainlinkTokenAddress, which is * an internal method of the ChainlinkClient contract */ function getChainlinkToken() public view override returns ( address ) { return address(linkToken); } /** * @notice Require that the token transfer action is valid * @dev OPERATOR_REQUEST_SELECTOR = multiword, ORACLE_REQUEST_SELECTOR = singleword */ function _validateTokenTransferAction( bytes4 funcSelector, bytes memory data ) internal override pure { require(data.length >= MINIMUM_REQUEST_LENGTH, "Invalid request length"); require(funcSelector == OPERATOR_REQUEST_SELECTOR || funcSelector == ORACLE_REQUEST_SELECTOR, "Must use whitelisted functions"); } /** * @notice Verify the Oracle Request * @param sender The sender of the request * @param payment The amount of payment given (specified in wei) * @param callbackAddress The callback address for the response * @param callbackFunctionId The callback function ID for the response * @param nonce The nonce sent by the requester */ function _verifyOracleRequest( address sender, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion ) private returns ( bytes32 requestId, uint256 expiration ) { requestId = keccak256(abi.encodePacked(sender, nonce)); require(sCommitments[requestId].paramsHash == 0, "Must use a unique ID"); // solhint-disable-next-line not-rely-on-time expiration = block.timestamp.add(GET_EXPIRY_TIME); bytes31 paramsHash = _buildFunctionHash(payment, callbackAddress, callbackFunctionId, expiration); sCommitments[requestId] = Commitment(paramsHash, _safeCastToUint8(dataVersion)); sTokensInEscrow = sTokensInEscrow.add(payment); return (requestId, expiration); } /** * @notice Verify the Oracle Response * @param requestId The fulfillment request ID that must match the requester's * @param payment The payment amount that will be released for the oracle (specified in wei) * @param callbackAddress The callback address to call for fulfillment * @param callbackFunctionId The callback function ID to use for fulfillment * @param expiration The expiration that the node should respond by before the requester can cancel */ function _verifyOracleResponse( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, uint256 dataVersion ) internal { bytes31 paramsHash = _buildFunctionHash(payment, callbackAddress, callbackFunctionId, expiration); require(sCommitments[requestId].paramsHash == paramsHash, "Params do not match request ID"); require(sCommitments[requestId].dataVersion <= _safeCastToUint8(dataVersion), "Data versions must match"); sTokensInEscrow = sTokensInEscrow.sub(payment); delete sCommitments[requestId]; } /** * @notice Build the bytes31 function hash from the payment, callback and expiration. * @param payment The payment amount that will be released for the oracle (specified in wei) * @param callbackAddress The callback address to call for fulfillment * @param callbackFunctionId The callback function ID to use for fulfillment * @param expiration The expiration that the node should respond by before the requester can cancel * @return hash bytes31 */ function _buildFunctionHash( uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration ) internal pure returns ( bytes31 ) { return bytes31(keccak256( abi.encodePacked( payment, callbackAddress, callbackFunctionId, expiration ) )); } /** * @notice Safely cast uint256 to uint8 * @param number uint256 * @return uint8 number */ function _safeCastToUint8( uint256 number ) internal pure returns ( uint8 ) { require(number < MAXIMUM_DATA_VERSION, "number too big to cast"); return uint8(number); } /** * @notice Returns the LINK available in this contract, not locked in escrow * @return uint256 LINK tokens available */ function _fundsAvailable() private view returns ( uint256 ) { uint256 inEscrow = sTokensInEscrow.sub(ONE_FOR_CONSISTENT_GAS_COST); return linkToken.balanceOf(address(this)).sub(inEscrow); } /** * @notice concrete implementation of AuthorizedReceiver * @return bool of whether sender is authorized */ function _canSetAuthorizedSenders() internal view override returns (bool) { return isAuthorizedSender(msg.sender) || owner() == msg.sender; } // MODIFIERS /** * @dev Reverts if the first 32 bytes of the bytes array is not equal to requestId * @param requestId bytes32 * @param data bytes */ modifier validateMultiWordResponseId( bytes32 requestId, bytes memory data ) { bytes32 firstWord; // solhint-disable-next-line no-inline-assembly assembly{ firstWord := mload(add(data, 0x20)) } require(requestId == firstWord, "First word must be requestId"); _; } /** * @dev Reverts if amount requested is greater than withdrawable balance * @param amount The given amount to compare to `s_withdrawableTokens` */ modifier validateAvailableFunds( uint256 amount ) { require(_fundsAvailable() >= amount, "Amount requested is greater than withdrawable balance"); _; } /** * @dev Reverts if request ID does not exist * @param requestId The given request ID to check in stored `commitments` */ modifier validateRequestId( bytes32 requestId ) { require(sCommitments[requestId].paramsHash != 0, "Must have a valid requestId"); _; } /** * @dev Reverts if the callback address is the LINK token * @param to The callback address */ modifier validateNotToLINK( address to ) { require(to != address(linkToken), "Cannot call to LINK"); _; } } // File contracts/chainlink/AuthorizedForwarder.sol contract AuthorizedForwarder is ConfirmedOwnerWithProposal, AuthorizedReceiver { using Address for address; address public immutable getChainlinkToken; event OwnershipTransferRequestedWithMessage( address indexed from, address indexed to, bytes message ); constructor( address link, address owner, address recipient, bytes memory message ) ConfirmedOwnerWithProposal(owner, recipient) { getChainlinkToken = link; if (recipient != address(0)) { emit OwnershipTransferRequestedWithMessage(owner, recipient, message); } } /** * @notice Forward a call to another contract * @dev Only callable by an authorized sender * @param to address * @param data to forward */ function forward( address to, bytes calldata data ) external validateAuthorizedSender() { require(to != getChainlinkToken, "Cannot #forward to Link token"); _forward(to, data); } /** * @notice Forward a call to another contract * @dev Only callable by the owner * @param to address * @param data to forward */ function ownerForward( address to, bytes calldata data ) external onlyOwner() { _forward(to, data); } /** * @notice Transfer ownership with instructions for recipient * @param to address proposed recipeint of ownership * @param message instructions for recipient upon accepting ownership */ function transferOwnershipWithMessage( address to, bytes memory message ) public { transferOwnership(to); emit OwnershipTransferRequestedWithMessage(msg.sender, to, message); } /** * @notice concrete implementation of AuthorizedReceiver * @return bool of whether sender is authorized */ function _canSetAuthorizedSenders() internal view override returns (bool) { return owner() == msg.sender; } /** * @notice common forwarding functionality and validation */ function _forward( address to, bytes calldata data ) private { require(to.isContract(), "Must forward to a contract"); (bool status,) = to.call(data); require(status, "Forwarded call failed"); } } // File contracts/chainlink/OperatorFactory.sol /** * @title Operator Factory * @notice Creates Operator contracts for node operators */ contract OperatorFactory { address public immutable getChainlinkToken; mapping(address => bool) private s_created; event OperatorCreated( address indexed operator, address indexed owner, address indexed sender ); event AuthorizedForwarderCreated( address indexed forwarder, address indexed owner, address indexed sender ); /** * @param linkAddress address */ constructor( address linkAddress ) { getChainlinkToken = linkAddress; } /** * @notice creates a new Operator contract with the msg.sender as owner */ function deployNewOperator() external returns ( address ) { Operator operator = new Operator( getChainlinkToken, msg.sender ); s_created[address(operator)] = true; emit OperatorCreated( address(operator), msg.sender, msg.sender ); return address(operator); } /** * @notice creates a new Operator contract with the msg.sender as owner and a * new Operator Forwarder with the Operator as the owner */ function deployNewOperatorAndForwarder() external returns ( address, address ) { Operator operator = new Operator( getChainlinkToken, msg.sender ); s_created[address(operator)] = true; emit OperatorCreated( address(operator), msg.sender, msg.sender ); bytes memory tmp = new bytes(0); AuthorizedForwarder forwarder = new AuthorizedForwarder( getChainlinkToken, address(operator), address(0), tmp ); s_created[address(forwarder)] = true; emit AuthorizedForwarderCreated( address(forwarder), address(operator), msg.sender ); return (address(operator), address(forwarder)); } /** * @notice creates a new Forwarder contract with the msg.sender as owner */ function deployNewForwarder() external returns ( address ) { bytes memory tmp = new bytes(0); AuthorizedForwarder forwarder = new AuthorizedForwarder( getChainlinkToken, msg.sender, address(0), tmp ); s_created[address(forwarder)] = true; emit AuthorizedForwarderCreated( address(forwarder), msg.sender, msg.sender ); return address(forwarder); } /** * @notice creates a new Forwarder contract with the msg.sender as owner */ function deployNewForwarderAndTransferOwnership( address to, bytes calldata message ) external returns ( address ) { AuthorizedForwarder forwarder = new AuthorizedForwarder( getChainlinkToken, msg.sender, to, message ); s_created[address(forwarder)] = true; emit AuthorizedForwarderCreated( address(forwarder), msg.sender, msg.sender ); return address(forwarder); } /** * @notice indicates whether this factory deployed an address */ function created( address query ) external view returns (bool) { return s_created[query]; } }
Forward a call to another contract Only callable by the owner to address data to forward/
function ownerForward( address to, bytes calldata data ) external onlyOwner() { _forward(to, data); }
15,839,771
./partial_match/100/0x0881E22BeDeDf41DdAa38A1cC571b805A8406251/sources/DMEX_Trading.sol
closes position for user
function closeFuturesPositionForUser (bytes32 futuresContract, bool side, address user, address poolAddress, uint256 expirationFee) onlyAdmin { closeFuturesPositionInternal(futuresContract, side, user, poolAddress, expirationFee); }
16,645,090
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //import {RedirectAll, ISuperToken, IConstantFlowAgreementV1, ISuperfluid} from "./RedirectAll.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {IConstantFlowAgreementV1} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol"; import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol"; import { ISuperfluid, ISuperToken, ISuperApp, ISuperAgreement, ContextDefinitions, SuperAppDefinitions } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol"; // Interface for ChainlinkKeepers //interface KeeperCompatibleInterface { // function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData); // function performUpkeep(bytes calldata performData) external; //} //contract MagePadNFT is ERC721, RedirectAll, KeeperCompatibleInterface { contract CrowdfundingNFT is ERC721 { uint256 tokenId; address operator; uint256 public oldTokenId; //For Kovantestnet ISuperfluid host = ISuperfluid(0xF0d7d1D47109bA426B9D8A3Cde1941327af1eea3); IConstantFlowAgreementV1 cfa = IConstantFlowAgreementV1(0xECa8056809e7e8db04A8fF6e4E82cD889a46FE2F); // Storing single NFT Data struct nftData { uint256 startingBlockTime; uint256 endingBlockTime; address streamReceiver; uint256 streamAmount; uint256 streamRate; address streamToken; uint256 securityAmount; address minter; bool isStopped; address[] investors; uint256 originalStreamAmount; } // storing which address funded which nft with how many tokens mapping (uint256 => mapping(address => uint256)) public nftAccounting; // Storing all NFTs mapping (uint256 => nftData) public allNFTs; constructor (address _operator) ERC721 ("CrowdfundingNFT", "CFNFT") { tokenId = 1; operator = _operator; uint256 configWord = SuperAppDefinitions.APP_LEVEL_FINAL | SuperAppDefinitions.BEFORE_AGREEMENT_CREATED_NOOP | SuperAppDefinitions.BEFORE_AGREEMENT_UPDATED_NOOP | SuperAppDefinitions.BEFORE_AGREEMENT_TERMINATED_NOOP; host.registerApp(configWord); } function checkForUpdate() public view returns(uint256[] memory) { uint256[] memory flowsToStop = new uint256[](tokenId); uint256 counter = 0; for(uint256 i = 1; i < tokenId; i++) { //calculating the actual streamed amount uint256 _alreadyStreamedAmount = (block.timestamp - allNFTs[tokenId].startingBlockTime) * allNFTs[tokenId].streamRate; if(_alreadyStreamedAmount >= allNFTs[i].streamAmount && allNFTs[i].isStopped == false) { flowsToStop[counter] = i; counter = counter + 1; } } return flowsToStop; } function performUpdate(uint256[] memory _flowsToStop) public { for(uint256 i = 0; i < _flowsToStop.length; i++) { // Stop the Flow stopFlow(_flowsToStop[i]); uint256 _toMuchStreamedAmount = (block.timestamp - allNFTs[_flowsToStop[i]].endingBlockTime) * allNFTs[_flowsToStop[i]].streamRate; uint256 _resultingSecurityAmount = allNFTs[_flowsToStop[i]].securityAmount - _toMuchStreamedAmount; ISuperToken(allNFTs[_flowsToStop[i]].streamToken).transfer(allNFTs[_flowsToStop[i]].minter, _resultingSecurityAmount); // set NFT to zero allNFTs[_flowsToStop[i]].streamRate = 0; allNFTs[_flowsToStop[i]].securityAmount = 0; allNFTs[_flowsToStop[i]].streamAmount = 0; } } function mint(uint8 _isSupertoken, uint256 _streamAmount, uint256 _streamRate, address _streamToken, address _erc20TokenAddress, address _projectOwner) public { uint256 _startingBlockTime = block.timestamp; uint256 _securityAmount = _streamRate * (60 * 60); address[] memory _investor = new address[](1); _investor[0] = msg.sender; //decide if the token to be streamed is a supertoken or not if(_isSupertoken == 1) { //get the supertoken out of the senders pocket and store the balance in the mapping require(ISuperToken(_streamToken).balanceOf(msg.sender) > (_streamAmount + _securityAmount), "Not enough funds in your wallet to pay for stream and security"); ISuperToken(_streamToken).transferFrom(msg.sender, address(this), (_streamAmount + _securityAmount)); } if(_isSupertoken == 2) { //get the erc20 token out of the senders pocket, store and start upgrading require(IERC20(_erc20TokenAddress).balanceOf(msg.sender) > (_streamAmount + _securityAmount), "Not enough funds in your wallet to pay for stream and security"); IERC20(_erc20TokenAddress).transferFrom(msg.sender, address(this), (_streamAmount + _securityAmount)); //approve wrapper to spend ERC20_token IERC20(_erc20TokenAddress).approve(_streamToken, (_streamAmount + _securityAmount)); //upgrading the ERC20_token ISuperToken(_streamToken).upgrade((_streamAmount + _securityAmount)); } //storing nft data on chain allNFTs[tokenId] = nftData(_startingBlockTime, 0, _projectOwner, _streamAmount, _streamRate, _streamToken, _securityAmount, msg.sender, false, _investor, _streamAmount); //add investor to the accounting nftAccounting[tokenId][msg.sender] = nftAccounting[tokenId][msg.sender] + (_streamAmount + _securityAmount); //actual minting of the nft directly in the wallet of the project _mint(_projectOwner, tokenId); //start the flow _startFlow(tokenId); oldTokenId = tokenId; tokenId = tokenId + 1; } function _startFlow(uint256 _tokenId) private returns(bool) { // calculating the endingBlock uint256 _duration = allNFTs[_tokenId].streamAmount / allNFTs[_tokenId].streamRate; uint256 _endingBlock = allNFTs[_tokenId].startingBlockTime + _duration; allNFTs[_tokenId].endingBlockTime = _endingBlock; allNFTs[_tokenId].isStopped = false; host.callAgreement(cfa, abi.encodeWithSelector(cfa.createFlow.selector, allNFTs[_tokenId].streamToken, allNFTs[_tokenId].streamReceiver, allNFTs[_tokenId].streamRate, new bytes(0)), "0x"); return true; } function getAlreadyStreamed(uint256 _tokenId) public view returns(uint256) { uint256 _actualTime = block.timestamp; uint256 _alreadyStreamedAmount = (_actualTime - allNFTs[_tokenId].startingBlockTime) * allNFTs[_tokenId].streamRate; // #1 stream is stopped beacuse out of money if(allNFTs[_tokenId].isStopped && allNFTs[_tokenId].streamAmount == 0) { return allNFTs[_tokenId].originalStreamAmount; } // #2 stream is ongoing else { return _alreadyStreamedAmount; } } function stopFlow(uint256 _tokenId) public returns(bool) { require(allNFTs[_tokenId].isStopped == false, "Stream is already stopped"); require(msg.sender == operator, "You are not allowed to stop the stream"); allNFTs[_tokenId].isStopped = true; // calculating the already streamed amount and set the rest of initial streaming amount to the new streamAmount for this nft uint256 _actualTime = block.timestamp; uint256 _alreadyStreamedAmount = (_actualTime - allNFTs[_tokenId].startingBlockTime) * allNFTs[_tokenId].streamRate; // _newStreamAmount as an uint256 value can never be negative uint256 _newStreamAmount = 0; if(_alreadyStreamedAmount <= allNFTs[_tokenId].streamAmount) { _newStreamAmount = allNFTs[_tokenId].streamAmount - _alreadyStreamedAmount; } allNFTs[_tokenId].streamAmount = _newStreamAmount; host.callAgreement(cfa, abi.encodeWithSelector(cfa.deleteFlow.selector, allNFTs[_tokenId].streamToken, address(this), allNFTs[_tokenId].streamReceiver, new bytes(0)), "0x"); return true; } function withdraw(uint256 _tokenId) public returns(bool) { require(allNFTs[_tokenId].isStopped == true, "Stream is not stopped yet"); require(msg.sender == operator, "You are not allowed to withdraw"); uint256 balance = allNFTs[_tokenId].streamAmount + allNFTs[_tokenId].securityAmount; allNFTs[_tokenId].streamAmount = 0; allNFTs[_tokenId].securityAmount = 0; ISuperToken(allNFTs[_tokenId].streamToken).transfer(msg.sender, balance); return true; } function fundNFT(uint256 _tokenId, address _streamToken, uint256 _fundAmount) public { require(allNFTs[_tokenId].streamToken == _streamToken, "You can only fund the token that is already streamed"); //get the supertoken out of the senders pocket and store the balance in the mapping require(ISuperToken(_streamToken).balanceOf(msg.sender) > _fundAmount, "Not enough funds in your wallet"); ISuperToken(_streamToken).transferFrom(msg.sender, address(this), _fundAmount); //adding the investor to the nft allNFTs[_tokenId].investors.push(msg.sender); //adding the fundingamount to the nft allNFTs[_tokenId].streamAmount = allNFTs[_tokenId].streamAmount + _fundAmount; allNFTs[_tokenId].originalStreamAmount = allNFTs[_tokenId].originalStreamAmount + _fundAmount; //add investor to the accounting nftAccounting[_tokenId][msg.sender] = nftAccounting[_tokenId][msg.sender] + _fundAmount; //calculating //update stream //host.callAgreement(cfa, abi.encodeWithSelector(cfa.updateFlow.selector, allNFTs[_tokenId].streamToken, allNFTs[_tokenId].streamReceiver, allNFTs[_tokenId].streamRate, new bytes(0)), "0x"); } //now I will insert a nice little hook in the _transfer, including the RedirectAll function I need function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override { // should not be called if the nft is minted if(from != address(0)) { (,int96 outFlowRate,,) = cfa.getFlow(ISuperToken(allNFTs[_tokenId].streamToken), address(this), allNFTs[_tokenId].streamReceiver); if(outFlowRate > 0) { stopFlow(_tokenId); allNFTs[_tokenId].streamReceiver = to; allNFTs[_tokenId].isStopped = false; host.callAgreement(cfa, abi.encodeWithSelector(cfa.createFlow.selector, allNFTs[_tokenId].streamToken, allNFTs[_tokenId].streamReceiver, allNFTs[_tokenId].streamRate, new bytes(0)), "0x"); } else { allNFTs[_tokenId].streamReceiver = to; allNFTs[_tokenId].isStopped = false; host.callAgreement(cfa, abi.encodeWithSelector(cfa.createFlow.selector, allNFTs[_tokenId].streamToken, allNFTs[_tokenId].streamReceiver, allNFTs[_tokenId].streamRate, new bytes(0)), "0x"); } } } }
calculating the already streamed amount and set the rest of initial streaming amount to the new streamAmount for this nft _newStreamAmount as an uint256 value can never be negative
function stopFlow(uint256 _tokenId) public returns(bool) { require(allNFTs[_tokenId].isStopped == false, "Stream is already stopped"); require(msg.sender == operator, "You are not allowed to stop the stream"); allNFTs[_tokenId].isStopped = true; uint256 _actualTime = block.timestamp; uint256 _alreadyStreamedAmount = (_actualTime - allNFTs[_tokenId].startingBlockTime) * allNFTs[_tokenId].streamRate; uint256 _newStreamAmount = 0; if(_alreadyStreamedAmount <= allNFTs[_tokenId].streamAmount) { _newStreamAmount = allNFTs[_tokenId].streamAmount - _alreadyStreamedAmount; } allNFTs[_tokenId].streamAmount = _newStreamAmount; host.callAgreement(cfa, abi.encodeWithSelector(cfa.deleteFlow.selector, allNFTs[_tokenId].streamToken, address(this), allNFTs[_tokenId].streamReceiver, new bytes(0)), "0x"); return true; }
12,720,188
./partial_match/1/0x03BB51F2299d5301a680efb1a085fBBF7701877E/sources/GREENTEACN.sol
exclude from paying fees or having max transaction amount
constructor() ERC20(unicode"China Green Tea", unicode"绿茶") { marketingWallet = address(0x1a7De267bbeA17cD92587EAc388aA36c043b4647); devWallet = address(msg.sender); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1000000000 * 1e18; maxTransactionAmount = totalSupply * 35 / 1000; maxWallet = totalSupply * 35 / 1000; swapTokensAtAmount = totalSupply * 2 / 100000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; distribution = marketingWallet; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(devWallet, true); excludeFromFees(marketingWallet, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(devWallet, true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
16,113,441
./full_match/56/0x6f287eCBBbCE7042187d388db663b036fc67b5B0/sources/project_/contracts/StrategyCommonChefLP.sol
puts the funds to work
function deposit() public whenNotPaused { uint256 wantBal = IERC20(want).balanceOf(address(this)); if (wantBal > 0) { IRewardPool(rewardPool).stake(wantBal); } }
3,234,951
pragma solidity ^0.4.19; // copyright contact@emontalliance.com contract BasicAccessControl { address public owner; // address[] public moderators; uint16 public totalModerators = 0; mapping (address => bool) public moderators; bool public isMaintaining = false; function BasicAccessControl() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyModerators() { require(msg.sender == owner || moderators[msg.sender] == true); _; } modifier isActive { require(!isMaintaining); _; } function ChangeOwner(address _newOwner) onlyOwner public { if (_newOwner != address(0)) { owner = _newOwner; } } function AddModerator(address _newModerator) onlyOwner public { if (moderators[_newModerator] == false) { moderators[_newModerator] = true; totalModerators += 1; } } function RemoveModerator(address _oldModerator) onlyOwner public { if (moderators[_oldModerator] == true) { moderators[_oldModerator] = false; totalModerators -= 1; } } function UpdateMaintaining(bool _isMaintaining) onlyOwner public { isMaintaining = _isMaintaining; } } 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); } contract EmontFrenzy is BasicAccessControl { uint constant public HIGH = 20; uint constant public BASE_POS = 510; uint constant public ONE_EMONT = 10 ** 8; struct Fish { address player; uint weight; bool active; // location != 0 uint blockNumber; // block number } // private uint private seed; // address address public tokenContract; // variable uint public addFee = 0.01 ether; uint public addWeight = 5 * 10 ** 8; // emont uint public addDrop = 5 * 10 ** 8; // emont uint public moveCharge = 5; // percentage uint public cashOutRate = 100; // to EMONT rate uint public cashInRate = 50; // from EMONT to fish weight uint public width = 50; uint public minJump = 2 * 2; uint public maxPos = HIGH * width; // valid pos (0 -> maxPos - 1) uint public minCashout = 25 * 10 ** 8; uint public minEatable = 1 * 10 ** 8; uint public minWeightDeduct = 4 * 10 ** 8; // 0.2 EMONT uint public basePunish = 40000; // per block uint public oceanBonus = 125000; // per block uint public minWeightPunish = 1 * 10 ** 8; uint public maxWeightBonus = 25 * 10 ** 8; mapping(uint => Fish) fishMap; mapping(uint => uint) ocean; // pos => fish id mapping(uint => uint) bonus; // pos => emont amount mapping(address => uint) players; mapping(uint => uint) maxJumps; // weight in EMONT => square length uint public totalFish = 0; // event event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event EventCashout(address indexed player, uint fishId, uint weight); event EventBonus(uint pos, uint value); event EventMove(address indexed player, uint fishId, uint fromPos, uint toPos, uint weight); event EventEat(address indexed player, address indexed defender, uint playerFishId, uint defenderFishId, uint fromPos, uint toPos, uint playerWeight); event EventFight(address indexed player, address indexed defender, uint playerFishId, uint defenderFishId, uint fromPos, uint toPos, uint playerWeight); event EventSuicide(address indexed player, address indexed defender, uint playerFishId, uint defenderFishId, uint fromPos, uint toPos, uint defenderWeight); // modifier modifier requireTokenContract { require(tokenContract != address(0)); _; } function EmontFrenzy(address _tokenContract) public { tokenContract = _tokenContract; seed = getRandom(0); } function setRate(uint _moveCharge, uint _cashOutRate, uint _cashInRate) onlyModerators external { moveCharge = _moveCharge; cashOutRate = _cashOutRate; cashInRate = _cashInRate; } function setMaxConfig(uint _minWeightPunish, uint _maxWeightBonus) onlyModerators external { minWeightPunish = _minWeightPunish; maxWeightBonus = _maxWeightBonus; } function setConfig(uint _addFee, uint _addWeight, uint _addDrop, uint _width) onlyModerators external { addFee = _addFee; addWeight = _addWeight; addDrop = _addDrop; width = _width; maxPos = HIGH * width; } function setExtraConfig(uint _minCashout, uint _minEatable, uint _minWeightDeduct, uint _basePunish, uint _oceanBonus) onlyModerators external { minCashout = _minCashout; minEatable = _minEatable; minWeightDeduct = _minWeightDeduct; basePunish = _basePunish; oceanBonus = _oceanBonus; } // weight in emont, x*x function updateMaxJump(uint _weight, uint _squareLength) onlyModerators external { maxJumps[_weight] = _squareLength; } function setDefaultMaxJump() onlyModerators external { maxJumps[0] = 50 * 50; maxJumps[1] = 30 * 30; maxJumps[2] = 20 * 20; maxJumps[3] = 15 * 15; maxJumps[4] = 12 * 12; maxJumps[5] = 9 * 9; maxJumps[6] = 7 * 7; maxJumps[7] = 7 * 7; maxJumps[8] = 6 * 6; maxJumps[9] = 6 * 6; maxJumps[10] = 6 * 6; maxJumps[11] = 5 * 5; maxJumps[12] = 5 * 5; maxJumps[13] = 5 * 5; maxJumps[14] = 5 * 5; maxJumps[15] = 4 * 4; maxJumps[16] = 4 * 4; maxJumps[17] = 4 * 4; maxJumps[18] = 4 * 4; maxJumps[19] = 4 * 4; maxJumps[20] = 3 * 3; maxJumps[21] = 3 * 3; maxJumps[22] = 3 * 3; maxJumps[23] = 3 * 3; maxJumps[24] = 3 * 3; maxJumps[25] = 3 * 3; } function updateMinJump(uint _minJump) onlyModerators external { minJump = _minJump; } // moderators function withdrawEther(address _sendTo, uint _amount) onlyModerators external { // no user money is kept in this contract, only trasaction fee if (_amount > address(this).balance) { revert(); } _sendTo.transfer(_amount); } function withdrawToken(address _sendTo, uint _amount) onlyModerators requireTokenContract external { ERC20Interface token = ERC20Interface(tokenContract); if (_amount > token.balanceOf(address(this))) { revert(); } token.transfer(_sendTo, _amount); } function addBonus(uint _pos, uint _amount) onlyModerators external { bonus[_pos] += _amount; EventBonus(_pos, _amount); } function refundFish(address _player, uint _weight) onlyModerators external { // max: one fish per address if (fishMap[players[_player]].weight > 0) revert(); totalFish += 1; Fish storage fish = fishMap[totalFish]; fish.player = _player; fish.weight = _weight; fish.active = false; fish.blockNumber = block.number; players[_player] = totalFish; seed = getRandom(seed); Transfer(address(0), _player, totalFish); } function cleanOcean(uint _pos1, uint _pos2, uint _pos3, uint _pos4, uint _pos5, uint _pos6, uint _pos7, uint _pos8, uint _pos9, uint _pos10) onlyModerators external { if (_pos1 > 0) { bonus[_pos1] = 0; EventBonus(_pos1, 0); } if (_pos2 > 0) { bonus[_pos2] = 0; EventBonus(_pos2, 0); } if (_pos3 > 0) { bonus[_pos3] = 0; EventBonus(_pos3, 0); } if (_pos4 > 0) { bonus[_pos4] = 0; EventBonus(_pos4, 0); } if (_pos5 > 0) { bonus[_pos5] = 0; EventBonus(_pos5, 0); } if (_pos6 > 0) { bonus[_pos6] = 0; EventBonus(_pos6, 0); } if (_pos7 > 0) { bonus[_pos7] = 0; EventBonus(_pos7, 0); } if (_pos8 > 0) { bonus[_pos8] = 0; EventBonus(_pos8, 0); } if (_pos9 > 0) { bonus[_pos9] = 0; EventBonus(_pos9, 0); } if (_pos10 > 0) { bonus[_pos10] = 0; EventBonus(_pos10, 0); } } // for payment contract to call function AddFishByToken(address _player, uint _tokens) onlyModerators external { uint weight = _tokens * cashInRate / 100; if (weight != addWeight) revert(); // max: one fish per address if (fishMap[players[_player]].weight > 0) revert(); totalFish += 1; Fish storage fish = fishMap[totalFish]; fish.player = _player; fish.weight = addWeight; fish.active = false; fish.blockNumber = block.number; players[_player] = totalFish; // airdrop if (addDrop > 0) { seed = getRandom(seed); uint temp = seed % (maxPos - 1); if (temp == BASE_POS) temp += 1; bonus[temp] += addDrop; EventBonus(temp, bonus[temp]); } else { seed = getRandom(seed); } Transfer(address(0), _player, totalFish); } // public functions function getRandom(uint _seed) constant public returns(uint) { return uint(keccak256(block.timestamp, block.difficulty)) ^ _seed; } function AddFish() isActive payable external { if (msg.value != addFee) revert(); // max: one fish per address if (fishMap[players[msg.sender]].weight > 0) revert(); totalFish += 1; Fish storage fish = fishMap[totalFish]; fish.player = msg.sender; fish.weight = addWeight; fish.active = false; fish.blockNumber = block.number; players[msg.sender] = totalFish; // airdrop if (addDrop > 0) { seed = getRandom(seed); uint temp = seed % (maxPos - 1); if (temp == BASE_POS) temp += 1; bonus[temp] += addDrop; EventBonus(temp, bonus[temp]); } else { seed = getRandom(seed); } Transfer(address(0), msg.sender, totalFish); } function DeductABS(uint _a, uint _b) pure public returns(uint) { if (_a > _b) return (_a - _b); return (_b - _a); } function SafeDeduct(uint _a, uint _b) pure public returns(uint) { if (_a > _b) return (_a - _b); return 0; } function MoveFromBase(uint _toPos) isActive external { // from = 0 if (_toPos >= maxPos || _toPos == 0) revert(); uint fishId = players[msg.sender]; Fish storage fish = fishMap[fishId]; if (fish.weight == 0) revert(); // not from base if (fish.active) revert(); // deduct weight if (fish.weight > minWeightPunish) { uint tempX = SafeDeduct(block.number, fish.blockNumber); tempX = SafeDeduct(fish.weight, tempX * basePunish); if (tempX < minWeightPunish) { fish.weight = minWeightPunish; } else { fish.weight = tempX; } } // check valid move tempX = DeductABS(BASE_POS / HIGH, _toPos / HIGH); uint tempY = DeductABS(BASE_POS % HIGH, _toPos % HIGH); uint squareLength = maxJumps[fish.weight / ONE_EMONT]; if (squareLength == 0) squareLength = minJump; if (tempX * tempX + tempY * tempY > squareLength) revert(); // can not attack if (ocean[_toPos] > 0) revert(); // check target bonus if (bonus[_toPos] > 0) { fish.weight += bonus[_toPos]; bonus[_toPos] = 0; } fish.active = true; fish.blockNumber = block.number; ocean[_toPos] = fishId; EventMove(msg.sender, fishId, BASE_POS, _toPos, fish.weight); } function MoveToBase(uint _fromPos) isActive external { uint fishId = players[msg.sender]; Fish storage fish = fishMap[fishId]; if (fish.weight == 0) revert(); if (!fish.active || ocean[_fromPos] != fishId) revert(); // check valid move uint tempX = DeductABS(_fromPos / HIGH, BASE_POS / HIGH); uint tempY = DeductABS(_fromPos % HIGH, BASE_POS % HIGH); uint squareLength = maxJumps[fish.weight / ONE_EMONT]; if (squareLength == 0) squareLength = minJump; if (tempX * tempX + tempY * tempY > squareLength) revert(); if (fish.weight >= minWeightDeduct) { tempX = (moveCharge * fish.weight) / 100; bonus[_fromPos] += tempX; fish.weight -= tempX; } // add bonus if (fish.weight < maxWeightBonus) { uint temp = SafeDeduct(block.number, fish.blockNumber) * oceanBonus; if (fish.weight + temp > maxWeightBonus) { fish.weight = maxWeightBonus; } else { fish.weight += temp; } } ocean[_fromPos] = 0; fish.active = false; fish.blockNumber = block.number; EventMove(msg.sender, fishId, _fromPos, BASE_POS, fish.weight); return; } function MoveFish(uint _fromPos, uint _toPos) isActive external { // check valid _x, _y if (_toPos >= maxPos && _fromPos != _toPos) revert(); if (_fromPos == BASE_POS || _toPos == BASE_POS) revert(); uint fishId = players[msg.sender]; Fish storage fish = fishMap[fishId]; if (fish.weight == 0) revert(); if (!fish.active || ocean[_fromPos] != fishId) revert(); // check valid move uint tempX = DeductABS(_fromPos / HIGH, _toPos / HIGH); uint tempY = DeductABS(_fromPos % HIGH, _toPos % HIGH); uint squareLength = maxJumps[fish.weight / ONE_EMONT]; if (squareLength == 0) squareLength = minJump; if (tempX * tempX + tempY * tempY > squareLength) revert(); // move ocean[_fromPos] = 0; if (fish.weight >= minWeightDeduct) { tempX = (moveCharge * fish.weight) / 100; bonus[_fromPos] += tempX; fish.weight -= tempX; } tempX = ocean[_toPos]; // target fish id // no fish at that location if (tempX == 0) { if (bonus[_toPos] > 0) { fish.weight += bonus[_toPos]; bonus[_toPos] = 0; } // update location EventMove(msg.sender, fishId, _fromPos, _toPos, fish.weight); ocean[_toPos] = fishId; } else { Fish storage targetFish = fishMap[tempX]; if (targetFish.weight + minEatable <= fish.weight) { // eat the target fish fish.weight += targetFish.weight; targetFish.weight = 0; // update location ocean[_toPos] = fishId; EventEat(msg.sender, targetFish.player, fishId, tempX, _fromPos, _toPos, fish.weight); Transfer(targetFish.player, address(0), tempX); } else if (targetFish.weight <= fish.weight) { // fight and win // bonus to others seed = getRandom(seed); tempY = seed % (maxPos - 1); if (tempY == BASE_POS) tempY += 1; bonus[tempY] += targetFish.weight * 2; EventBonus(tempY, bonus[tempY]); // fight fish.weight -= targetFish.weight; targetFish.weight = 0; // update location if (fish.weight > 0) { ocean[_toPos] = fishId; } else { ocean[_toPos] = 0; Transfer(msg.sender, address(0), fishId); } EventFight(msg.sender, targetFish.player, fishId, tempX, _fromPos, _toPos, fish.weight); Transfer(targetFish.player, address(0), tempX); } else { // bonus to others seed = getRandom(seed); tempY = seed % (maxPos - 1); if (tempY == BASE_POS) tempY += 1; bonus[tempY] += fish.weight * 2; EventBonus(tempY, bonus[tempY]); // suicide targetFish.weight -= fish.weight; fish.weight = 0; EventSuicide(msg.sender, targetFish.player, fishId, tempX, _fromPos, _toPos, targetFish.weight); Transfer(msg.sender, address(0), fishId); } } } function CashOut() isActive external { uint fishId = players[msg.sender]; Fish storage fish = fishMap[fishId]; // if fish at base, need to deduct if (!fish.active) { // deduct weight if (fish.weight > minWeightPunish) { uint tempX = SafeDeduct(block.number, fish.blockNumber); tempX = SafeDeduct(fish.weight, tempX * basePunish); if (tempX < minWeightPunish) { fish.weight = minWeightPunish; } else { fish.weight = tempX; } } fish.blockNumber = block.number; } if (fish.weight < minCashout) revert(); if (fish.weight < addWeight) revert(); uint _amount = fish.weight - addWeight; fish.weight = addWeight; ERC20Interface token = ERC20Interface(tokenContract); if (_amount > token.balanceOf(address(this))) { revert(); } token.transfer(msg.sender, (_amount * cashOutRate) / 100); EventCashout(msg.sender, fishId, fish.weight); } // public get function getFish(uint32 _fishId) constant public returns(address player, uint weight, bool active, uint blockNumber) { Fish storage fish = fishMap[_fishId]; return (fish.player, fish.weight, fish.active, fish.blockNumber); } function getFishByAddress(address _player) constant public returns(uint fishId, address player, uint weight, bool active, uint blockNumber) { fishId = players[_player]; Fish storage fish = fishMap[fishId]; player = fish.player; weight =fish.weight; active = fish.active; blockNumber = fish.blockNumber; } function getFishIdByAddress(address _player) constant public returns(uint fishId) { return players[_player]; } function getFishIdByPos(uint _pos) constant public returns(uint fishId) { return ocean[_pos]; } function getFishByPos(uint _pos) constant public returns(uint fishId, address player, uint weight, uint blockNumber) { fishId = ocean[_pos]; Fish storage fish = fishMap[fishId]; return (fishId, fish.player, fish.weight, fish.blockNumber); } // cell has valid fish or bonus function getActiveFish(uint _fromPos, uint _toPos) constant public returns(uint pos, uint fishId, address player, uint weight, uint blockNumber) { for (uint index = _fromPos; index <= _toPos; index+=1) { if (ocean[index] > 0) { fishId = ocean[index]; Fish storage fish = fishMap[fishId]; return (index, fishId, fish.player, fish.weight, fish.blockNumber); } } } function getAllBonus(uint _fromPos, uint _toPos) constant public returns(uint pos, uint amount) { for (uint index = _fromPos; index <= _toPos; index+=1) { if (bonus[index] > 0) { return (index, bonus[index]); } } } function getStats() constant public returns(uint countFish, uint countBonus) { countFish = 0; countBonus = 0; for (uint index = 0; index < width * HIGH; index++) { if (ocean[index] > 0) { countFish += 1; } if (bonus[index] > 0) { countBonus += 1; } } } function getFishAtBase(uint _fishId) constant public returns(uint fishId, address player, uint weight, uint blockNumber) { for (uint id = _fishId; id <= totalFish; id++) { Fish storage fish = fishMap[id]; if (fish.weight > 0 && !fish.active) { return (id, fish.player, fish.weight, fish.blockNumber); } } return (0, address(0), 0, 0); } function countFishAtBase() constant public returns(uint count) { count = 0; for (uint id = 0; id <= totalFish; id++) { Fish storage fish = fishMap[id]; if (fish.weight > 0 && !fish.active) { count += 1; } } } function getMaxJump(uint _weight) constant public returns(uint) { return maxJumps[_weight]; } // some meta data string public constant name = "EmontFrenzy"; string public constant symbol = "EMONF"; function totalSupply() public view returns (uint256) { return totalFish; } function balanceOf(address _owner) public view returns (uint256 _balance) { if (fishMap[players[_owner]].weight > 0) return 1; return 0; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { Fish storage fish = fishMap[_tokenId]; if (fish.weight > 0) return fish.player; return address(0); } function transfer(address _to, uint256 _tokenId) public{ require(_to != address(0)); uint fishId = players[msg.sender]; Fish storage fish = fishMap[fishId]; if (fishId == 0 || fish.weight == 0 || fishId != _tokenId) revert(); if (balanceOf(_to) > 0) revert(); fish.player = _to; players[msg.sender] = 0; players[_to] = fishId; Transfer(msg.sender, _to, _tokenId); } }
max: one fish per address airdrop
function AddFish() isActive payable external { if (msg.value != addFee) revert(); if (fishMap[players[msg.sender]].weight > 0) revert(); totalFish += 1; Fish storage fish = fishMap[totalFish]; fish.player = msg.sender; fish.weight = addWeight; fish.active = false; fish.blockNumber = block.number; players[msg.sender] = totalFish; if (addDrop > 0) { seed = getRandom(seed); uint temp = seed % (maxPos - 1); if (temp == BASE_POS) temp += 1; bonus[temp] += addDrop; EventBonus(temp, bonus[temp]); seed = getRandom(seed); } Transfer(address(0), msg.sender, totalFish); }
2,167,424
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; /// @title zkSync main contract /// @author Matter Labs contract ZkSync is UpgradeableMaster, Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /// @notice Data needed to process onchain operation from block public data. /// @notice Onchain operations is operations that need some processing on L1: Deposits, Withdrawals, ChangePubKey. /// @param ethWitness Some external data that can be needed for operation processing /// @param publicDataOffset Byte offset in public data for onchain operation struct OnchainOperationData { bytes ethWitness; uint32 publicDataOffset; } /// @notice Data needed to commit new block struct CommitBlockInfo { bytes32 newStateHash; bytes publicData; uint256 timestamp; OnchainOperationData[] onchainOperations; uint32 blockNumber; uint32 feeAccount; } /// @notice Data needed to execute committed and verified block /// @param commitmentsInSlot verified commitments in one slot /// @param commitmentIdx index such that commitmentsInSlot[commitmentIdx] is current block commitment struct ExecuteBlockInfo { StoredBlockInfo storedBlock; bytes[] pendingOnchainOpsPubdata; } /// @notice Recursive proof input data (individual commitments are constructed onchain) struct ProofInput { uint256[] recursiveInput; uint256[] proof; uint256[] commitments; uint8[] vkIndexes; uint256[16] subproofsLimbs; } // Upgrade functional /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external pure override returns (uint256) { return UPGRADE_NOTICE_PERIOD; } /// @notice Notification that upgrade notice period started /// @dev Can be external because Proxy contract intercepts illegal calls of this function // solhint-disable-next-line no-empty-blocks function upgradeNoticePeriodStarted() external override {} /// @notice Notification that upgrade preparation status is activated /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradePreparationStarted() external override { upgradePreparationActive = true; upgradePreparationActivationTime = block.timestamp; } /// @notice Notification that upgrade canceled /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeCanceled() external override { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Notification that upgrade finishes /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeFinishes() external override { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external view override returns (bool) { return !exodusMode; } /// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// @dev _governanceAddress The address of Governance contract /// @dev _verifierAddress The address of Verifier contract /// @dev _genesisStateHash Genesis blocks (first block) state tree root hash function initialize(bytes calldata initializationParameters) external { initializeReentrancyGuard(); (address _governanceAddress, address _verifierAddress, bytes32 _genesisStateHash) = abi.decode(initializationParameters, (address, address, bytes32)); verifier = Verifier(_verifierAddress); governance = Governance(_governanceAddress); // We need initial state hash because it is used in the commitment of the next block StoredBlockInfo memory storedBlockZero = StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0)); storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero); } /// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external nonReentrant {} /// @notice Sends tokens /// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount /// @dev This function is used to allow tokens to spend zkSync contract balance up to amount that is requested /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @param _maxAmount Maximum possible amount of tokens to transfer to this account function _transferERC20( IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount ) external returns (uint128 withdrawnAmount) { require(msg.sender == address(this), "5"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed) uint256 balanceBefore = _token.balanceOf(address(this)); require(Utils.sendERC20(_token, _to, _amount), "6"); // wtg11 - ERC20 transfer fails uint256 balanceAfter = _token.balanceOf(address(this)); uint256 balanceDiff = balanceBefore.sub(balanceAfter); require(balanceDiff <= _maxAmount, "7"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount return SafeCast.toUint128(balanceDiff); } /// @notice Accrues users balances from deposit priority requests in Exodus mode /// @dev WARNING: Only for Exodus mode /// @dev Canceling may take several separate transactions to be completed /// @param _n number of requests to process function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external nonReentrant { require(exodusMode, "8"); // exodus mode not active uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n); require(toProcess == _depositsPubdata.length, "A"); require(toProcess > 0, "9"); // no deposits to process uint64 currentDepositIdx = 0; for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) { if (priorityRequests[id].opType == Operations.OpType.Deposit) { bytes memory depositPubdata = _depositsPubdata[currentDepositIdx]; require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a"); ++currentDepositIdx; Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata); bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId); pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount; } delete priorityRequests[id]; } firstPriorityRequestId += toProcess; totalOpenPriorityRequests -= toProcess; } /// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit /// @param _zkSyncAddress The receiver Layer 2 address function depositETH(address _zkSyncAddress) external payable { requireActive(); registerDeposit(0, SafeCast.toUint128(msg.value), _zkSyncAddress); } /// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit /// @param _token Token address /// @param _amount Token amount /// @param _zkSyncAddress Receiver Layer 2 address function depositERC20( IERC20 _token, uint104 _amount, address _zkSyncAddress ) external nonReentrant { requireActive(); // Get token id by its address uint16 tokenId = governance.validateTokenAddress(address(_token)); require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused uint256 balanceBefore = _token.balanceOf(address(this)); require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "c"); // token transfer failed deposit uint256 balanceAfter = _token.balanceOf(address(this)); uint128 depositAmount = SafeCast.toUint128(balanceAfter.sub(balanceBefore)); require(depositAmount <= MAX_DEPOSIT_AMOUNT, "C"); registerDeposit(tokenId, depositAmount, _zkSyncAddress); } /// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract /// @param _address Address of the tokens owner /// @param _token Address of token, zero address is used for ETH function getPendingBalance(address _address, address _token) public view returns (uint128) { uint16 tokenId = 0; if (_token != address(0)) { tokenId = governance.validateTokenAddress(_token); } return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw; } /// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract /// @notice DEPRECATED: to be removed in future, use getPendingBalance instead /// @param _address Address of the tokens owner /// @param _tokenId token id, 0 is used for ETH function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) { return pendingBalances[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw; } /// @notice Withdraws tokens from zkSync contract to the owner /// @param _owner Address of the tokens owner /// @param _token Address of tokens, zero address is used for ETH /// @param _amount Amount to withdraw to request. /// NOTE: We will call ERC20.transfer(.., _amount), but if according to internal logic of ERC20 token zkSync contract /// balance will be decreased by value more then _amount we will try to subtract this value from user pending balance function withdrawPendingBalance( address payable _owner, address _token, uint128 _amount ) external nonReentrant { if (_token == address(0)) { registerWithdrawal(0, _amount, _owner); (bool success, ) = _owner.call{value: _amount}(""); require(success, "d"); // ETH withdraw failed } else { uint16 tokenId = governance.validateTokenAddress(_token); bytes22 packedBalanceKey = packAddressAndTokenId(_owner, tokenId); uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw; // We will allow withdrawals of `value` such that: // `value` <= user pending balance // `value` can be bigger then `_amount` requested if token takes fee from sender in addition to `_amount` requested uint128 withdrawnAmount = this._transferERC20(IERC20(_token), _owner, _amount, balance); registerWithdrawal(tokenId, withdrawnAmount, _owner); } } /// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender /// @notice DEPRECATED: use withdrawPendingBalance instead /// @param _token Token address /// @param _amount amount to withdraw function withdrawERC20(IERC20 _token, uint128 _amount) external nonReentrant { uint16 tokenId = governance.validateTokenAddress(address(_token)); bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw; uint128 withdrawnAmount = this._transferERC20(_token, msg.sender, _amount, balance); registerWithdrawal(tokenId, withdrawnAmount, msg.sender); } /// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender /// @notice DEPRECATED: use withdrawPendingBalance instead /// @param _amount Ether amount to withdraw function withdrawETH(uint128 _amount) external nonReentrant { registerWithdrawal(0, _amount, msg.sender); (bool success, ) = msg.sender.call{value: _amount}(""); require(success, "D"); // ETH withdraw failed } /// @notice Register full exit request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _token Token address, 0 address for ether function requestFullExit(uint32 _accountId, address _token) public nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "e"); uint16 tokenId; if (_token == address(0)) { tokenId = 0; } else { tokenId = governance.validateTokenAddress(_token); } // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId: _accountId, owner: msg.sender, tokenId: tokenId, amount: 0 // unknown at this point }); bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.FullExit, pubData); // User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value // In this case operator should just overwrite this slot during confirming withdrawal bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE; } /// @notice Register full exit request - pack pubdata, add priority request /// @notice DEPRECATED: use requestFullExit instead. /// @param _accountId Numerical id of the account /// @param _token Token address, 0 address for ether function fullExit(uint32 _accountId, address _token) external { requestFullExit(_accountId, _token); } /// @dev Process one block commit using previous block StoredBlockInfo, /// @dev returns new block StoredBlockInfo /// @dev NOTE: Does not change storage (except events, so we can't mark it view) function commitOneBlock(StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlock) internal view returns (StoredBlockInfo memory storedNewBlock) { require(_newBlock.blockNumber == _previousBlock.blockNumber + 1, "f"); // only commit next block // Check timestamp of the new block { require(_newBlock.timestamp >= _previousBlock.timestamp, "g"); // Block should be after previous block bool timestampNotTooSmall = block.timestamp.sub(COMMIT_TIMESTAMP_NOT_OLDER) <= _newBlock.timestamp; bool timestampNotTooBig = _newBlock.timestamp <= block.timestamp.add(COMMIT_TIMESTAMP_APPROXIMATION_DELTA); require(timestampNotTooSmall && timestampNotTooBig, "h"); // New block timestamp is not valid } // Check onchain operations (bytes32 pendingOnchainOpsHash, uint64 priorityReqCommitted, bytes memory onchainOpsOffsetCommitment) = collectOnchainOps(_newBlock); // Create block commitment for verification proof bytes32 commitment = createBlockCommitment(_previousBlock, _newBlock, onchainOpsOffsetCommitment); return StoredBlockInfo( _newBlock.blockNumber, priorityReqCommitted, pendingOnchainOpsHash, _newBlock.timestamp, _newBlock.newStateHash, commitment ); } /// @notice Commit block /// @notice 1. Checks onchain operations, timestamp. /// @notice 2. Store block commitments function commitBlocks(StoredBlockInfo memory _lastCommittedBlockData, CommitBlockInfo[] memory _newBlocksData) external nonReentrant { requireActive(); governance.requireActiveValidator(msg.sender); // Check that we commit blocks after last committed block require(storedBlockHashes[totalBlocksCommitted] == hashStoredBlockInfo(_lastCommittedBlockData), "i"); // incorrect previous block data for (uint32 i = 0; i < _newBlocksData.length; ++i) { _lastCommittedBlockData = commitOneBlock(_lastCommittedBlockData, _newBlocksData[i]); totalCommittedPriorityRequests += _lastCommittedBlockData.priorityOperations; storedBlockHashes[_lastCommittedBlockData.blockNumber] = hashStoredBlockInfo(_lastCommittedBlockData); emit BlockCommit(_lastCommittedBlockData.blockNumber); } totalBlocksCommitted += uint32(_newBlocksData.length); require(totalCommittedPriorityRequests <= totalOpenPriorityRequests, "j"); } /// @dev 1. Try to send token to _recipients /// @dev 2. On failure: Increment _recipients balance to withdraw. function withdrawOrStore( uint16 _tokenId, address _recipient, uint128 _amount ) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_recipient, _tokenId); bool sent = false; if (_tokenId == 0) { address payable toPayable = address(uint160(_recipient)); sent = sendETHNoRevert(toPayable, _amount); } else { address tokenAddr = governance.tokenAddresses(_tokenId); // We use `_transferERC20` here to check that `ERC20` token indeed transferred `_amount` // and fail if token subtracted from zkSync balance more then `_amount` that was requested. // This can happen if token subtracts fee from sender while transferring `_amount` that was requested to transfer. try this._transferERC20{gas: WITHDRAWAL_GAS_LIMIT}(IERC20(tokenAddr), _recipient, _amount, _amount) { sent = true; } catch { sent = false; } } if (sent) { emit Withdrawal(_tokenId, _amount); } else { increaseBalanceToWithdraw(packedBalanceKey, _amount); } } /// @dev Executes one block /// @dev 1. Processes all pending operations (Send Exits, Complete priority requests) /// @dev 2. Finalizes block on Ethereum /// @dev _executedBlockIdx is index in the array of the blocks that we want to execute together function executeOneBlock(ExecuteBlockInfo memory _blockExecuteData, uint32 _executedBlockIdx) internal { // Ensure block was committed require( hashStoredBlockInfo(_blockExecuteData.storedBlock) == storedBlockHashes[_blockExecuteData.storedBlock.blockNumber], "exe10" // executing block should be committed ); require(_blockExecuteData.storedBlock.blockNumber == totalBlocksExecuted + _executedBlockIdx + 1, "k"); // Execute blocks in order bytes32 pendingOnchainOpsHash = EMPTY_STRING_KECCAK; for (uint32 i = 0; i < _blockExecuteData.pendingOnchainOpsPubdata.length; ++i) { bytes memory pubData = _blockExecuteData.pendingOnchainOpsPubdata[i]; Operations.OpType opType = Operations.OpType(uint8(pubData[0])); if (opType == Operations.OpType.PartialExit) { Operations.PartialExit memory op = Operations.readPartialExitPubdata(pubData); withdrawOrStore(op.tokenId, op.owner, op.amount); } else if (opType == Operations.OpType.ForcedExit) { Operations.ForcedExit memory op = Operations.readForcedExitPubdata(pubData); withdrawOrStore(op.tokenId, op.target, op.amount); } else if (opType == Operations.OpType.FullExit) { Operations.FullExit memory op = Operations.readFullExitPubdata(pubData); withdrawOrStore(op.tokenId, op.owner, op.amount); } else { revert("l"); // unsupported op in block execution } pendingOnchainOpsHash = Utils.concatHash(pendingOnchainOpsHash, pubData); } require(pendingOnchainOpsHash == _blockExecuteData.storedBlock.pendingOnchainOperationsHash, "m"); // incorrect onchain ops executed } /// @notice Execute blocks, completing priority operations and processing withdrawals. /// @notice 1. Processes all pending operations (Send Exits, Complete priority requests) /// @notice 2. Finalizes block on Ethereum function executeBlocks(ExecuteBlockInfo[] memory _blocksData) external nonReentrant { requireActive(); governance.requireActiveValidator(msg.sender); uint64 priorityRequestsExecuted = 0; uint32 nBlocks = uint32(_blocksData.length); for (uint32 i = 0; i < nBlocks; ++i) { executeOneBlock(_blocksData[i], i); priorityRequestsExecuted += _blocksData[i].storedBlock.priorityOperations; emit BlockVerification(_blocksData[i].storedBlock.blockNumber); } firstPriorityRequestId += priorityRequestsExecuted; totalCommittedPriorityRequests -= priorityRequestsExecuted; totalOpenPriorityRequests -= priorityRequestsExecuted; totalBlocksExecuted += nBlocks; require(totalBlocksExecuted <= totalBlocksProven, "n"); // Can't execute blocks more then committed and proven currently. } /// @notice Blocks commitment verification. /// @notice Only verifies block commitments without any other processing function proveBlocks(StoredBlockInfo[] memory _committedBlocks, ProofInput memory _proof) external nonReentrant { uint32 currentTotalBlocksProven = totalBlocksProven; for (uint256 i = 0; i < _committedBlocks.length; ++i) { require(hashStoredBlockInfo(_committedBlocks[i]) == storedBlockHashes[currentTotalBlocksProven + 1], "o1"); ++currentTotalBlocksProven; require(_proof.commitments[i] & INPUT_MASK == uint256(_committedBlocks[i].commitment) & INPUT_MASK, "o"); // incorrect block commitment in proof } bool success = verifier.verifyAggregatedBlockProof( _proof.recursiveInput, _proof.proof, _proof.vkIndexes, _proof.commitments, _proof.subproofsLimbs ); require(success, "p"); // Aggregated proof verification fail require(currentTotalBlocksProven <= totalBlocksCommitted, "q"); totalBlocksProven = currentTotalBlocksProven; } /// @notice Reverts unverified blocks function revertBlocks(StoredBlockInfo[] memory _blocksToRevert) external nonReentrant { governance.requireActiveValidator(msg.sender); uint32 blocksCommitted = totalBlocksCommitted; uint32 blocksToRevert = Utils.minU32(uint32(_blocksToRevert.length), blocksCommitted - totalBlocksExecuted); uint64 revertedPriorityRequests = 0; for (uint32 i = 0; i < blocksToRevert; ++i) { StoredBlockInfo memory storedBlockInfo = _blocksToRevert[i]; require(storedBlockHashes[blocksCommitted] == hashStoredBlockInfo(storedBlockInfo), "r"); // incorrect stored block info delete storedBlockHashes[blocksCommitted]; --blocksCommitted; revertedPriorityRequests += storedBlockInfo.priorityOperations; } totalBlocksCommitted = blocksCommitted; totalCommittedPriorityRequests -= revertedPriorityRequests; if (totalBlocksCommitted < totalBlocksProven) { totalBlocksProven = totalBlocksCommitted; } emit BlocksRevert(totalBlocksExecuted, blocksCommitted); } /// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event. /// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest /// @dev of existed priority requests expiration block number. /// @return bool flag that is true if the Exodus mode must be entered. function activateExodusMode() public returns (bool) { // #if EASY_EXODUS bool trigger = true; // #else bool trigger = block.number >= priorityRequests[firstPriorityRequestId].expirationBlock && priorityRequests[firstPriorityRequestId].expirationBlock != 0; // #endif if (trigger) { if (!exodusMode) { exodusMode = true; emit ExodusMode(); } return true; } else { return false; } } /// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds /// @param _storedBlockInfo Last verified block /// @param _owner Owner of the account /// @param _accountId Id of the account in the tree /// @param _proof Proof /// @param _tokenId Verified token id /// @param _amount Amount for owner (must be total amount, not part of it) function performExodus( StoredBlockInfo memory _storedBlockInfo, address _owner, uint32 _accountId, uint16 _tokenId, uint128 _amount, uint256[] memory _proof ) external nonReentrant { bytes22 packedBalanceKey = packAddressAndTokenId(_owner, _tokenId); require(exodusMode, "s"); // must be in exodus mode require(!performedExodus[_accountId][_tokenId], "t"); // already exited require(storedBlockHashes[totalBlocksExecuted] == hashStoredBlockInfo(_storedBlockInfo), "u"); // incorrect sotred block info bool proofCorrect = verifier.verifyExitProof(_storedBlockInfo.stateHash, _accountId, _owner, _tokenId, _amount, _proof); require(proofCorrect, "x"); increaseBalanceToWithdraw(packedBalanceKey, _amount); performedExodus[_accountId][_tokenId] = true; } /// @notice Set data for changing pubkey hash using onchain authorization. /// Transaction author (msg.sender) should be L2 account address /// @notice New pubkey hash can be reset, to do that user should send two transactions: /// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer. /// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`. /// @param _pubkeyHash New pubkey hash /// @param _nonce Nonce of the change pubkey L2 transaction function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external { require(_pubkeyHash.length == PUBKEY_HASH_BYTES, "y"); // PubKeyHash should be 20 bytes. if (authFacts[msg.sender][_nonce] == bytes32(0)) { authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash); } else { uint256 currentResetTimer = authFactsResetTimer[msg.sender][_nonce]; if (currentResetTimer == 0) { authFactsResetTimer[msg.sender][_nonce] = block.timestamp; } else { require(block.timestamp.sub(currentResetTimer) >= AUTH_FACT_RESET_TIMELOCK, "z"); authFactsResetTimer[msg.sender][_nonce] = 0; authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash); } } } /// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event /// @param _tokenId Token by id /// @param _amount Token amount /// @param _owner Receiver function registerDeposit( uint16 _tokenId, uint128 _amount, address _owner ) internal { // Priority Queue request Operations.Deposit memory op = Operations.Deposit({ accountId: 0, // unknown at this point owner: _owner, tokenId: _tokenId, amount: _amount }); bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.Deposit, pubData); emit Deposit(_tokenId, _amount); } /// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event /// @param _token - token by id /// @param _amount - token amount /// @param _to - address to withdraw to function registerWithdrawal( uint16 _token, uint128 _amount, address payable _to ) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token); uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw; pendingBalances[packedBalanceKey].balanceToWithdraw = balance.sub(_amount); emit Withdrawal(_token, _amount); } /// @dev Gets operations packed in bytes array. Unpacks it and stores onchain operations. /// @dev Priority operations must be committed in the same order as they are in the priority queue. /// @dev NOTE: does not change storage! (only emits events) /// @dev processableOperationsHash - hash of the all operations that needs to be executed (Deposit, Exits, ChangPubKey) /// @dev priorityOperationsProcessed - number of priority operations processed in this block (Deposits, FullExits) /// @dev offsetsCommitment - array where 1 is stored in chunk where onchainOperation begins and other are 0 (used in commitments) function collectOnchainOps(CommitBlockInfo memory _newBlockData) internal view returns ( bytes32 processableOperationsHash, uint64 priorityOperationsProcessed, bytes memory offsetsCommitment ) { bytes memory pubData = _newBlockData.publicData; uint64 uncommittedPriorityRequestsOffset = firstPriorityRequestId + totalCommittedPriorityRequests; priorityOperationsProcessed = 0; processableOperationsHash = EMPTY_STRING_KECCAK; require(pubData.length % CHUNK_BYTES == 0, "A"); // pubdata length must be a multiple of CHUNK_BYTES offsetsCommitment = new bytes(pubData.length / CHUNK_BYTES); for (uint256 i = 0; i < _newBlockData.onchainOperations.length; ++i) { OnchainOperationData memory onchainOpData = _newBlockData.onchainOperations[i]; uint256 pubdataOffset = onchainOpData.publicDataOffset; require(pubdataOffset < pubData.length, "A1"); require(pubdataOffset % CHUNK_BYTES == 0, "B"); // offsets should be on chunks boundaries uint256 chunkId = pubdataOffset / CHUNK_BYTES; require(offsetsCommitment[chunkId] == 0x00, "C"); // offset commitment should be empty offsetsCommitment[chunkId] = bytes1(0x01); Operations.OpType opType = Operations.OpType(uint8(pubData[pubdataOffset])); if (opType == Operations.OpType.Deposit) { bytes memory opPubData = Bytes.slice(pubData, pubdataOffset, DEPOSIT_BYTES); Operations.Deposit memory depositData = Operations.readDepositPubdata(opPubData); checkPriorityOperation(depositData, uncommittedPriorityRequestsOffset + priorityOperationsProcessed); priorityOperationsProcessed++; } else if (opType == Operations.OpType.ChangePubKey) { bytes memory opPubData = Bytes.slice(pubData, pubdataOffset, CHANGE_PUBKEY_BYTES); Operations.ChangePubKey memory op = Operations.readChangePubKeyPubdata(opPubData); if (onchainOpData.ethWitness.length != 0) { bool valid = verifyChangePubkey(onchainOpData.ethWitness, op); require(valid, "D"); // failed to verify change pubkey hash signature } else { bool valid = authFacts[op.owner][op.nonce] == keccak256(abi.encodePacked(op.pubKeyHash)); require(valid, "E"); // new pub key hash is not authenticated properly } } else { bytes memory opPubData; if (opType == Operations.OpType.PartialExit) { opPubData = Bytes.slice(pubData, pubdataOffset, PARTIAL_EXIT_BYTES); } else if (opType == Operations.OpType.ForcedExit) { opPubData = Bytes.slice(pubData, pubdataOffset, FORCED_EXIT_BYTES); } else if (opType == Operations.OpType.FullExit) { opPubData = Bytes.slice(pubData, pubdataOffset, FULL_EXIT_BYTES); Operations.FullExit memory fullExitData = Operations.readFullExitPubdata(opPubData); checkPriorityOperation( fullExitData, uncommittedPriorityRequestsOffset + priorityOperationsProcessed ); priorityOperationsProcessed++; } else { revert("F"); // unsupported op } processableOperationsHash = Utils.concatHash(processableOperationsHash, opPubData); } } } /// @notice Checks that change operation is correct function verifyChangePubkey(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { Operations.ChangePubkeyType changePkType = Operations.ChangePubkeyType(uint8(_ethWitness[0])); if (changePkType == Operations.ChangePubkeyType.ECRECOVER) { return verifyChangePubkeyECRECOVER(_ethWitness, _changePk); } else if (changePkType == Operations.ChangePubkeyType.CREATE2) { return verifyChangePubkeyCREATE2(_ethWitness, _changePk); } else if (changePkType == Operations.ChangePubkeyType.OldECRECOVER) { return verifyChangePubkeyOldECRECOVER(_ethWitness, _changePk); } else { revert("G"); // Incorrect ChangePubKey type } } /// @notice Checks that signature is valid for pubkey change message /// @param _ethWitness Signature (65 bytes) + 32 bytes of the arbitrary signed data /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { (, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey // (, bytes32 additionalData) = Bytes.readBytes32(_ethWitness, offset); bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n60", _changePk.pubKeyHash, _changePk.nonce, _changePk.accountId, bytes32(0) ) ); address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash); return recoveredAddress == _changePk.owner && recoveredAddress != address(0); } /// @notice Checks that signature is valid for pubkey change message, old version differs by form of the signed message. /// @param _ethWitness Signature (65 bytes) /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyOldECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { (, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n152", "Register zkSync pubkey:\n\n", Bytes.bytesToHexASCIIBytes(abi.encodePacked(_changePk.pubKeyHash)), "\n", "nonce: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.nonce)), "\n", "account id: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.accountId)), "\n\n", "Only sign this message for a trusted client!" ) ); address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash); return recoveredAddress == _changePk.owner && recoveredAddress != address(0); } /// @notice Checks that signature is valid for pubkey change message /// @param _ethWitness Create2 deployer address, saltArg, codeHash /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyCREATE2(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { address creatorAddress; bytes32 saltArg; // salt arg is additional bytes that are encoded in the CREATE2 salt bytes32 codeHash; uint256 offset = 1; // offset is 1 because we skip type of ChangePubkey (offset, creatorAddress) = Bytes.readAddress(_ethWitness, offset); (offset, saltArg) = Bytes.readBytes32(_ethWitness, offset); (offset, codeHash) = Bytes.readBytes32(_ethWitness, offset); // salt from CREATE2 specification bytes32 salt = keccak256(abi.encodePacked(saltArg, _changePk.pubKeyHash)); // Address computation according to CREATE2 definition: https://eips.ethereum.org/EIPS/eip-1014 address recoveredAddress = address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), creatorAddress, salt, codeHash))))); // This type of change pubkey can be done only once return recoveredAddress == _changePk.owner && _changePk.nonce == 0; } /// @dev Creates block commitment from its data /// @dev _offsetCommitment - hash of the array where 1 is stored in chunk where onchainOperation begins and 0 for other chunks function createBlockCommitment( StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlockData, bytes memory _offsetCommitment ) internal view returns (bytes32 commitment) { bytes32 hash = sha256(abi.encodePacked(uint256(_newBlockData.blockNumber), uint256(_newBlockData.feeAccount))); hash = sha256(abi.encodePacked(hash, _previousBlock.stateHash)); hash = sha256(abi.encodePacked(hash, _newBlockData.newStateHash)); hash = sha256(abi.encodePacked(hash, uint256(_newBlockData.timestamp))); bytes memory pubdata = abi.encodePacked(_newBlockData.publicData, _offsetCommitment); /// The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))` /// We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation). /// Specifically, we perform the following trick: /// First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`. /// Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer. /// Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`). assembly { let hashResult := mload(0x40) let pubDataLen := mload(pubdata) mstore(pubdata, hash) // staticcall to the sha256 precompile at address 0x2 let success := staticcall(gas(), 0x2, pubdata, add(pubDataLen, 0x20), hashResult, 0x20) mstore(pubdata, pubDataLen) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } commitment := mload(hashResult) } } /// @notice Checks that deposit is same as operation in priority queue /// @param _deposit Deposit data /// @param _priorityRequestId Operation's id in priority queue function checkPriorityOperation(Operations.Deposit memory _deposit, uint64 _priorityRequestId) internal view { Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType; require(priorReqType == Operations.OpType.Deposit, "H"); // incorrect priority op type bytes20 hashedPubdata = priorityRequests[_priorityRequestId].hashedPubData; require(Operations.checkDepositInPriorityQueue(_deposit, hashedPubdata), "I"); } /// @notice Checks that FullExit is same as operation in priority queue /// @param _fullExit FullExit data /// @param _priorityRequestId Operation's id in priority queue function checkPriorityOperation(Operations.FullExit memory _fullExit, uint64 _priorityRequestId) internal view { Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType; require(priorReqType == Operations.OpType.FullExit, "J"); // incorrect priority op type bytes20 hashedPubdata = priorityRequests[_priorityRequestId].hashedPubData; require(Operations.checkFullExitInPriorityQueue(_fullExit, hashedPubdata), "K"); } /// @notice Checks that current state not is exodus mode function requireActive() internal view { require(!exodusMode, "L"); // exodus mode activated } // Priority queue /// @notice Saves priority request in storage /// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event /// @param _opType Rollup operation type /// @param _pubData Operation pubdata function addPriorityRequest(Operations.OpType _opType, bytes memory _pubData) internal { // Expiration block is: current block number + priority expiration delta uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION); uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests; bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData); priorityRequests[nextPriorityRequestId] = PriorityOperation({ hashedPubData: hashedPubData, expirationBlock: expirationBlock, opType: _opType }); emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock)); totalOpenPriorityRequests++; } /// @notice Deletes processed priority requests /// @param _number The number of requests function deleteRequests(uint64 _number) internal { require(_number <= totalOpenPriorityRequests, "M"); // number is higher than total priority requests number uint64 numberOfRequestsToClear = Utils.minU64(_number, MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY); uint64 startIndex = firstPriorityRequestId; for (uint64 i = startIndex; i < startIndex + numberOfRequestsToClear; i++) { delete priorityRequests[i]; } totalOpenPriorityRequests -= _number; firstPriorityRequestId += _number; totalCommittedPriorityRequests -= _number; } function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal { uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw; pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE); } /// @notice Sends ETH /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) { (bool callSuccess, ) = _to.call{gas: WITHDRAWAL_GAS_LIMIT, value: _amount}(""); return callSuccess; } }
Reverts unverified blocks
function revertBlocks(StoredBlockInfo[] memory _blocksToRevert) external nonReentrant { governance.requireActiveValidator(msg.sender); uint32 blocksCommitted = totalBlocksCommitted; uint32 blocksToRevert = Utils.minU32(uint32(_blocksToRevert.length), blocksCommitted - totalBlocksExecuted); uint64 revertedPriorityRequests = 0; for (uint32 i = 0; i < blocksToRevert; ++i) { StoredBlockInfo memory storedBlockInfo = _blocksToRevert[i]; delete storedBlockHashes[blocksCommitted]; --blocksCommitted; revertedPriorityRequests += storedBlockInfo.priorityOperations; } totalBlocksCommitted = blocksCommitted; totalCommittedPriorityRequests -= revertedPriorityRequests; if (totalBlocksCommitted < totalBlocksProven) { totalBlocksProven = totalBlocksCommitted; } emit BlocksRevert(totalBlocksExecuted, blocksCommitted); }
13,012,650
./partial_match/1/0x41C1F38A4BbFA4f14Ef235ed8901b3a0e51a2933/sources/NABC.sol
Allows updating the UniswapRouter in cases where liquidity is moved/ Create a uniswap pair for the new token
function updateUniswapRouter(address newRouterAddress) external onlyOwner { IUniswapV2Router02 newRouter = IUniswapV2Router02(newRouterAddress); IUniswapV2Factory newFactory = IUniswapV2Factory(newRouter.factory()); address newPair = newFactory.getPair( address(this), newRouter.WETH() ); if (newPair == address(0)) { newPair = newFactory.createPair( address(this), newRouter.WETH() ); } uniswapRouter = newRouter; pairs[newPair] = true; }
2,617,113
pragma solidity 0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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: openzeppelin-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: openzeppelin-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 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; } } // File: contracts/Vault12LockedTokens.sol contract Vault12LockedTokens { using SafeMath for uint256; uint256 constant internal SECONDS_PER_YEAR = 31561600; modifier onlyV12MultiSig { require(msg.sender == v12MultiSig, "not owner"); _; } modifier onlyValidAddress(address _recipient) { require(_recipient != address(0) && _recipient != address(this) && _recipient != address(token), "not valid _recipient"); _; } struct Grant { uint256 startTime; uint256 amount; uint256 vestingDuration; uint256 yearsClaimed; uint256 totalClaimed; } event GrantAdded(address recipient, uint256 amount); event GrantTokensClaimed(address recipient, uint256 amountClaimed); event ChangedMultisig(address multisig); ERC20 public token; mapping (address => Grant) public tokenGrants; address public v12MultiSig; constructor(ERC20 _token) public { require(address(_token) != address(0)); v12MultiSig = msg.sender; token = _token; } function addTokenGrant( address _recipient, uint256 _startTime, uint256 _amount, uint256 _vestingDurationInYears ) onlyV12MultiSig onlyValidAddress(_recipient) external { require(!grantExist(_recipient), "grant already exist"); require(_vestingDurationInYears <= 25, "more than 25 years"); uint256 amountVestedPerYear = _amount.div(_vestingDurationInYears); require(amountVestedPerYear > 0, "amountVestedPerYear > 0"); // Transfer the grant tokens under the control of the vesting contract require(token.transferFrom(msg.sender, address(this), _amount), "transfer failed"); Grant memory grant = Grant({ startTime: _startTime == 0 ? currentTime() : _startTime, amount: _amount, vestingDuration: _vestingDurationInYears, yearsClaimed: 0, totalClaimed: 0 }); tokenGrants[_recipient] = grant; emit GrantAdded(_recipient, _amount); } /// @notice Calculate the vested and unclaimed months and tokens available for `_grantId` to claim /// Due to rounding errors once grant duration is reached, returns the entire left grant amount /// Returns (0, 0) if cliff has not been reached function calculateGrantClaim(address _recipient) public view returns (uint256, uint256) { Grant storage tokenGrant = tokenGrants[_recipient]; // For grants created with a future start date, that hasn't been reached, return 0, 0 if (currentTime() < tokenGrant.startTime) { return (0, 0); } uint256 elapsedTime = currentTime().sub(tokenGrant.startTime); uint256 elapsedYears = elapsedTime.div(SECONDS_PER_YEAR); // If over vesting duration, all tokens vested if (elapsedYears >= tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); uint256 remainingYears = tokenGrant.vestingDuration.sub(tokenGrant.yearsClaimed); return (remainingYears, remainingGrant); } else { uint256 i = 0; uint256 tokenGrantAmount = tokenGrant.amount; uint256 totalVested = 0; for(i; i < elapsedYears; i++){ totalVested = (tokenGrantAmount.mul(10)).div(100).add(totalVested); tokenGrantAmount = tokenGrant.amount.sub(totalVested); } uint256 amountVested = totalVested.sub(tokenGrant.totalClaimed); return (elapsedYears, amountVested); } } /// @notice Allows a grant recipient to claim their vested tokens. Errors if no tokens have vested /// It is advised recipients check they are entitled to claim via `calculateGrantClaim` before calling this function claimVestedTokens(address _recipient) external { uint256 yearsVested; uint256 amountVested; (yearsVested, amountVested) = calculateGrantClaim(_recipient); require(amountVested > 0, "amountVested is 0"); Grant storage tokenGrant = tokenGrants[_recipient]; tokenGrant.yearsClaimed = yearsVested; tokenGrant.totalClaimed = tokenGrant.totalClaimed.add(amountVested); require(token.transfer(_recipient, amountVested), "no tokens"); emit GrantTokensClaimed(_recipient, amountVested); } function currentTime() public view returns(uint256) { return block.timestamp; } function changeMultiSig(address _newMultisig) external onlyV12MultiSig onlyValidAddress(_newMultisig) { v12MultiSig = _newMultisig; emit ChangedMultisig(_newMultisig); } function grantExist(address _recipient) public view returns(bool) { return tokenGrants[_recipient].amount > 0; } }
Calculate the vested and unclaimed months and tokens available for `_grantId` to claim Due to rounding errors once grant duration is reached, returns the entire left grant amount Returns (0, 0) if cliff has not been reached For grants created with a future start date, that hasn't been reached, return 0, 0 If over vesting duration, all tokens vested
function calculateGrantClaim(address _recipient) public view returns (uint256, uint256) { Grant storage tokenGrant = tokenGrants[_recipient]; if (currentTime() < tokenGrant.startTime) { return (0, 0); } uint256 elapsedTime = currentTime().sub(tokenGrant.startTime); uint256 elapsedYears = elapsedTime.div(SECONDS_PER_YEAR); if (elapsedYears >= tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); uint256 remainingYears = tokenGrant.vestingDuration.sub(tokenGrant.yearsClaimed); return (remainingYears, remainingGrant); uint256 i = 0; uint256 tokenGrantAmount = tokenGrant.amount; uint256 totalVested = 0; for(i; i < elapsedYears; i++){ totalVested = (tokenGrantAmount.mul(10)).div(100).add(totalVested); tokenGrantAmount = tokenGrant.amount.sub(totalVested); } uint256 amountVested = totalVested.sub(tokenGrant.totalClaimed); return (elapsedYears, amountVested); } }
2,471,681
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg interface UpgradeBeaconControllerInterface { function upgrade(address beacon, address implementation) external; } 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) { require(b <= a, "SafeMath: subtraction overflow"); 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) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @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 aplied to your functions to restrict their use to * the owner. * * In order to transfer ownership, a recipient must be specified, at which point * the specified recipient can call `acceptOwnership` and take ownership. */ contract TwoStepOwnable { address private _owner; address private _newPotentialOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initialize contract by setting transaction submitter as initial owner. */ constructor() internal { _owner = tx.origin; 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(), "TwoStepOwnable: caller is not the owner."); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows a new account (`newOwner`) to accept ownership. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } /** * @dev Cancel a transfer of ownership to a new account. * Can only be called by the current owner. */ function cancelOwnershipTransfer() public onlyOwner { _newPotentialOwner = address(0); } /** * @dev Transfers ownership of the contract to the caller. * Can only be called by a new potential owner set by the current owner. */ function acceptOwnership() public { require( msg.sender != _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OwnershipTransferred(_owner, msg.sender); _owner = msg.sender; } } /** * @title Timelocker * @author 0age * @notice This contract allows contracts that inherit it to implement timelocks * on functions, where the `setTimelock` function must first be called, with the * same arguments that the function will be supplied with. Then, a given time * interval must first fully transpire before the timelock functions can be * successfully called. It also includes a `modifyTimelockInterval` function * that is itself able to be timelocked, and that is given a function selector * and a new timelock interval for the function as arguments. To make a function * timelocked, use the `_enforceTimelock` internal function. To set initial * minimum timelock intervals, use the `_setInitialTimelockInterval` internal * function - it can only be used from within a constructor. Finally, there are * two public getters: `getTimelock` and `getTimelockInterval`. */ contract Timelocker { using SafeMath for uint256; // Fire an event any time a timelock is initiated. event TimelockInitiated( bytes4 functionSelector, // selector of the function uint256 timeComplete, // timestamp at which the function can be called bytes arguments, // abi-encoded function arguments to call with uint256 timeExpired // timestamp where function can no longer be called ); // Fire an event any time a minimum timelock interval is modified. event TimelockIntervalModified( bytes4 functionSelector, // selector of the function uint256 oldInterval, // old minimum timelock interval for the function uint256 newInterval // new minimum timelock interval for the function ); // Fire an event any time a default timelock expiration is modified. event TimelockExpirationModified( bytes4 functionSelector, // selector of the function uint256 oldExpiration, // old default timelock expiration for the function uint256 newExpiration // new default timelock expiration for the function ); // Each timelock has timestamps for when it is complete and when it expires. struct Timelock { uint128 complete; uint128 expires; } // Implement a timelock for each function and set of arguments. mapping(bytes4 => mapping(bytes32 => Timelock)) private _timelocks; // Implement a default timelock interval for each timelocked function. mapping(bytes4 => uint256) private _timelockIntervals; // Implement a default timelock expiration for each timelocked function. mapping(bytes4 => uint256) private _timelockExpirations; bytes32 private constant _EMPTY_HASH = bytes32( 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 ); /** * @notice Public function for setting a new timelock interval for a given * function selector. The default for this function may also be modified, but * excessive values will cause the `modifyTimelockInterval` function to become * unusable. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */ function modifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) public { // Ensure that the new timelock interval will not cause an overflow error. require( newTimelockInterval < 365000000000000 days, "New timelock interval is too large." ); // Ensure that the timelock has been set and is completed. _enforceTimelock( this.modifyTimelockInterval.selector, abi.encode() ); // Set new timelock interval and emit a `TimelockIntervalModified` event. _setTimelockInterval(functionSelector, newTimelockInterval); } /** * @notice Public function for setting a new timelock expiration for a given * function selector. Once the minimum interval has elapsed, the timelock will * expire once the specified expiration time has elapsed. Setting this value * too low will result in timelocks that are very difficult to execute * correctly. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration the new minimum timelock expiration to set for * the given function. */ function modifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) public { // Ensure that the new timelock expiration will not cause an overflow error. require( newTimelockExpiration < 365000000000000 days, "New timelock expiration is too large." ); // Ensure that the new timelock expiration will not cause an overflow error. require( newTimelockExpiration > 1 minutes, "New timelock expiration is too short." ); // Ensure that the timelock has been set and is completed. _enforceTimelock( this.modifyTimelockExpiration.selector, abi.encode() ); // Set new default expiration and emit a `TimelockExpirationModified` event. _setTimelockExpiration(functionSelector, newTimelockExpiration); } /** * @notice View function to check if a timelock for the specified function and * arguments has completed. * @param functionSelector function to be called. * @param arguments The abi-encoded arguments of the function to be called. * @return A boolean indicating if the timelock exists or not and the time at * which the timelock completes if it does exist. */ function getTimelock( bytes4 functionSelector, bytes memory arguments ) public view returns ( bool exists, bool completed, bool expired, uint256 completionTime, uint256 expirationTime ) { // Get timelock ID using the supplied function arguments. bytes32 timelockID; if ( functionSelector == this.modifyTimelockInterval.selector || functionSelector == this.modifyTimelockExpiration.selector ) { timelockID = _EMPTY_HASH; } else { timelockID = keccak256(abi.encodePacked(arguments)); } // Get information on the current timelock, if one exists. completionTime = uint256(_timelocks[functionSelector][timelockID].complete); exists = completionTime != 0; expirationTime = uint256(_timelocks[functionSelector][timelockID].expires); completed = exists && now > completionTime; expired = exists && now > expirationTime; } /** * @notice View function to check the current minimum timelock interval on a * given function. * @param functionSelector function to retrieve the timelock interval for. * @return The current minimum timelock interval for the given function. */ function getTimelockInterval( bytes4 functionSelector ) public view returns (uint256 timelockInterval) { timelockInterval = _timelockIntervals[functionSelector]; } /** * @notice View function to check the current default timelock expiration on a * given function. * @param functionSelector function to retrieve the timelock expiration for. * @return The current default timelock expiration for the given function. */ function getTimelockExpiration( bytes4 functionSelector ) public view returns (uint256 timelockExpiration) { timelockExpiration = _timelockExpirations[functionSelector]; } /** * @notice Internal function that sets a timelock so that the specified * function can be called with the specified arguments. Note that existing * timelocks may be extended, but not shortened - this can also be used as a * method for "cancelling" a function call by extending the timelock to an * arbitrarily long duration. Keep in mind that new timelocks may be created * with a shorter duration on functions that already have other timelocks on * them, but only if they have different arguments. * @param functionSelector selector of the function to be called. * @param arguments The abi-encoded arguments of the function to be called. * @param extraTime Additional time in seconds to add to the minimum timelock * interval for the given function. */ function _setTimelock( bytes4 functionSelector, bytes memory arguments, uint256 extraTime ) internal { // Get timelock using current time, inverval for timelock ID, & extra time. uint256 timelock = _timelockIntervals[functionSelector].add(now).add( extraTime ); // Get expiration time using timelock duration plus default expiration time. uint256 expiration = timelock.add(_timelockExpirations[functionSelector]); // Get timelock ID using the supplied function arguments. bytes32 timelockID; if ( functionSelector == this.modifyTimelockInterval.selector || functionSelector == this.modifyTimelockExpiration.selector ) { timelockID = _EMPTY_HASH; } else { timelockID = keccak256(abi.encodePacked(arguments)); } // Get the current timelock, if one exists. Timelock storage timelockStorage = _timelocks[functionSelector][timelockID]; uint256 currentTimelock = uint256(timelockStorage.complete); // Ensure that the timelock duration does not decrease. Note that a new, // shorter timelock may still be set up on the same function in the event // that it is provided with different arguments. require( currentTimelock == 0 || timelock > currentTimelock, "Existing timelocks may only be extended." ); // Set timelock completion and expiration using timelock ID and extra time. timelockStorage.complete = uint128(timelock); timelockStorage.expires = uint128(expiration); // Emit an event with all of the relevant information. emit TimelockInitiated(functionSelector, timelock, arguments, expiration); } /** * @notice Internal function to set an initial timelock interval for a given * function selector. Only callable during contract creation. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */ function _setInitialTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) internal { // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set the timelock interval and emit a `TimelockIntervalModified` event. _setTimelockInterval(functionSelector, newTimelockInterval); } /** * @notice Internal function to set an initial timelock expiration for a given * function selector. Only callable during contract creation. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration the new minimum timelock expiration to set for * the given function. */ function _setInitialTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) internal { // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set the timelock interval and emit a `TimelockExpirationModified` event. _setTimelockExpiration(functionSelector, newTimelockExpiration); } /** * @notice Internal function to ensure that a timelock is complete or expired * and to clear the existing timelock if it is complete so it cannot later be * reused. * @param functionSelector function to be called. * @param arguments The abi-encoded arguments of the function to be called. */ function _enforceTimelock( bytes4 functionSelector, bytes memory arguments ) internal { // Get timelock ID using the supplied function arguments. bytes32 timelockID = keccak256(abi.encodePacked(arguments)); // Get the current timelock, if one exists. Timelock memory timelock = _timelocks[functionSelector][timelockID]; uint256 currentTimelock = uint256(timelock.complete); uint256 expiration = uint256(timelock.expires); // Ensure that the timelock is set and has completed. require( currentTimelock != 0 && currentTimelock <= now, "Timelock is incomplete." ); // Ensure that the timelock has not expired. require(expiration > now, "Timelock has expired."); // Clear out the existing timelock so that it cannot be reused. delete _timelocks[functionSelector][timelockID]; } /** * @notice Private function for setting a new timelock interval for a given * function selector. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */ function _setTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) private { // Get the existing timelock interval, if any. uint256 oldTimelockInterval = _timelockIntervals[functionSelector]; // Update the timelock interval on the provided function. _timelockIntervals[functionSelector] = newTimelockInterval; // Emit a `TimelockIntervalModified` event with the appropriate arguments. emit TimelockIntervalModified( functionSelector, oldTimelockInterval, newTimelockInterval ); } /** * @notice Private function for setting a new timelock expiration for a given * function selector. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockExpiration the new default timelock expiration to set for * the given function. */ function _setTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) private { // Get the existing timelock expiration, if any. uint256 oldTimelockExpiration = _timelockExpirations[functionSelector]; // Update the timelock expiration on the provided function. _timelockExpirations[functionSelector] = newTimelockExpiration; // Emit a `TimelockExpirationModified` event with the appropriate arguments. emit TimelockExpirationModified( functionSelector, oldTimelockExpiration, newTimelockExpiration ); } } /** * @title DharmaUpgradeBeaconControllerManager * @author 0age * @notice This contract will be owned by DharmaUpgradeMultisig and will manage * upgrades to the global smart wallet and key ring implementation contracts via * dedicated control over the "upgrade beacon" controller contracts (and can * additionally be used to manage other upgrade beacon controllers). It contains * a set of timelocked functions, where the `setTimelock` function must first be * called, with the same arguments that the function will be supplied with. * Then, a given time interval must first fully transpire before the timelock * functions can be successfully called. * * The timelocked functions currently implemented include: * upgrade(address controller, address implementation) * transferControllerOwnership(address controller, address newOwner) * modifyTimelockInterval(bytes4 functionSelector, uint256 newTimelockInterval) * modifyTimelockExpiration( * bytes4 functionSelector, uint256 newTimelockExpiration * ) * * It also specifies dedicated implementations for the Dharma Smart Wallet and * Dharma Key Ring upgrade beacons that can be triggered in an emergency or in * the event of an extended period of inactivity from Dharma. These contingency * implementations give the user the ability to withdraw any funds on their * smart wallet by submitting a transaction directly from the account of any of * their signing keys, but are otherwise kept as simple as possible. * * This contract can transfer ownership of any upgrade beacon controller it owns * (subject to the timelock on `transferControllerOwnership`), in order to * introduce new upgrade conditions or to otherwise alter the way that upgrades * are carried out. */ contract DharmaUpgradeBeaconControllerManager is TwoStepOwnable, Timelocker { using SafeMath for uint256; // Fire an event whenever the Adharma Contingency is activated or exited. event AdharmaContingencyActivated(address controller, address beacon); event AdharmaContingencyExited(address controller, address beacon); // Store timestamp and last implementation in case of Adharma Contingency. // Note that this is specific to a particular controller and beacon. struct AdharmaContingency { bool armed; bool activated; uint256 activationTime; } // Store the last implementation address for each controller + beacon pair. mapping(address => mapping (address => address)) private _lastImplementation; // Store information on contingency status of each controller + beacon pair. mapping(address => mapping (address => AdharmaContingency)) private _adharma; // New controller owners must accept ownership before a transfer can occur. mapping(address => mapping(address => bool)) private _willAcceptOwnership; // Track the last heartbeat timestamp as well as the current heartbeat address uint256 private _lastHeartbeat; address private _heartbeater; // Store the address of the Dharma Smart Wallet Upgrade Beacon as a constant. address private constant _DHARMA_SMART_WALLET_UPGRADE_BEACON = address( 0x000000000026750c571ce882B17016557279ADaa ); // Store the Adharma Smart Wallet Contingency implementation. Note that this // is specific to the smart wallet and will not be activated on other beacons. address private constant _ADHARMA_SMART_WALLET_IMPLEMENTATION = address( 0x0000000053d300f11703dcDD1e90921Db83F0048 ); // Store the address of the Dharma Key Ring Upgrade Beacon as a constant. address private constant _DHARMA_KEY_RING_UPGRADE_BEACON = address( 0x0000000000BDA2152794ac8c76B2dc86cbA57cad ); // Store the Adharma Key Ring Contingency implementation. Note that this is // specific to the key ring and will not be activated on other beacons. address private constant _ADHARMA_KEY_RING_IMPLEMENTATION = address( 0x00000000480003d5eE4F51134CE73Cc9AC00f693 ); /** * @notice In the constructor, set tx.origin as initial owner, the initial * minimum timelock interval and expiration values, and some initial variable * values. */ constructor() public { // Ensure Adharma Smart Wallet implementation has the correct runtime code. bytes32 adharmaSmartWalletHash; bytes32 expectedAdharmaSmartWalletHash = bytes32( 0x2534c2b555b9011741eabee1c96e1683bb4f58483d05d3e654f00fde85c2673c ); address adharmaSmartWallet = _ADHARMA_SMART_WALLET_IMPLEMENTATION; assembly { adharmaSmartWalletHash := extcodehash(adharmaSmartWallet) } require( adharmaSmartWalletHash == expectedAdharmaSmartWalletHash, "Adharma Smart Wallet implementation runtime code hash is incorrect." ); // Ensure Adharma Key Ring implementation has the correct runtime code. bytes32 adharmaKeyRingHash; bytes32 expectedAdharmaKeyRingHash = bytes32( 0x72f85d929335f00aee7e110513479e43febf22b0ee7826ee4f8cfc767be6c001 ); address adharmaKeyRing = _ADHARMA_KEY_RING_IMPLEMENTATION; assembly { adharmaKeyRingHash := extcodehash(adharmaKeyRing) } require( adharmaKeyRingHash == expectedAdharmaKeyRingHash, "Adharma Key Ring implementation runtime code hash is incorrect." ); // Set initial minimum timelock interval values. _setInitialTimelockInterval( this.transferControllerOwnership.selector, 4 weeks ); _setInitialTimelockInterval(this.modifyTimelockInterval.selector, 4 weeks); _setInitialTimelockInterval( this.modifyTimelockExpiration.selector, 4 weeks ); _setInitialTimelockInterval(this.upgrade.selector, 7 days); // Set initial default timelock expiration values. _setInitialTimelockExpiration( this.transferControllerOwnership.selector, 7 days ); _setInitialTimelockExpiration(this.modifyTimelockInterval.selector, 7 days); _setInitialTimelockExpiration( this.modifyTimelockExpiration.selector, 7 days ); _setInitialTimelockExpiration(this.upgrade.selector, 7 days); // Set the initial owner as the initial heartbeater. _heartbeater = tx.origin; _lastHeartbeat = now; } /** * @notice Initiates a timelocked upgrade process via a given controller and * upgrade beacon to a given implementation address. Only the owner may call * this function. Once the timelock period is complete (and before it has * expired) the owner may call `upgrade` to complete the process and trigger * the upgrade. * @param controller address of controller to call into that will trigger the * update to the specified upgrade beacon. * @param beacon address of upgrade beacon to set the new implementation on. * @param implementation the address of the new implementation. * @param extraTime Additional time in seconds to add to the timelock. */ function initiateUpgrade( address controller, address beacon, address implementation, uint256 extraTime ) external onlyOwner { require(controller != address(0), "Must specify a controller address."); require(beacon != address(0), "Must specify a beacon address."); // Ensure that the implementaton contract is not the null address. require( implementation != address(0), "Implementation cannot be the null address." ); // Ensure that the implementation contract has code via extcodesize. uint256 size; assembly { size := extcodesize(implementation) } require(size > 0, "Implementation must have contract code."); // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.upgrade.selector, abi.encode(controller, beacon, implementation), extraTime ); } /** * @notice Timelocked function to set a new implementation address on an * upgrade beacon contract. This function could optionally check the * runtime code of the specified upgrade beacon, but that step is not strictly * necessary. * @param controller address of controller to call into that will trigger the * update to the specified upgrade beacon. * @param beacon address of upgrade beacon to set the new implementation on. * @param implementation the address of the new implementation. */ function upgrade( address controller, address beacon, address implementation ) external onlyOwner { // Ensure that the timelock has been set and is completed. _enforceTimelock( this.upgrade.selector, abi.encode(controller, beacon, implementation) ); // Reset the heartbeat to the current time. _lastHeartbeat = now; // Call controller with beacon to upgrade and implementation to upgrade to. _upgrade(controller, beacon, implementation); } /** * @notice Allow a new potential owner of an upgrade beacon controller to * accept ownership of the controller. * @param controller address of controller to allow ownership transfer for. * @param willAcceptOwnership a boolean signifying if an ownership transfer to * the caller is acceptable. */ function agreeToAcceptOwnership( address controller, bool willAcceptOwnership ) external { require(controller != address(0), "Must specify a controller address."); // Register whether or not the new owner is willing to accept ownership. _willAcceptOwnership[controller][msg.sender] = willAcceptOwnership; } /** * @notice Timelocked function to set a new owner on an upgrade beacon * controller that is owned by this contract. * @param controller address of controller to transfer ownership of. * @param newOwner address to assign ownership of the controller to. */ function transferControllerOwnership( address controller, address newOwner ) external onlyOwner { // Ensure that the new owner has confirmed that it can accept ownership. require( _willAcceptOwnership[controller][newOwner], "New owner must agree to accept ownership of the given controller." ); // Ensure that the timelock has been set and is completed. _enforceTimelock( this.transferControllerOwnership.selector, abi.encode(controller, newOwner) ); // Transfer ownership of the controller to the new owner. TwoStepOwnable(controller).transferOwnership(newOwner); } /** * @notice Send a new heartbeat. If 90 days pass without a heartbeat, anyone * may trigger the Adharma Contingency and force an upgrade to any controlled * upgrade beacon. */ function heartbeat() external { require(msg.sender == _heartbeater, "Must be called from the heartbeater."); _lastHeartbeat = now; } /** * @notice Set a new heartbeater. * @param heartbeater address to designate as the heartbeating address. */ function newHeartbeater(address heartbeater) external onlyOwner { require(heartbeater != address(0), "Must specify a heartbeater address."); _heartbeater = heartbeater; } /** * @notice Arm the Adharma Contingency upgrade. This is required as an extra * safeguard against accidentally triggering the Adharma Contingency. * @param controller address of controller to arm. * @param beacon address of upgrade beacon to arm. * @param armed Boolean that signifies the desired armed status. */ function armAdharmaContingency( address controller, address beacon, bool armed ) external { require(controller != address(0), "Must specify a controller address."); require(beacon != address(0), "Must specify a beacon address."); // Determine if 90 days have passed since the last heartbeat. (bool expired, ) = heartbeatStatus(); require( isOwner() || expired, "Only callable by the owner or after 90 days without a heartbeat." ); // Arm (or disarm) the Adharma Contingency. _adharma[controller][beacon].armed = armed; } /** * @notice Trigger the Adharma Contingency upgrade. This requires that the * owner first call `armAdharmaContingency` and set `armed` to `true`. This is * only to be invoked in cases of a time-sensitive emergency, or if the owner * has become inactive for over 90 days. * @param controller address of controller to call into that will trigger the * update to the Adharma contingency implementation on the specified upgrade * beacon. * @param beacon address of upgrade beacon to set the Adharma contingency * implementation on. */ function activateAdharmaContingency( address controller, address beacon ) external { // Determine if 90 days have passed since the last heartbeat. (bool expired, ) = heartbeatStatus(); require( isOwner() || expired, "Only callable by the owner or after 90 days without a heartbeat." ); // Ensure that the Adharma Contingency has been armed. require( _adharma[controller][beacon].armed, "Adharma Contingency is not armed - are SURE you meant to call this?" ); require( !_adharma[controller][beacon].activated, "Adharma Contingency is already activated on this controller + beacon." ); // Mark the Adharma Contingency as having been activated. _adharma[controller][beacon] = AdharmaContingency({ armed: false, activated: true, activationTime: now }); // Trigger the upgrade to the correct Adharma implementation contract. if (beacon == _DHARMA_SMART_WALLET_UPGRADE_BEACON) { _upgrade(controller, beacon, _ADHARMA_SMART_WALLET_IMPLEMENTATION); } else if (beacon == _DHARMA_KEY_RING_UPGRADE_BEACON) { _upgrade(controller, beacon, _ADHARMA_KEY_RING_IMPLEMENTATION); } else { revert("Only the smart wallet or key ring contingency can be activated."); } // Emit an event to signal that the Adharma Contingency has been activated. emit AdharmaContingencyActivated(controller, beacon); } /** * @notice Roll back an upgrade to the last implementation and exit from * contingency status if one currently exists. Note that you can also roll * back a rollback to restore it back to the original implementation that was * just rolled back from. * @param controller address of controller to call into that will trigger the * rollback on the specified upgrade beacon. * @param beacon address of upgrade beacon to roll back to the last * implementation. */ function rollback(address controller, address beacon) external onlyOwner { // Ensure that there is an implementation address to roll back to. require( _lastImplementation[controller][beacon] != address(0), "No prior implementation to roll back to." ); // Exit the contingency state if there is currently one active. if (_adharma[controller][beacon].activated) { delete _adharma[controller][beacon]; emit AdharmaContingencyExited(controller, beacon); } // Reset the heartbeat to the current time. _lastHeartbeat = now; // Upgrade to the last implementation contract. _upgrade(controller, beacon, _lastImplementation[controller][beacon]); } /** * @notice Exit the Adharma Contingency by upgrading to a new contract. This * requires that the contingency is currently activated and that at least 48 * hours has elapsed since it was activated. * @param controller address of controller to call into that will trigger the * update to the Adharma contingency implementation on the specified upgrade * beacon. * @param beacon address of upgrade beacon to set the Adharma contingency * implementation on. * @param implementation the address of the new implementation. */ function exitAdharmaContingency( address controller, address beacon, address implementation ) external onlyOwner { // Ensure that the Adharma Contingency is currently active. require( _adharma[controller][beacon].activated, "Adharma Contingency is not currently activated." ); // Ensure that at least 48 hours has elapsed since the contingency commenced. require( now > _adharma[controller][beacon].activationTime + 48 hours, "Cannot exit contingency with a new upgrade until 48 hours have elapsed." ); // Exit the contingency state. delete _adharma[controller][beacon]; // Reset the heartbeat to the current time. _lastHeartbeat = now; // Call controller with beacon to upgrade and implementation to upgrade to. _upgrade(controller, beacon, implementation); // Emit an event to signal that the Adharma Contingency has been activated. emit AdharmaContingencyExited(controller, beacon); } /** * @notice Sets the timelock for a new timelock interval for a given function * selector. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval The new timelock interval to set for the given * function selector. * @param extraTime Additional time in seconds to add to the timelock. */ function initiateModifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval, uint256 extraTime ) public onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Ensure a timelock interval over eight weeks is not set on this function. if (functionSelector == this.modifyTimelockInterval.selector) { require( newTimelockInterval <= 8 weeks, "Timelock interval of modifyTimelockInterval cannot exceed eight weeks." ); } // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.modifyTimelockInterval.selector, abi.encode(functionSelector, newTimelockInterval), extraTime ); } /** * @notice Sets a new timelock interval for a given function selector. The * default for this function may also be modified, but has a maximum allowable * value of eight weeks. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval The new timelock interval to set for the given * function selector. */ function modifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) public onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Continue via logic in the inherited `modifyTimelockInterval` function. Timelocker.modifyTimelockInterval(functionSelector, newTimelockInterval); } /** * @notice Sets a new timelock expiration for a given function selector. The * default Only the owner may call this function. New expiration durations may * not exceed one month. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration The new timelock expiration to set for the * given function selector. * @param extraTime Additional time in seconds to add to the timelock. */ function initiateTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration, uint256 extraTime ) public onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Ensure that the supplied default expiration does not exceed 1 month. require( newTimelockExpiration <= 30 days, "New timelock expiration cannot exceed one month." ); // Ensure a timelock expiration under one hour is not set on this function. if (functionSelector == this.modifyTimelockExpiration.selector) { require( newTimelockExpiration >= 60 minutes, "Expiration of modifyTimelockExpiration must be at least an hour long." ); } // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.modifyTimelockExpiration.selector, abi.encode(functionSelector, newTimelockExpiration), extraTime ); } /** * @notice Sets a new timelock expiration for a given function selector. The * default for this function may also be modified, but has a minimum allowable * value of one hour. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration The new timelock expiration to set for the * given function selector. */ function modifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) public onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Continue via logic in the inherited `newTimelockExpiration` function. Timelocker.modifyTimelockExpiration( functionSelector, newTimelockExpiration ); } /** * @notice Determine if the deadman's switch has expired and get the time at * which it is set to expire (i.e. 90 days from the last heartbeat). */ function heartbeatStatus() public view returns ( bool expired, uint256 expirationTime ) { expirationTime = _lastHeartbeat + 90 days; expired = now > expirationTime; } /** * @notice Private function that sets a new implementation address on an * upgrade beacon contract. * @param controller address of controller to call into that will trigger the * update to the specified upgrade beacon. * @param beacon address of upgrade beacon to set the new implementation on. * @param implementation the address of the new implementation. */ function _upgrade( address controller, address beacon, address implementation ) private { // Ensure that the implementaton contract is not the null address. require( implementation != address(0), "Implementation cannot be the null address." ); // Ensure that the implementation contract has code via extcodesize. uint256 size; assembly { size := extcodesize(implementation) } require(size > 0, "Implementation must have contract code."); // Try to get current implementation contract, defaulting to null address. address currentImplementation; (bool ok, bytes memory returnData) = beacon.call(""); if (ok && returnData.length == 32) { currentImplementation = abi.decode(returnData, (address)); } else { currentImplementation = address(0); } // Record the last implementation in case it needs to be restored. _lastImplementation[controller][beacon] = currentImplementation; // Trigger the upgrade to the new implementation contract. UpgradeBeaconControllerInterface(controller).upgrade( beacon, implementation ); } }
Internal function to ensure that a timelock is complete or expired and to clear the existing timelock if it is complete so it cannot later be reused. functionSelector function to be called. arguments The abi-encoded arguments of the function to be called./ Get timelock ID using the supplied function arguments. Get the current timelock, if one exists. Ensure that the timelock is set and has completed. Ensure that the timelock has not expired. Clear out the existing timelock so that it cannot be reused.
function _enforceTimelock( bytes4 functionSelector, bytes memory arguments ) internal { bytes32 timelockID = keccak256(abi.encodePacked(arguments)); Timelock memory timelock = _timelocks[functionSelector][timelockID]; uint256 currentTimelock = uint256(timelock.complete); uint256 expiration = uint256(timelock.expires); require( currentTimelock != 0 && currentTimelock <= now, "Timelock is incomplete." ); require(expiration > now, "Timelock has expired."); delete _timelocks[functionSelector][timelockID]; }
12,797,105
./full_match/1/0x76E7BE90D0BF6bfaa2CA07381169654c6b45793F/sources/recharge.io/ropsten/token/RCG.sol
Add the value of the privilege granted through the allowance function
function upAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0), "Address cannot be 0x0"); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender]+addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; }
9,688,082
// CryptoRabbit Source code pragma solidity ^0.4.18; /// @title A base contract to control ownership /// @author cuilichen contract OwnerBase { // The addresses of the accounts that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// constructor function OwnerBase() public { ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; } /// @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 Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCFO The address of the new COO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @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 onlyCOO 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 onlyCOO whenPaused { // can't unpause if contract was upgraded paused = false; } } /** * * @title Interface for contracts conforming to fighters camp * @author cuilichen */ contract FighterCamp { // function isCamp() public pure returns (bool); // Required methods function getFighter(uint _tokenId) external view returns (uint32); } /// @title Base contract for combat /// @author cuilichen contract RabbitArena is OwnerBase { event FightersReady(uint32 season); event SeasonWinner(uint32 season, uint winnerID); struct Fighter { uint tokenID; uint32 strength; } //where are fighters from FighterCamp public theCamp; mapping (uint => Fighter) soldiers; uint32[] public seasons; uint32 public matchDay; /// @dev constructor function RabbitArena(address _camp) public { FighterCamp tmp = FighterCamp(_camp); require(tmp.isCamp()); theCamp = tmp; } /// @dev set camp for this contract function setBaseInfo(address _camp) external onlyCOO { FighterCamp tmp = FighterCamp(_camp); require(tmp.isCamp()); theCamp = tmp; } /// @dev release storaged data, to save gas fee. function releaseOldData() internal { for (uint i = 0; i < seasons.length; i++) { uint _season = seasons[i]; for (uint j = 0; j < 8; j++) { uint key = _season * 1000 + j; delete soldiers[key]; } } delete seasons;// seasons.length --> 0 } /// @dev set 8 fighters for a season, prepare for combat. function setFighters(uint32 _today, uint32 _season, uint[] _tokenIDs) external onlyCOO { require(_tokenIDs.length == 8); if (matchDay != _today) { releaseOldData(); matchDay = _today; } seasons.push(_season);// a new season //record fighter datas for(uint i = 0; i < 8; i++) { uint tmpID = _tokenIDs[i]; Fighter memory soldier = Fighter({ tokenID: tmpID, strength: theCamp.getFighter(tmpID) }); uint key = _season * 1000 + i; soldiers[key] = soldier; } //fire the event emit FightersReady(_season); } /// @dev get fighter property function getFighterInfo(uint32 _season, uint32 _index) external view returns ( uint outTokenID, uint32 outStrength ) { require(_index < 8); uint key = _season * 1000 + _index; Fighter storage soldier = soldiers[key]; require(soldier.strength > 0); outTokenID = soldier.tokenID; outStrength = soldier.strength; } /// @dev process a combat /// @param _season The round for combat /// @param _seed The seed from the users function processOneCombat(uint32 _season, uint32 _seed) external onlyCOO { uint[] memory powers = new uint[](8); uint sumPower = 0; uint i = 0; uint key = 0; for (i = 0; i < 8; i++) { key = _season * 1000 + i; Fighter storage soldier = soldiers[key]; powers[i] = soldier.strength; sumPower = sumPower + soldier.strength; } uint sumValue = 0; uint tmpPower = 0; for (i = 0; i < 8; i++) { tmpPower = powers[i] ** 5;// sumValue += tmpPower; powers[i] = sumValue; } uint singleDeno = sumPower ** 5; uint randomVal = _getRandom(_seed); uint winner = 0; uint shoot = sumValue * randomVal * 10000000000 / singleDeno / 0xffffffff; for (i = 0; i < 8; i++) { tmpPower = powers[i]; if (shoot <= tmpPower * 10000000000 / singleDeno) { winner = i; break; } } key = _season * 1000 + winner; Fighter storage tmp = soldiers[key]; emit SeasonWinner(_season, tmp.tokenID); } /// @dev give a seed and get a random value between 0 and 0xffffffff. /// @param _seed an uint32 value from users function _getRandom(uint32 _seed) pure internal returns(uint32) { return uint32(keccak256(_seed)); } }
get fighter property
function getFighterInfo(uint32 _season, uint32 _index) external view returns ( uint outTokenID, uint32 outStrength ) { require(_index < 8); uint key = _season * 1000 + _index; Fighter storage soldier = soldiers[key]; require(soldier.strength > 0); outTokenID = soldier.tokenID; outStrength = soldier.strength; }
10,140,694
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; 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)); } } abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } // File: openzeppelin-solidity\contracts\token\ERC20\IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: 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. * * [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); } } } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } contract fKISHU is IERC20, ReentrancyGuard { using Address for address; using SafeMath for uint256; enum TxType { FromExcluded, ToExcluded, BothExcluded, Standard } mapping (address => uint256) private rTokenBalance; mapping (address => uint256) private tTokenBalance; mapping (address => mapping (address => uint256)) private _allowances; EnumerableSet.AddressSet excluded; uint256 private tTokenSupply; uint256 private rTokenSupply; uint256 private feesAccrued; string private _name = 'FEG Wrapped KISHU Token'; string private _symbol = 'fKISHU'; uint8 private _decimals = 9; address private op; address private op2; address public tContract = 0xA2b4C0Af19cC16a6CfAcCe81F192B024d625817D; event Deposit(address indexed dst, uint amount); event Withdrawal(address indexed src, uint amount); constructor () { op = address(0x4c9BC793716e8dC05d1F48D8cA8f84318Ec3043C); op2 = op; EnumerableSet.add(excluded, address(0)); // stablity - zen. emit Transfer(address(0), msg.sender, 0); } 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 tTokenSupply; } function balanceOf(address account) public view override returns (uint256) { if (EnumerableSet.contains(excluded, account)) return tTokenBalance[account]; (uint256 r, uint256 t) = currentSupply(); return (rTokenBalance[account] * t) / r; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender] - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue); return true; } function isExcluded(address account) public view returns (bool) { return EnumerableSet.contains(excluded, account); } function totalFees() public view returns (uint256) { return feesAccrued; } function ClaimOPfee() public { require (msg.sender == op); uint256 transferToAmount = (IERC20(tContract).balanceOf(address(this))) - (tTokenSupply); _pushUnderlying(tContract, op, transferToAmount); tTokenSupply -= transferToAmount; } function deposit(uint256 _amount) public { require(_amount > 0, "can't deposit nothing"); _pullUnderlying(tContract, msg.sender, _amount); (uint256 r, uint256 t) = currentSupply(); uint256 fee = _amount / 100; uint256 df = fee / 10; uint256 net = fee != 0 ? (_amount - (fee)) : _amount; tTokenSupply += _amount; if(isExcluded(msg.sender)){ tTokenBalance[msg.sender] += (_amount- fee); } feesAccrued += df; rTokenBalance[op] += ((df * r) / t); rTokenSupply += (((net + df) * r) / t); rTokenBalance[msg.sender] += ((net * r) / t); emit Deposit(msg.sender, _amount); } function _pullUnderlying(address erc20, address from, uint amount) internal nonReentrant { bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer, "ERR_ERC20_FALSE"); } function withdraw(uint256 _amount) public { require(balanceOf(msg.sender) >= _amount && _amount <= totalSupply(), "invalid _amount"); (uint256 r, uint256 t) = currentSupply(); uint256 fee = _amount / 100; uint256 wf = fee / 10; uint256 net = _amount - fee; if(isExcluded(msg.sender)) { tTokenBalance[msg.sender] -= _amount; rTokenBalance[msg.sender] -= ((_amount * r) / t); } else { rTokenBalance[msg.sender] -= ((_amount * r) / t); } tTokenSupply -= (net + wf); rTokenSupply -= (((net + wf) * r ) / t); rTokenBalance[op] += ((wf * r) / t); feesAccrued += wf; _pushUnderlying(tContract, msg.sender, net); emit Withdrawal(msg.sender, net); } function _pushUnderlying(address erc20, address to, uint amount) internal nonReentrant { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "ERR_ERC20_FALSE"); } function rTokenToEveryone(uint256 amt) public { require(!isExcluded(msg.sender), "not allowed"); (uint256 r, uint256 t) = currentSupply(); rTokenBalance[msg.sender] -= ((amt * r) / t); rTokenSupply -= ((amt * r) / t); feesAccrued += amt; } function excludeFromFees(address account) external { require(msg.sender == op2, "op only"); require(!EnumerableSet.contains(excluded, account), "address excluded"); if(rTokenBalance[account] > 0) { (uint256 r, uint256 t) = currentSupply(); tTokenBalance[account] = (rTokenBalance[account] * (t)) / (r); } EnumerableSet.add(excluded, account); } function includeInFees(address account) external { require(msg.sender == op2, "op only"); require(EnumerableSet.contains(excluded, account), "address excluded"); tTokenBalance[account] = 0; EnumerableSet.remove(excluded, account); } function tTokenFromrToken(uint256 rTokenAmount) external view returns (uint256) { (uint256 r, uint256 t) = currentSupply(); return (rTokenAmount * t) / r; } function _approve(address owner, address spender, uint256 amount) private { 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 getTtype(address sender, address recipient) internal view returns (TxType t) { bool isSenderExcluded = EnumerableSet.contains(excluded, sender); bool isRecipientExcluded = EnumerableSet.contains(excluded, recipient); if (isSenderExcluded && !isRecipientExcluded) { t = TxType.FromExcluded; } else if (!isSenderExcluded && isRecipientExcluded) { t = TxType.ToExcluded; } else if (!isSenderExcluded && !isRecipientExcluded) { t = TxType.Standard; } else if (isSenderExcluded && isRecipientExcluded) { t = TxType.BothExcluded; } else { t = TxType.Standard; } return t; } function _transfer(address sender, address recipient, uint256 amt) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amt > 0, "Transfer amt must be greater than zero"); (uint256 r, uint256 t) = currentSupply(); uint256 fee = amt / 100; TxType tt = getTtype(sender, recipient); if (tt == TxType.ToExcluded) { rTokenBalance[sender] -= ((amt * r) / t); tTokenBalance[recipient] += (amt - fee); rTokenBalance[recipient] += (((amt - fee) * r) / t); } else if (tt == TxType.FromExcluded) { tTokenBalance[sender] -= (amt); rTokenBalance[sender] -= ((amt * r) / t); rTokenBalance[recipient] += (((amt - fee) * r) / t); } else if (tt == TxType.BothExcluded) { tTokenBalance[sender] -= (amt); rTokenBalance[sender] -= ((amt * r) / t); tTokenBalance[recipient] += (amt - fee); rTokenBalance[recipient] += (((amt - fee) * r) / t); } else { rTokenBalance[sender] -= ((amt * r) / t); rTokenBalance[recipient] += (((amt - fee) * r) / t); } rTokenSupply -= ((fee * r) / t); feesAccrued += fee; emit Transfer(sender, recipient, amt - fee); } function currentSupply() public view returns(uint256, uint256) { if(rTokenSupply == 0 || tTokenSupply == 0) return (1000000000, 1); uint256 rSupply = rTokenSupply; uint256 tSupply = tTokenSupply; for (uint256 i = 0; i < EnumerableSet.length(excluded); i++) { if (rTokenBalance[EnumerableSet.at(excluded, i)] > rSupply || tTokenBalance[EnumerableSet.at(excluded, i)] > tSupply) return (rTokenSupply, tTokenSupply); rSupply -= (rTokenBalance[EnumerableSet.at(excluded, i)]); tSupply -= (tTokenBalance[EnumerableSet.at(excluded, i)]); } if (rSupply < rTokenSupply / tTokenSupply) return (rTokenSupply, tTokenSupply); return (rSupply, tSupply); } function setOp(address opper, address opper2) external { require(msg.sender == op, "only op can call"); op = opper; op2 = opper2; } }
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; }
193,186
pragma solidity ^0.4.21; 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } 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; } } contract Autonomy is Ownable { address public congress; modifier onlyCongress() { require(msg.sender == congress); _; } /** * @dev initialize a Congress contract address for this token * * @param _congress address the congress contract address */ function initialCongress(address _congress) onlyOwner public { require(_congress != address(0)); congress = _congress; } /** * @dev set a Congress contract address for this token * must change this address by the last congress contract * * @param _congress address the congress contract address */ function changeCongress(address _congress) onlyCongress public { require(_congress != address(0)); congress = _congress; } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract OwnerContract is Claimable { Claimable public ownedContract; address internal origOwner; /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function bindContract(address _contract) onlyOwner public returns (bool) { require(_contract != address(0)); ownedContract = Claimable(_contract); origOwner = ownedContract.owner(); // take ownership of the owned contract ownedContract.claimOwnership(); return true; } /** * @dev change the owner of the contract from this contract address to the original one. * */ function transferOwnershipBack() onlyOwner public { ownedContract.transferOwnership(origOwner); ownedContract = Claimable(address(0)); origOwner = address(0); } /** * @dev change the owner of the contract from this contract address to another one. * * @param _nextOwner the contract address that will be next Owner of the original Contract */ function changeOwnershipto(address _nextOwner) onlyOwner public { ownedContract.transferOwnership(_nextOwner); ownedContract = Claimable(address(0)); origOwner = address(0); } } contract MintDRCT is OwnerContract, Autonomy { using SafeMath for uint256; uint256 public TOTAL_SUPPLY_CAP = 1000000000E18; bool public capInitialized = false; address[] internal mainAccounts = [ 0xaD5CcBE3aaB42812aa05921F0513C509A4fb5b67, // tokensale 0xBD37616a455f1054644c27CC9B348CE18D490D9b, // community 0x4D9c90Cc719B9bd445cea9234F0d90BaA79ad629, // foundation 0x21000ec96084D2203C978E38d781C84F497b0edE // miscellaneous ]; uint8[] internal mainPercentages = [30, 40, 15, 15]; mapping (address => uint) internal accountCaps; modifier afterCapInit() { require(capInitialized); _; } /** * @dev set capacity limitation for every main accounts * */ function initialCaps() onlyOwner public returns (bool) { for (uint i = 0; i < mainAccounts.length; i = i.add(1)) { accountCaps[mainAccounts[i]] = TOTAL_SUPPLY_CAP * mainPercentages[i] / 100; } capInitialized = true; return true; } /** * @dev Mint DRC Tokens from one specific wallet addresses * * @param _ind uint8 the main account index * @param _value uint256 the amounts of tokens to be minted */ function mintUnderCap(uint _ind, uint256 _value) onlyOwner afterCapInit public returns (bool) { require(_ind < mainAccounts.length); address accountAddr = mainAccounts[_ind]; uint256 accountBalance = MintableToken(ownedContract).balanceOf(accountAddr); require(_value <= accountCaps[accountAddr].sub(accountBalance)); return MintableToken(ownedContract).mint(accountAddr, _value); } /** * @dev Mint DRC Tokens from serveral specific wallet addresses * * @param _values uint256 the amounts of tokens to be minted */ function mintAll(uint256[] _values) onlyOwner afterCapInit public returns (bool) { require(_values.length == mainAccounts.length); bool res = true; for(uint i = 0; i < _values.length; i = i.add(1)) { res = mintUnderCap(i, _values[i]) && res; } return res; } /** * @dev Mint DRC Tokens from serveral specific wallet addresses upto cap limitation * */ function mintUptoCap() onlyOwner afterCapInit public returns (bool) { bool res = true; for(uint i = 0; i < mainAccounts.length; i = i.add(1)) { require(MintableToken(ownedContract).balanceOf(mainAccounts[i]) == 0); res = MintableToken(ownedContract).mint(mainAccounts[i], accountCaps[mainAccounts[i]]) && res; } require(res); return MintableToken(ownedContract).finishMinting(); // when up to cap limit, then stop minting. } /** * @dev raise the supply capacity of one specific wallet addresses * * @param _ind uint the main account index * @param _value uint256 the amounts of tokens to be added to capacity limitation */ function raiseCap(uint _ind, uint256 _value) onlyCongress afterCapInit public returns (bool) { require(_ind < mainAccounts.length); require(_value > 0); accountCaps[mainAccounts[_ind]] = accountCaps[mainAccounts[_ind]].add(_value); return true; } /** * @dev query the main account address of one type * * @param _ind the index of the main account */ function getMainAccount(uint _ind) public view returns (address) { require(_ind < mainAccounts.length); return mainAccounts[_ind]; } /** * @dev query the supply capacity of one type of main account * * @param _ind the index of the main account */ function getAccountCap(uint _ind) public view returns (uint256) { require(_ind < mainAccounts.length); return accountCaps[mainAccounts[_ind]]; } /** * @dev set one type of main account to another address * * @param _ind the main account index * @param _newAddr address the new main account address */ function setMainAccount(uint _ind, address _newAddr) onlyOwner public returns (bool) { require(_ind < mainAccounts.length); require(_newAddr != address(0)); mainAccounts[_ind] = _newAddr; return true; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } }
initialize a Congress contract address for this token _congress address the congress contract address/
function initialCongress(address _congress) onlyOwner public { require(_congress != address(0)); congress = _congress; }
1,962,639
pragma solidity 0.6.6; // uniswap router address = 0xcDbE04934d89e97a24BCc07c3562DC8CF17d8167; // daiAddress = 0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa; // cdaiAddress = 0x6D7F0754FFeb405d23C51CE938289d4835bE3b14; // import "github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol"; // import "github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; // import "github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; // import "github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol"; // import "github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; interface ICERC20 { function mint(uint256) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external returns (uint256); function redeem(uint256) external returns (uint256); function redeemUnderlying(uint256) external returns (uint256); function getCash() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address account) external returns (uint256); } /** * @title The Lottery contract * @author Brennan Fife * @notice This contract will allow users to enter a new lottery. * Open - A period where users can join the lottery * Committing - A period where savings will accrue interest * Rewarding - The final stage in which a user is selected */ contract LotteryPot is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint256; IERC20 public underlying; ICERC20 public cToken; uint256 public creationTime; uint256 public potsDaiBalance; address public winningAddress; uint256 public winningsAmount; address[] public entrants; mapping(address => uint256) private entrantBalance; mapping(address => uint256) private entryList; enum States {OPEN, COMMITTING, REWARDING} States public state; bool hasNotBeenRewarded; // EVENTS event EntrantEntered(address indexed sender); event EntrantWithdrawn(address indexed sender, uint256 amount); event StateChange(States state); event WinnerSelected(address indexed winner); event LogValue(string, uint256); event ReceiveFallback(address); event WinnerWinnings(uint256); // MODIFIERS modifier checkState(States currentState) { require( state == currentState, "function cannot be called at this time" ); _; } // modifier checkIfWinnerDeclared() { // require( // entrants.length >= 2, // "There must be at least 2 players in the current lottery" // ); // _; // } modifier requiredTimePassed { require((now - creationTime) > 4 weeks, "4 weeks must have passed"); //block.timestamp _; } modifier minAmount { require( msg.value >= 100 finney, "Must submit at least 100 finney worth of Eth" ); _; } modifier canWithdraw { require( entrantBalance[msg.sender] > 0, "Entrant has nothing to withdraw" ); _; } modifier winnerNotDeclared() { require(hasNotBeenRewarded, "Winner has been declared"); _; } constructor(address _owner, address _daiAddress, address _cdaiAddress) public payable { state = States.OPEN; creationTime = 0; winningsAmount = 0; if (_owner != msg.sender) { transferOwnership(_owner); } underlying = IERC20(_daiAddress); cToken = ICERC20(_cdaiAddress); hasNotBeenRewarded = true; } // function deposit(uint256 daiAmount, address daiAddress, address cdaiAddress) function deposit(uint256 daiAmount) public checkState(States.OPEN) whenNotPaused nonReentrant { underlying = IERC20(0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa); cToken = ICERC20(0x6D7F0754FFeb405d23C51CE938289d4835bE3b14); // underlying = IERC20(daiAddress); // cToken = ICERC20(cdaiAddress); require( underlying.balanceOf(msg.sender) >= daiAmount, "Requested Dai deposit is greater than current balance" ); require(daiAmount >= 10000000000000000000, "Must save at least 10 Dai"); require( underlying.transferFrom(msg.sender, address(this), daiAmount), "Transfer DAI failed" ); if (entrantBalance[msg.sender] == 0) entrants.push(msg.sender); entryList[msg.sender] = entrants.length.add(1); emit EntrantEntered(msg.sender); entrantBalance[msg.sender] = entrantBalance[msg.sender].add(daiAmount); //potsDaiBalance = potsDaiBalance.add(daiAmount); mint( daiAmount, 0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa, 0x6D7F0754FFeb405d23C51CE938289d4835bE3b14 ); } // nonReentrant canWithdraw // function withdraw(uint256 amount) public { // cToken = ICERC20(0x6D7F0754FFeb405d23C51CE938289d4835bE3b14); // // require( // // state != States.COMMITTING, // // "Cannot withdraw during committing period" // // ); // uint256 balance = entrantBalance[msg.sender]; // //require(balance >= amount, "Taking out too much"); // entrantBalance[msg.sender] = balance.sub(amount); // potsDaiBalance = potsDaiBalance.sub(amount); // //cToken.redeemUnderlying(amount) == 0; // msg.sender.transfer(amount); // emit EntrantWithdrawn(msg.sender, amount); // } function withdraw(uint256 amount) public { _withdraw(msg.sender, amount); } function _withdraw(address sender, uint256 amount) private { underlying = IERC20(0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa); cToken = ICERC20(0x6D7F0754FFeb405d23C51CE938289d4835bE3b14); uint256 balance = entrantBalance[msg.sender]; require(balance >= amount, "Taking out too much"); entrantBalance[sender] = balance.sub(amount); potsDaiBalance = potsDaiBalance.sub(amount); require(cToken.redeemUnderlying(amount) == 0, "Redeem"); require(underlying.transfer(sender, amount), "Transfer"); } //nonReentrant function mint( uint256 _numberOfDaiToSupply, address daiAddress, address cDaiAddress ) private { underlying = IERC20(daiAddress); cToken = ICERC20(cDaiAddress); require( underlying.approve(address(cToken), _numberOfDaiToSupply), "Failed to approve sending token" ); require( cToken.mint(_numberOfDaiToSupply) == 0, "Failed to mint cToken" ); potsDaiBalance = potsDaiBalance.add(_numberOfDaiToSupply); } function lockLottery() public whenNotPaused onlyOwner { require((now - creationTime) > 2 weeks, "Two weeks must have passed"); //block.timestamp incrementState(); } function incrementState() public whenNotPaused onlyOwner { require(uint256(state) < 2, "state cannot be incremented"); state = States(uint256(state) + 1); emit StateChange(state); } function selectWinnerAndReward() public checkState(States.COMMITTING) onlyOwner winnerNotDeclared { selectWinner(); reward(); // incrementState(); hasNotBeenRewarded = false; } function selectWinner() public onlyOwner returns (address) { uint256 reducer = getRandomNumber(potsDaiBalance); uint256 i = 0; while (reducer > entrantBalance[entrants[i]]) { reducer = reducer.sub(entrantBalance[entrants[i]]); i += 1; } // require(entrants[i] != address(0)); winningAddress = entrants[i]; emit WinnerSelected(winningAddress); return winningAddress; } // checkState(States.REWARDING) function reward() private whenNotPaused returns (uint256) { uint256 underlyingBalance = cToken.balanceOfUnderlying(address(this)); //dai held in compound if (underlyingBalance > potsDaiBalance) { winningsAmount = underlyingBalance.sub(potsDaiBalance); } if (winningAddress != address(0) && winningsAmount != 0) { potsDaiBalance = underlyingBalance; entrantBalance[winningAddress] = entrantBalance[winningAddress].add( winningsAmount ); emit WinnerWinnings(winningsAmount); } } function getRandomNumber(uint256 entropy) private view returns (uint256) { return uint256( keccak256( abi.encodePacked( block.timestamp, block.number, block.difficulty ) ) ) .mod(entropy); } function redeemDaiFromCompound() public onlyOwner returns (uint256) { uint256 targetRedeemTargetTokenAmount = cToken.balanceOf(address(this)); uint256 redeemResult = cToken.redeem(targetRedeemTargetTokenAmount); emit LogValue("redeem result", redeemResult); return redeemResult; } function removeEntrant() private { entrants[entryList[msg.sender]] = entrants[entrants.length - 1]; entryList[msg.sender] = 0; if (entrants.length > 1) entrants.pop(); else entrants[0] = owner(); } function getLotterySize() public view returns (uint256) { return entrants.length; } function accountBalance(address entrantAddress) public view returns (uint256) { return (entrantBalance[entrantAddress]); } function disableContract() public onlyOwner returns (bool) { _pause(); } receive() external payable {} fallback() external payable { emit ReceiveFallback(address(msg.sender)); } }
function deposit(uint256 daiAmount, address daiAddress, address cdaiAddress) underlying = IERC20(daiAddress); cToken = ICERC20(cdaiAddress);potsDaiBalance = potsDaiBalance.add(daiAmount);
function deposit(uint256 daiAmount) public checkState(States.OPEN) whenNotPaused nonReentrant { underlying = IERC20(0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa); cToken = ICERC20(0x6D7F0754FFeb405d23C51CE938289d4835bE3b14); require( underlying.balanceOf(msg.sender) >= daiAmount, "Requested Dai deposit is greater than current balance" ); require(daiAmount >= 10000000000000000000, "Must save at least 10 Dai"); require( underlying.transferFrom(msg.sender, address(this), daiAmount), "Transfer DAI failed" ); if (entrantBalance[msg.sender] == 0) entrants.push(msg.sender); entryList[msg.sender] = entrants.length.add(1); emit EntrantEntered(msg.sender); entrantBalance[msg.sender] = entrantBalance[msg.sender].add(daiAmount); mint( daiAmount, 0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa, 0x6D7F0754FFeb405d23C51CE938289d4835bE3b14 ); }
13,031,412
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionVault interface /// @author Enzyme Council <[email protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[email protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function canDisable() external pure returns (bool canDisable_); function identifier() external pure returns (string memory identifier_); function implementedHooks() external pure returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { // When updating PolicyHook, also update these functions in PolicyManager: // 1. __getAllPolicyHooks() // 2. __policyHookRestrictsCurrentInvestorActions() enum PolicyHook { PostBuyShares, PostCallOnIntegration, PreTransferShares, RedeemSharesForSpecificAssets, AddTrackedAssets, RemoveTrackedAssets, CreateExternalPosition, PostCallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds /// @dev Any arbitrary fee is allowed by default, so all participants must be aware of /// their fund's configuration, especially whether they use official policies only. /// Policies that restrict current investors can only be added upon fund setup, migration, or reconfiguration. /// Policies that restrict new investors or asset management actions can be added at any time. /// Policies themselves specify whether or not they are allowed to be updated or removed. contract PolicyManager is IPolicyManager, ExtensionBase, GasRelayRecipientMixin { using AddressArrayLib for address[]; event PolicyDisabledOnHookForFund( address indexed comptrollerProxy, address indexed policy, PolicyHook indexed hook ); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); uint256 private constant POLICY_HOOK_COUNT = 10; mapping(address => mapping(PolicyHook => address[])) private comptrollerProxyToHookToPolicies; modifier onlyFundOwner(address _comptrollerProxy) { require( __msgSender() == IVault(getVaultProxyForFund(_comptrollerProxy)).getOwner(), "Only the fund owner can call this function" ); _; } constructor(address _fundDeployer, address _gasRelayPaymasterFactory) public ExtensionBase(_fundDeployer) GasRelayRecipientMixin(_gasRelayPaymasterFactory) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev There will be no enabledPolicies if the caller is not a valid ComptrollerProxy function activateForFund(bool _isMigratedFund) external override { address comptrollerProxy = msg.sender; // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(comptrollerProxy); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(comptrollerProxy, enabledPolicies[i]); } } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable /// @dev If an arbitrary policy changes its `implementedHooks()` return values after it is /// already enabled on a fund, then this will not correctly disable the policy from any /// removed hook values. function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyFundOwner(_comptrollerProxy) { require(IPolicy(_policy).canDisable(), "disablePolicyForFund: _policy cannot be disabled"); PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks(); for (uint256 i; i < implementedHooks.length; i++) { bool disabled = comptrollerProxyToHookToPolicies[_comptrollerProxy][implementedHooks[i]] .removeStorageItem(_policy); if (disabled) { emit PolicyDisabledOnHookForFund(_comptrollerProxy, _policy, implementedHooks[i]); } } } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyFundOwner(_comptrollerProxy) { PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks(); for (uint256 i; i < implementedHooks.length; i++) { require( !__policyHookRestrictsCurrentInvestorActions(implementedHooks[i]), "enablePolicyForFund: _policy restricts actions of current investors" ); } __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData, implementedHooks); __activatePolicyForFund(_comptrollerProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _configData Encoded config data function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external override onlyFundDeployer { __setValidatedVaultProxy(_comptrollerProxy, _vaultProxy); // In case there are no policies yet if (_configData.length == 0) { return; } (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund( _comptrollerProxy, policies[i], settingsData[i], IPolicy(policies[i]).implementedHooks() ); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyFundOwner(_comptrollerProxy) { IPolicy(_policy).updateFundSettings(_comptrollerProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { // Return as quickly as possible if no policies to run address[] memory policies = getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook); if (policies.length == 0) { return; } // Limit calls to trusted components, in case policies update local storage upon runs require( msg.sender == _comptrollerProxy || msg.sender == IComptroller(_comptrollerProxy).getIntegrationManager() || msg.sender == IComptroller(_comptrollerProxy).getExternalPositionManager(), "validatePolicies: Caller not allowed" ); for (uint256 i; i < policies.length; i++) { require( IPolicy(policies[i]).validateRule(_comptrollerProxy, _hook, _validationData), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund(address _comptrollerProxy, address _policy) private { IPolicy(_policy).activateForFund(_comptrollerProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData, PolicyHook[] memory _hooks ) private { // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy for (uint256 i; i < _hooks.length; i++) { require( !policyIsEnabledOnHookForFund(_comptrollerProxy, _hooks[i], _policy), "__enablePolicyForFund: Policy is already enabled" ); comptrollerProxyToHookToPolicies[_comptrollerProxy][_hooks[i]].push(_policy); } emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to get all the hooks available to policies function __getAllPolicyHooks() private pure returns (PolicyHook[POLICY_HOOK_COUNT] memory hooks_) { return [ PolicyHook.PostBuyShares, PolicyHook.PostCallOnIntegration, PolicyHook.PreTransferShares, PolicyHook.RedeemSharesForSpecificAssets, PolicyHook.AddTrackedAssets, PolicyHook.RemoveTrackedAssets, PolicyHook.CreateExternalPosition, PolicyHook.PostCallOnExternalPosition, PolicyHook.RemoveExternalPosition, PolicyHook.ReactivateExternalPosition ]; } /// @dev Helper to check if a policy hook restricts the actions of current investors. /// These hooks should not allow policy additions post-deployment or post-migration. function __policyHookRestrictsCurrentInvestorActions(PolicyHook _hook) private pure returns (bool restrictsActions_) { return _hook == PolicyHook.PreTransferShares || _hook == PolicyHook.RedeemSharesForSpecificAssets; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled policies for the given fund /// @param _comptrollerProxy The ComptrollerProxy /// @return enabledPolicies_ The array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { PolicyHook[POLICY_HOOK_COUNT] memory hooks = __getAllPolicyHooks(); for (uint256 i; i < hooks.length; i++) { enabledPolicies_ = enabledPolicies_.mergeArray( getEnabledPoliciesOnHookForFund(_comptrollerProxy, hooks[i]) ); } return enabledPolicies_; } /// @notice Get a list of enabled policies that run on a given hook for the given fund /// @param _comptrollerProxy The ComptrollerProxy /// @param _hook The PolicyHook /// @return enabledPolicies_ The array of enabled policy addresses function getEnabledPoliciesOnHookForFund(address _comptrollerProxy, PolicyHook _hook) public view returns (address[] memory enabledPolicies_) { return comptrollerProxyToHookToPolicies[_comptrollerProxy][_hook]; } /// @notice Check whether a given policy runs on a given hook for a given fund /// @param _comptrollerProxy The ComptrollerProxy /// @param _hook The PolicyHook /// @param _policy The policy /// @return isEnabled_ True if the policy is enabled function policyIsEnabledOnHookForFund( address _comptrollerProxy, PolicyHook _hook, address _policy ) public view returns (bool isEnabled_) { return getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook).contains(_policy); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/FundDeployerOwnerMixin.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension, FundDeployerOwnerMixin { event ValidatedVaultProxySetForFund( address indexed comptrollerProxy, address indexed vaultProxy ); mapping(address => address) internal comptrollerProxyToVaultProxy; modifier onlyFundDeployer() { require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call"); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund( address, address, bytes calldata ) external virtual override { return; } /// @dev Helper to store the validated ComptrollerProxy-VaultProxy relation function __setValidatedVaultProxy(address _comptrollerProxy, address _vaultProxy) internal { comptrollerProxyToVaultProxy[_comptrollerProxy] = _vaultProxy; emit ValidatedVaultProxySetForFund(_comptrollerProxy, _vaultProxy); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "./IGasRelayPaymaster.sol"; pragma solidity 0.6.12; /// @title GasRelayRecipientMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin that enables receiving GSN-relayed calls /// @dev IMPORTANT: Do not use storage var in this contract, /// unless it is no longer inherited by the VaultLib abstract contract GasRelayRecipientMixin { address internal immutable GAS_RELAY_PAYMASTER_FACTORY; constructor(address _gasRelayPaymasterFactory) internal { GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory; } /// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed function __msgSender() internal view returns (address payable canonicalSender_) { if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) { assembly { canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20))) } return canonicalSender_; } return msg.sender; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable /// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value function getGasRelayPaymasterFactory() public view returns (address gasRelayPaymasterFactory_) { return GAS_RELAY_PAYMASTER_FACTORY; } /// @notice Gets the trusted forwarder for GSN relaying /// @return trustedForwarder_ The trusted forwarder function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) { return IGasRelayPaymaster( IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib() ) .trustedForwarder(); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IGsnPaymaster.sol"; /// @title IGasRelayPaymaster Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymaster is IGsnPaymaster { function deposit() external; function withdrawBalance() external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGsnForwarder interface /// @author Enzyme Council <[email protected]> interface IGsnForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnPaymaster interface /// @author Enzyme Council <[email protected]> interface IGsnPaymaster { struct GasAndDataLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; uint256 calldataSizeLimit; } function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits); function getHubAddr() external view returns (address); function getRelayHubDeposit() external view returns (uint256); function preRelayedCall( IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, IGsnTypes.RelayData calldata relayData ) external; function trustedForwarder() external view returns (address); function versionPaymaster() external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnForwarder.sol"; /// @title IGsnTypes Interface /// @author Enzyme Council <[email protected]> interface IGsnTypes { struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } struct RelayRequest { IGsnForwarder.ForwardRequest request; RelayData relayData; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
Allows extension to run logic during fund activation Unimplemented by default, may be overridden.
function activateForFund(bool) external virtual override { return; }
181,835
/** *Submitted for verification at Etherscan.io on 2022-02-21 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity 0.8.11; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: MutationAnimalToken.sol contract MutationAnimal is ERC1155, Ownable { using Strings for uint256; //----Event---- event SetBaseURI(string indexed _baseURI); //----Struct---- struct MutationDetail{ uint256 animalLevel; uint256 animalType; } //-----Variable----- string private _name; string private _symbol; address public dinoContract; string private baseURI; mapping(uint256 => bool) public validAnimalTypes; mapping (uint256 => MutationDetail) public mutationDetails; constructor( string memory _mutantName, string memory _mutantSymbol, string memory _baseURI ) ERC1155(_baseURI) { _name = _mutantName; _symbol = _mutantSymbol; baseURI = _baseURI; validAnimalTypes[0] = true; validAnimalTypes[1] = true; validAnimalTypes[2] = true; emit SetBaseURI(baseURI); } //------Admin----- ///@notice mint the nft in batch ///@param ids: ids tokens id to mint ///@param amounts: amounts of tokens to mint ///@param levels: level of tokens to mint ///@param types: types of tokens to mint function mintBatch(uint256[] memory ids, uint256[] memory amounts, uint256[] memory levels, uint256[] memory types) external onlyOwner { _mintBatch(owner(), ids, amounts, ""); for(uint256 i=0; i<ids.length; i++){ MutationDetail memory currentMutationDetail = MutationDetail({ animalType: types[i], animalLevel: levels[i] }); mutationDetails[ids[i]] = currentMutationDetail; } } ///@notice add valid mutation animal types ///@param ids ids to add function addValidMutationAnimals(uint256[] memory ids) external onlyOwner { for(uint256 i=0; i<ids.length; i++){ validAnimalTypes[ids[i]] = true; } } ///@notice remove valid mutation animal types ///@param ids ids to remove function removeValidMutationAnimals(uint256[] memory ids) external onlyOwner { for(uint256 i=0; i<ids.length; i++){ validAnimalTypes[ids[i]] = false; } } ///@notice set the dino contract address ///@param dinoContractAddress contract address to set for the dino function setdinoContractAddress(address dinoContractAddress) external onlyOwner { dinoContract = dinoContractAddress; } ///@notice update base uri for the nft ///@param _baseURI base uri for the nft function updateBaseUri(string memory _baseURI) external onlyOwner { baseURI = _baseURI; emit SetBaseURI(baseURI); } //---User----- ///@notice called by the dino contract to burn the mutant animal ///@param typeId type of animal to burn i.e. animal nft id ///@param burnTokenAddress token mutator function burnSerumForAddress(uint256 typeId, address burnTokenAddress) external { require(msg.sender == dinoContract, "AnimalNFT: Cannot mutate other than Dino!"); require(validAnimalTypes[typeId], "AnimalNFT: Cannot mutate from non-valid serum!"); _burn(burnTokenAddress, typeId, 1); } //---View--- function getChemicalLevel(uint256 _id) external view returns(uint256){ return mutationDetails[_id].animalLevel; } function getChemicalType(uint256 _id) external view returns(uint256){ return mutationDetails[_id].animalType; } function uri(uint256 typeId) public view override returns (string memory) { require( validAnimalTypes[typeId], "URI requested for invalid serum type" ); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, typeId.toString(), '.json')) : baseURI; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: DeadDino.sol pragma solidity 0.8.11; interface IBone20 { // called when minting many NFTs // updated_amount = (balanceOf(user) * base_rate * delta / 86400) function updateRewardOnMint(address _user) external; // called on transfer function updateReward(address _from, address _to) external; function getReward(address _to) external; function burn(address _from, uint256 _amount) external; function getTotalClaimable(address _user) external view returns(uint256); } contract DeadDino is ERC721, Ownable { using Strings for uint256; using SafeMath for uint256; address public constant burn = address(0); string public baseUri; uint256 public maxSupply = 500; uint256 public dinoCount; address public yieldBone; MutationAnimal public mnft; string[] public mutationBaseUri = [ 'ipfs://a/', 'ipfs://b/', 'ipfs://c/', 'ipfs://d/', 'ipfs://e/', 'ipfs://f/', 'ipfs://g/', 'ipfs://h/', 'ipfs://i/', 'ipfs://j/', 'ipfs://k/', 'ipfs://l/' ]; //------Events----- event DinoAscended(uint256 tokenId); event MutationDone(address mutator, uint256 id, uint256 checmicalId, uint256 time); //------Struct----- struct MutationDetails{ uint256 mutationTypes; // mutation type 0,1,2,3 splicing uint256 mutationLevel; // mutation level 0,1,2,3 splicing } //------Variables---- mapping (uint256 => bool) public mutationStatus; mapping (uint256 => MutationDetails) public mutationDetails; mapping (uint256 => bool) public mutation; mapping (address => bool) public genesisTrasnsferer; constructor(uint256 _currentSupply, string memory _baseUri, address _mutationNFT ) ERC721("DeadDino","DEAD DINO") { // _setBaseURI("ipfs://QmaGqAY21r2EGRsMb8VFbPyRbqcveroeL6rKsmtzVsqAtZ/"); _setBaseURI(_baseUri); mnft = MutationAnimal(_mutationNFT); batchMintNFT(_currentSupply); } //-----Admin Function---- ///@notice update the uri for the token ///@param newURI new uri function updateURI(string memory newURI) public onlyOwner { _setBaseURI(newURI); } ///@notice set yield token ///@param _yield new yield bone token function setYieldToken(address _yield) external onlyOwner { yieldBone = _yield; } ///@notice set base uri ///@param _baseURI base uri for the nft function _setBaseURI(string memory _baseURI) internal { baseUri = _baseURI; } ///@notice set mutation base uri ///@param _mutationBaseUris set mutation base uri function setmutationBaseURi(string[] memory _mutationBaseUris) external onlyOwner { mutationBaseUri = _mutationBaseUris; } ///@notice mint nft function mintNFT() public onlyOwner { require(dinoCount <= maxSupply, "NFT: Cannot mint more than total Supply!"); dinoCount++; uint256 _tokenId = dinoCount; _mint(msg.sender, _tokenId); } ///@notice batch mint nft ///@param totalNumber nft number to mint function batchMintNFT(uint256 totalNumber) public onlyOwner { for(uint256 i=0;i < totalNumber; i++){ mintNFT(); } } ///@notice add the genisis trader like marketplace or other first distributor addresses ///@param genesisTrader genesis trader address function addGenesisTrader(address genesisTrader) external onlyOwner{ genesisTrasnsferer[genesisTrader] = true; } ///@notice remoce the genesis trader ///@param genesisTrader genisis trader address function removeGenesisTrader(address genesisTrader) external onlyOwner{ genesisTrasnsferer[genesisTrader] = false; } ///@notice animal mutation nft update ///@param _mnft mutation nft address function updateMNFT(address _mnft) external onlyOwner{ mnft = MutationAnimal(_mnft); } //-----View Function---- function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentUri = baseUri; if(mutationStatus[tokenId]){ MutationDetails memory details = mutationDetails[tokenId]; uint256 mutationType = details.mutationTypes; uint256 mutationLevel = details.mutationLevel; uint256 tokenUriIndex = mutationLevel.mul(4).add(mutationType); currentUri = mutationBaseUri[tokenUriIndex]; } return bytes(baseUri).length > 0 ? string(abi.encodePacked(currentUri, tokenId.toString(), ".json")) : ""; } //-----User function---- ///@notice function called to get the reward bones function getReward() external{ IBone20(yieldBone).updateReward(msg.sender, address(0)); IBone20(yieldBone).getReward(msg.sender); } ///@notice function called to get the ///@param nftId nft id to mutate ///@param animalId id for animal to mutate with function mutateNFT(uint256 nftId, uint256 animalId) public { if(!mutationStatus[nftId]) mutationStatus[nftId] = true; mnft.burnSerumForAddress(animalId, msg.sender); uint256 levels = mnft.getChemicalLevel(animalId); uint256 types = mnft.getChemicalType(animalId); mutationDetails[nftId].mutationLevel = levels; mutationDetails[nftId].mutationTypes = types; emit MutationDone(msg.sender, nftId, animalId, block.timestamp); } //---Override---- function transferFrom(address from, address to, uint256 tokenId) public override { //sender was the owner //it replicats that the NFT was sold from the Opensea / Owner to the user now it will be rewarded if(from == owner() || genesisTrasnsferer[from]){ IBone20(yieldBone).updateRewardOnMint(to); emit DinoAscended(tokenId); }else{ IBone20(yieldBone).updateReward(from, to); } _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { //sender was the owner //it means that the NFT was sold from the Opensea / Owner to the user now it will be rewarded if(from == owner() || genesisTrasnsferer[from]){ IBone20(yieldBone).updateRewardOnMint(to); emit DinoAscended(tokenId); }else{ IBone20(yieldBone).updateReward(from, to); } _safeTransfer(from, to, tokenId, _data); } }
set mutation base uri _mutationBaseUris set mutation base uri
function setmutationBaseURi(string[] memory _mutationBaseUris) external onlyOwner { mutationBaseUri = _mutationBaseUris; }
2,103,095
./full_match/5/0x7AbdbE7BD979D3326FD71afAe4858a58B34930C7/sources/lib/redstone-oracles-monorepo/packages/evm-connector/contracts/core/RedstoneConsumerBase.sol
This is an internal helpful function for secure extraction oracle values from the tx calldata. Security is achieved by signatures verification, timestamp validation, and aggregating values from different authorised signers into a single numeric value. If any of the required conditions (e.g. too old timestamp or insufficient number of authorised signers) do not match, the function will revert. Note! You should not call this function in a consumer contract. You can use `getOracleNumericValuesFromTxMsg` or `getOracleNumericValueFromTxMsg` instead. dataFeedIds An array of unique data feed identifiers return An array of the extracted and verified oracle values in the same order as they are requested in dataFeedIds array/ Initializing helpful variables and allocating memory The line below is commented because newly allocated arrays are filled with zeros But we left it for better readability signersBitmapForDataFeedIds[i] = 0; <- setting to an empty bitmap Data packages extraction in a loop Extract data package details and update calldata offset Shifting memory pointer back to the "safe" value
function _securelyExtractOracleValuesFromTxMsg(bytes32[] memory dataFeedIds) internal view returns (uint256[] memory) { uint256[] memory uniqueSignerCountForDataFeedIds = new uint256[](dataFeedIds.length); uint256[] memory signersBitmapForDataFeedIds = new uint256[](dataFeedIds.length); uint256[][] memory valuesForDataFeeds = new uint256[][](dataFeedIds.length); for (uint256 i = 0; i < dataFeedIds.length; i++) { valuesForDataFeeds[i] = new uint256[](getUniqueSignersThreshold()); } uint256 dataPackagesCount = _extractDataPackagesCountFromCalldata(calldataNegativeOffset); calldataNegativeOffset += DATA_PACKAGES_COUNT_BS; assembly { freeMemPtr := mload(FREE_MEMORY_PTR) } for (uint256 dataPackageIndex = 0; dataPackageIndex < dataPackagesCount; dataPackageIndex++) { uint256 dataPackageByteSize = _extractDataPackage( dataFeedIds, uniqueSignerCountForDataFeedIds, signersBitmapForDataFeedIds, valuesForDataFeeds, calldataNegativeOffset ); calldataNegativeOffset += dataPackageByteSize; assembly { mstore(FREE_MEMORY_PTR, freeMemPtr) } } }
1,950,866
pragma solidity 0.5.11; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "./IErc20DepositVerifier.sol"; import {PaymentTransactionModel as DepositTx} from "../../transactions/PaymentTransactionModel.sol"; import {PaymentOutputModel as DepositOutputModel} from "../../transactions/outputs/PaymentOutputModel.sol"; /** * @notice Implementation of Erc20 deposit verifier using payment transaction as the deposit tx */ contract Erc20DepositVerifier is IErc20DepositVerifier { using DepositOutputModel for DepositOutputModel.Output; uint256 public depositTxType; uint256 public supportedOutputType; constructor(uint256 txType, uint256 outputType) public { depositTxType = txType; supportedOutputType = outputType; } /** * @notice Overrides the function of IErc20DepositVerifier and implements the verification logic * for payment transaction * @dev Vault address must be approved to transfer from the sender address before doing the deposit * @return Verified (owner, token, amount) of the deposit ERC20 token data */ function verify(bytes calldata depositTx, address sender, address vault) external view returns ( address owner, address token, uint256 amount ) { DepositTx.Transaction memory decodedTx = DepositTx.decode(depositTx); require(decodedTx.txType == depositTxType, "Invalid transaction type"); require(decodedTx.inputs.length == 0, "Deposit must have no inputs"); require(decodedTx.outputs.length == 1, "Deposit must have exactly one output"); require(decodedTx.outputs[0].token != address(0), "Invalid output currency (ETH)"); require(decodedTx.outputs[0].outputType == supportedOutputType, "Invalid output type"); address depositorsAddress = decodedTx.outputs[0].owner(); require(depositorsAddress == sender, "Depositor's address must match sender's address"); IERC20 erc20 = IERC20(decodedTx.outputs[0].token); require(erc20.allowance(depositorsAddress, vault) == decodedTx.outputs[0].amount, "Tokens have not been approved"); return (depositorsAddress, decodedTx.outputs[0].token, decodedTx.outputs[0].amount); } }
Overrides the function of IErc20DepositVerifier and implements the verification logic for payment transaction Vault address must be approved to transfer from the sender address before doing the deposit return Verified (owner, token, amount) of the deposit ERC20 token data/
function verify(bytes calldata depositTx, address sender, address vault) external view returns ( address owner, address token, uint256 amount ) { DepositTx.Transaction memory decodedTx = DepositTx.decode(depositTx); require(decodedTx.txType == depositTxType, "Invalid transaction type"); require(decodedTx.inputs.length == 0, "Deposit must have no inputs"); require(decodedTx.outputs.length == 1, "Deposit must have exactly one output"); require(decodedTx.outputs[0].token != address(0), "Invalid output currency (ETH)"); require(decodedTx.outputs[0].outputType == supportedOutputType, "Invalid output type"); address depositorsAddress = decodedTx.outputs[0].owner(); require(depositorsAddress == sender, "Depositor's address must match sender's address"); IERC20 erc20 = IERC20(decodedTx.outputs[0].token); require(erc20.allowance(depositorsAddress, vault) == decodedTx.outputs[0].amount, "Tokens have not been approved"); return (depositorsAddress, decodedTx.outputs[0].token, decodedTx.outputs[0].amount); }
897,296
/** *Submitted for verification at Etherscan.io on 2022-04-12 */ // Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/utils/structs/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // 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); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // 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)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // 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 Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/Interfaces/PresaleInterface.sol pragma solidity 0.8.11; interface PresaleInterface is IAccessControlEnumerable { /* solhint-disable */ function ADMIN_ROLE() external pure returns(bytes32); function MODERATOR_ROLE() external pure returns(bytes32); /* solhint-enable */ // ****************************************** // ************* PUBLIC REGION ************** // ****************************************** function contributeFirstStage(address tokenInvested_, uint amountInvested_, bytes memory signature_) external; function contributeSecondStage(address tokenInvested_, uint amountInvested_, bytes memory signature_) external; // ******************************************* // ************* MANAGER REGION ************** // ******************************************* function setMinimumContributionRequierment(uint minimumContributionRequierment_) external returns (bool); function setPresaleCap(uint presaleCap_) external returns (bool); function setFirstStageBlockStart(uint firstStageBlockStart_) external returns (bool); function setFirstStageBlockEnd(uint firstStageBlockEnd_) external returns (bool); function setFirstStageMaxContributorCount(uint firstStageMaxContributorCount_) external returns (bool); function setFirstStageMaxContribution(uint firstStageMaxContribution_) external returns (bool); function setSecondStageBlockStart(uint secondStageBlockStart_) external returns (bool); function setSecondStageBlockEnd(uint secondStageBlockEnd_) external returns (bool); function setSecondStageMaxContribution(uint secondStageMaxContribution_) external returns (bool); function setTokenAllowed(address token_, bool option_) external returns (bool); function setDataInstance(address dataAddress_) external returns (bool); function setCorporateAddress(address corporateAddress_) external returns (bool); // ************************************************* // ************* DEFAULT_ADMIN REGION ************** // ************************************************* function setRoleAdmin(bytes32 role, bytes32 adminRole) external returns (bool); function salvageTokensFromContract(address tokenAddress, address to, uint amount) external returns (bool); function killContract() external returns (bool); // ************************************************** // ************* PUBLIC GETTERS REGION ************** // ************************************************** function getPresaleActive() external view returns (bool); function getFirstStageActive() external view returns (bool); function getSecondStageActive() external view returns (bool); function getFirstStageParticipantMaxContribution(address participant_) external view returns (uint); function getSecondStageParticipantMaxContribution(address participant_) external view returns (uint); function getMinimumContributionRequierment() external view returns (uint); function getPresaleCap() external view returns (uint); function getFirstStageBlockStart() external view returns (uint); function getFirstStageBlockEnd() external view returns (uint); function getFirstStageMaxContributorCount() external view returns (uint); function getFirstStageMaxContribution() external view returns (uint); function getSecondStageBlockStart() external view returns (uint); function getSecondStageBlockEnd() external view returns (uint); function getSecondStageMaxContribution() external view returns (uint); function getTokenAllowed(address token_) external view returns (bool); function getDataAddress() external view returns (address); function getCorporateAddress() external view returns (address); // ****************************************** // ************* EVENTS REGION ************** // ****************************************** event MinimumContributionRequiermentChanged(uint oldValue, uint newValue); event PresaleCapChanged(uint oldValue, uint newValue); event FirstStageBlockStartChanged(uint oldValue, uint newValue); event FirstStageBlockEndChanged(uint oldValue, uint newValue); event FirstStageMaxContributorCountChanged(uint oldValue, uint newValue); event FirstStageMaxContributionChanged(uint oldValue, uint newValue); event SecondStageBlockStartChanged(uint oldValue, uint newValue); event SecondStageBlockEndChanged(uint oldValue, uint newValue); event SecondStageMaxContributionChanged(uint oldValue, uint newValue); event TokenAllowedChanged(bool oldValue, bool newValue); event DataAddressChanged(address oldValue, address newValue); event CorporateAddressChanged(address oldValue, address newValue); event AdminRoleSet(bytes32 role, bytes32 adminRole); event TokensSalvaged(address tokenAddress, address reciever, uint amount); event ContractKilled(); } // File contracts/Interfaces/DataInterface.sol pragma solidity 0.8.11; interface DataInterface is IAccessControlEnumerable{ /* solhint-disable */ function ADMIN_ROLE() external pure returns(bytes32); function MODERATOR_ROLE() external pure returns(bytes32); function SALECONTRACT_ROLE() external pure returns(bytes32); /* solhint-enable */ // ******************************************* // ************* MANAGER REGION ************** // ******************************************* function manuallyWhitelistParticipant(address participant_) external; function manuallyBlacklistParticipant(address participant_) external; function manuallyCreditParticipant(address participant_, address tokenInvested_, uint tokenAmount_) external; function setSignersAddress(address signersAddress_) external returns (bool); function setTokenConversion(uint tokenConversion_) external returns (bool); // ***************************************************** // ************* SALECONTRACT_ROLE REGION ************** // ***************************************************** function whitelistParticipant(address participant_, bytes memory signature_) external; function creditParticipation(address participant_, address tokenInvested_, uint tokenAmount_) external; // ************************************************* // ************* DEFAULT_ADMIN REGION ************** // ************************************************* function setRoleAdmin(bytes32 role, bytes32 adminRole) external returns (bool); function salvageTokensFromContract(address tokenAddress, address to, uint amount) external returns (bool); function killContract() external returns (bool); // ******************************************** // ************* INTERNAL REGION ************** // ******************************************** // ************************************************** // ************* PUBLIC GETTERS REGION ************** // ************************************************** function getParticipantCount() external view returns (uint); function getCombinedContributions() external view returns (uint); function getIsParticipantWhitelisted(address participant_) external view returns (bool); function getParticipantContributions(address participant_) external view returns (uint); function getParticipantList(uint startIndex_, uint endIndex_) external view returns (address[] memory, uint[] memory); function getSignersAddress() external view returns (address); function getMessageHash(address contributor_, bool allowed_) external pure returns (bytes32); function getTokenConversion() external view returns (uint); // ****************************************** // ************* EVENTS REGION ************** // ****************************************** event ContributionMade(address indexed contractAddress, address indexed participant_, address tokenInvested_, uint baseAmount_, uint tokensIssued_); event ParticipantWhitelisted(address participant_); event ParticipantBlacklisted(address participant_); event SignersAddressChanged(address oldValue, address newValue); event TokenConversionChanged(uint oldValue, uint newValue); event AdminRoleSet(bytes32 role, bytes32 adminRole); event TokensSalvaged(address tokenAddress, address reciever, uint amount); event ContractKilled(); } // File contracts/PresaleContract.sol pragma solidity 0.8.11; //import "hardhat/console.sol"; /// @title Authtrail presale contract /// @author Authtrail llc /// @dev Presale contract that serves as an interface for collecting stable coins in presale /// @custom:experimental This is an experimental contract. contract PresaleContract is AccessControlEnumerable, PresaleInterface { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant MODERATOR_ROLE = keccak256("MODERATOR_ROLE"); DataInterface private _dataInstance; address private _corporateAddress; uint private _minimumContributionRequierment = 1000 * 10 ** 6; uint private _presaleCap = 6000000 * 10 ** 6; // TODO: adjust the blocks closer to the crowsale uint private _firstStageBlockStart = 14570950; // https://etherscan.io/block/countdown/14571380 - 12.4 14:00 UTC uint private _firstStageBlockEnd = 14573680; // https://etherscan.io/block/countdown/14573680 - 12.4 23:59 UTC uint private _firstStageMaxContributorCount = 1000; uint private _firstStageMaxContribution = 5000 * 10**6; uint private _secondStageBlockStart = 14584200; // https://etherscan.io/block/countdown/14584200 - 14.4 14:00 UTC uint private _secondStageBlockEnd = 14586600; // https://etherscan.io/block/countdown/14586600 - 14.4 23:59 UTC uint private _secondStageMaxContribution = 50000 * 10**6; mapping(address => bool) private _allowedTokens; constructor(address defaultAdminAddress_, address adminAddress_, address moderatorAddress_, address dataAddress_, address corporateAddress_) { _setupRole(DEFAULT_ADMIN_ROLE, defaultAdminAddress_); _setupRole(ADMIN_ROLE, adminAddress_); _setupRole(MODERATOR_ROLE, moderatorAddress_); _setRoleAdmin(MODERATOR_ROLE, ADMIN_ROLE); _dataInstance = DataInterface(dataAddress_); _corporateAddress = corporateAddress_; _allowedTokens[0xdAC17F958D2ee523a2206206994597C13D831ec7] = true; // Allow USDT as participation currency _allowedTokens[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48] = true; // Allow USDC as participation currency } // ****************************************** // ************* PUBLIC REGION ************** // ****************************************** /// @notice Executes the code for participating in the crowdsale @ First stage /// @dev This is a public method that users should execute for participating /// @param tokenInvested_ The ERC20 token address that participant wants to contribute /// @param amountInvested_ The amount of tokens contributed to presale, will be transfered to corpo from /// @param signature_ Cryptographic proof that participant is whitelisted function contributeFirstStage(address tokenInvested_, uint amountInvested_, bytes memory signature_) public override { require(getFirstStageActive(), "FirstStage is not active!"); require(getTokenAllowed(tokenInvested_), "Token is not allowed!"); uint allowedContribution = getFirstStageParticipantMaxContribution(msg.sender); require(allowedContribution > 0, "Allowed amount is 0!"); if (allowedContribution > amountInvested_) { allowedContribution = amountInvested_; } if (!_dataInstance.getIsParticipantWhitelisted(msg.sender)) { require(amountInvested_ >= _minimumContributionRequierment, "Not enough tokens contributed!"); _dataInstance.whitelistParticipant(msg.sender, signature_); } _dataInstance.creditParticipation(msg.sender, tokenInvested_, allowedContribution); IERC20(tokenInvested_).transferFrom(msg.sender, _corporateAddress, allowedContribution); } /// @notice Executes the code for participating in the crowdsale @ Second stage /// @dev This is a public method that users should execute for participating /// @param tokenInvested_ The ERC20 token address that participant wants to contribute /// @param amountInvested_ The amount of tokens contributed to presale, will be transfered to corpo from /// @param signature_ Cryptographic proof that participant is whitelisted function contributeSecondStage(address tokenInvested_, uint amountInvested_, bytes memory signature_) public override { require(getSecondStageActive(), "Presale is not active!"); require(getTokenAllowed(tokenInvested_), "Token is not allowed!"); uint allowedContribution = getSecondStageParticipantMaxContribution(msg.sender); require(allowedContribution > 0, "Allowed amount is 0!"); if (allowedContribution > amountInvested_) { allowedContribution = amountInvested_; } if (!_dataInstance.getIsParticipantWhitelisted(msg.sender)) { require(amountInvested_ >= _minimumContributionRequierment, "Not enough tokens contributed!"); _dataInstance.whitelistParticipant(msg.sender, signature_); } _dataInstance.creditParticipation(msg.sender, tokenInvested_, allowedContribution); IERC20(tokenInvested_).transferFrom(msg.sender, _corporateAddress, allowedContribution); } // ********************************************* // ************* MODERATOR REGION ************** // ********************************************* /// @notice Sets new minimum ammount users can invest /// @dev This method should only be used in ongoing presale if something goes wrong /// @param minimumContributionRequierment_ Minimum ammount of allowed tokens user can invest /// @return default return True after everything is processed function setMinimumContributionRequierment(uint minimumContributionRequierment_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _minimumContributionRequierment; require(oldValue != minimumContributionRequierment_, "Value is already set!"); _minimumContributionRequierment = minimumContributionRequierment_; emit MinimumContributionRequiermentChanged(oldValue, minimumContributionRequierment_); return true; } /// @notice Sets new amount of stablecoins that needs to be colected for presale to be over /// @dev This method should only be used in ongoing presale if something goes wrong /// @param presaleCap_ The new cap on presale /// @return default return True after everything is processed function setPresaleCap(uint presaleCap_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _presaleCap; require(oldValue != presaleCap_, "Value is already set!"); _presaleCap = presaleCap_; emit PresaleCapChanged(oldValue, presaleCap_); return true; } /// @notice Sets new block number on which presales phase one should start /// @dev This method should only be used in ongoing presale if something goes wrong /// @param firstStageBlockStart_ The block number on which crowdsales first phase will start /// @return default return True after everything is processed function setFirstStageBlockStart(uint firstStageBlockStart_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _firstStageBlockStart; require(oldValue != firstStageBlockStart_, "Value is already set!"); _firstStageBlockStart = firstStageBlockStart_; emit FirstStageBlockStartChanged(oldValue, firstStageBlockStart_); return true; } /// @notice Sets new block on which presales first stage will end /// @dev This method should only be used in ongoing presale if something goes wrong /// @param firstStageBlockEnd_ The block number on which presales first stage will end /// @return default return True after everything is processed function setFirstStageBlockEnd(uint firstStageBlockEnd_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _firstStageBlockEnd; require(oldValue != firstStageBlockEnd_, "Value is already set!"); _firstStageBlockEnd = firstStageBlockEnd_; emit FirstStageBlockEndChanged(oldValue, firstStageBlockEnd_); return true; } /// @notice Sets new amount of participants in first stage /// @dev This method should only be used in ongoing presale if something goes wrong /// @param firstStageMaxContributorCount_ The block number on which maxContribution limit is waived /// @return default return True after everything is processed function setFirstStageMaxContributorCount(uint firstStageMaxContributorCount_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _firstStageMaxContributorCount; require(oldValue != firstStageMaxContributorCount_, "Value is already set!"); _firstStageMaxContributorCount = firstStageMaxContributorCount_; emit FirstStageMaxContributorCountChanged(oldValue, firstStageMaxContributorCount_); return true; } /// @notice Sets new amount of stablecoins that participant can contribute during first phase /// @dev This method should only be used in ongoing presale if something goes wrong /// @param firstStageMaxContribution_ The new cap on users contribution on first phase /// @return default return True after everything is processed function setFirstStageMaxContribution(uint firstStageMaxContribution_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _firstStageMaxContribution; require(oldValue != firstStageMaxContribution_, "Value is already set!"); _firstStageMaxContribution = firstStageMaxContribution_; emit FirstStageMaxContributionChanged(oldValue, firstStageMaxContribution_); return true; } /// @notice Sets new block number on which presales phase two should start /// @dev This method should only be used in ongoing presale if something goes wrong /// @param secondStageBlockStart_ The block number on which crowdsales second phase will start /// @return default return True after everything is processed function setSecondStageBlockStart(uint secondStageBlockStart_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _secondStageBlockStart; require(oldValue != secondStageBlockStart_, "Value is already set!"); _secondStageBlockStart = secondStageBlockStart_; emit SecondStageBlockStartChanged(oldValue, secondStageBlockStart_); return true; } /// @notice Sets new block on which presales second stage will end /// @dev This method should only be used in ongoing presale if something goes wrong /// @param secondStageBlockEnd_ The block number on which presales second stage will end /// @return default return True after everything is processed function setSecondStageBlockEnd(uint secondStageBlockEnd_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _secondStageBlockEnd; require(oldValue != secondStageBlockEnd_, "Value is already set!"); _secondStageBlockEnd = secondStageBlockEnd_; emit SecondStageBlockEndChanged(oldValue, secondStageBlockEnd_); return true; } /// @notice Sets new amount of stablecoins that participant can contribute during first phase /// @dev This method should only be used in ongoing presale if something goes wrong /// @param secondStageMaxContribution_ The new cap on users contribution on first phase /// @return default return True after everything is processed function setSecondStageMaxContribution(uint secondStageMaxContribution_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _secondStageMaxContribution; require(oldValue != secondStageMaxContribution_, "Value is already set!"); _secondStageMaxContribution = secondStageMaxContribution_; emit SecondStageMaxContributionChanged(oldValue, secondStageMaxContribution_); return true; } /// @notice Disables or enables ERC20 token that can be used by contributors /// @dev This method should only be used in ongoing presale if something goes wrong /// @param token_ The ERC20 token we want to edit /// @param option_ Option on what we want to do with the token, True - Enabled, False - disabled /// @return default return True after everything is processed function setTokenAllowed(address token_, bool option_) public onlyRole(MODERATOR_ROLE) override returns (bool) { bool oldValue = _allowedTokens[token_]; require(oldValue != option_, "Value is already set!"); _allowedTokens[token_] = option_; emit TokenAllowedChanged(oldValue, option_); return true; } /// @notice Sets new data contract address to be used internally /// @dev This method should only be used in ongoing presale if something goes wrong /// @param dataAddress_ Address of new DataContract /// @return default return True after everything is processed function setDataInstance(address dataAddress_) public onlyRole(MODERATOR_ROLE) override returns (bool) { address oldValue = address(_dataInstance); require(oldValue != dataAddress_, "Value is already set!"); _dataInstance = DataInterface(dataAddress_); emit DataAddressChanged(oldValue, dataAddress_); return true; } /// @notice Sets new address on which contribution funds will be sent /// @dev This method should only be used in ongoing presale if something goes wrong /// @param corporateAddress_ New destination for funds /// @return default return True after everything is processed function setCorporateAddress(address corporateAddress_) public onlyRole(MODERATOR_ROLE) override returns (bool) { address oldValue = _corporateAddress; require(oldValue != corporateAddress_, "Value is already set!"); _corporateAddress = corporateAddress_; emit CorporateAddressChanged(oldValue, corporateAddress_); return true; } // ************************************************* // ************* DEFAULT_ADMIN REGION ************** // ************************************************* /// @notice Sets new role admin to the role defined /// @dev This method should only be used if some of priviliged keys are compromised, can only be done by defaultAdmin /// @param role_ Role that we want to change /// @param adminRole_ Role that will become new admin of the changed role /// @return default return True after everything is processed function setRoleAdmin(bytes32 role_, bytes32 adminRole_) public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool) { _setRoleAdmin(role_, adminRole_); emit AdminRoleSet(role_, adminRole_); return true; } /// @notice Transfer tokens from the contract to desiered address /// @dev This method should be used if users accedentaly sends tokens to our contract address /// @param tokenAddress_ Token address of the token that we want to salvage /// @param to_ Destination where salvaged tokens will be sent /// @param amount_ Amount of tokens we want to salvage /// @return default return True after everything is processed function salvageTokensFromContract(address tokenAddress_, address to_, uint amount_) public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool){ IERC20(tokenAddress_).transfer(to_, amount_); emit TokensSalvaged(tokenAddress_, to_, amount_); return true; } /// @notice Destroys the contract /// @dev This method should NEVER be used if you don't know the implications!!!!!!!! /// @return default return True after everything is processed function killContract() public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool){ emit ContractKilled(); selfdestruct(payable(msg.sender)); return true; } // ************************************************** // ************* PUBLIC GETTERS REGION ************** // ************************************************** /// @notice Returns if presale is active or notActive function getPresaleActive() public view override returns (bool) { if (getFirstStageActive() || getSecondStageActive()) { return true; } return false; } /// @notice Returns if first stage of presale is active or notActive function getFirstStageActive() public view override returns (bool) { if (block.number < _firstStageBlockStart) { return false; } if (block.number > _firstStageBlockEnd) { return false; } if (_dataInstance.getParticipantCount() >= _firstStageMaxContributorCount ) { return false; } if (_dataInstance.getCombinedContributions() >= _presaleCap ) { return false; } return true; } /// @notice Returns if second stage presale is active or notActive function getSecondStageActive() public view override returns (bool) { if (block.number < _secondStageBlockStart) { return false; } if (block.number > _secondStageBlockEnd) { return false; } if (_dataInstance.getCombinedContributions() >= _presaleCap ) { return false; } return true; } /// @notice Returns the amount that participant can contribute depending on the state of presale while in first stage function getFirstStageParticipantMaxContribution(address participant_) public view override returns (uint) { uint maxContribution = _firstStageMaxContribution - _dataInstance.getParticipantContributions(participant_); uint tokensLeftTillCap = _presaleCap - _dataInstance.getCombinedContributions(); if (tokensLeftTillCap < maxContribution) { return tokensLeftTillCap; } return maxContribution; } /// @notice Returns the amount that participant can contribute depending on the state of presale while in second stage function getSecondStageParticipantMaxContribution(address participant_) public view override returns (uint) { uint maxContribution = _secondStageMaxContribution - _dataInstance.getParticipantContributions(participant_); uint tokensLeftTillCap = _presaleCap - _dataInstance.getCombinedContributions(); if (tokensLeftTillCap < maxContribution) { return tokensLeftTillCap; } return maxContribution; } /// @notice Returns the lowest ammount that user can contribute function getMinimumContributionRequierment() public view override returns (uint) { return _minimumContributionRequierment; } /// @notice Returns the amount of tokens that presale will recieve function getPresaleCap() public view override returns (uint) { return _presaleCap; } /// @notice Returns block which starts first phase of presale function getFirstStageBlockStart() public view override returns (uint) { return _firstStageBlockStart; } /// @notice Returns block which ends first phase of presale function getFirstStageBlockEnd() public view override returns (uint) { return _firstStageBlockEnd; } /// @notice Returns the maximum number of participants in first stage function getFirstStageMaxContributorCount() public view override returns (uint) { return _firstStageMaxContributorCount; } /// @notice Returns the maximum amount that users can contribute in first phase function getFirstStageMaxContribution() public view override returns (uint) { return _firstStageMaxContribution; } /// @notice Returns block which starts second phase of presale function getSecondStageBlockStart() public view override returns (uint) { return _secondStageBlockStart; } /// @notice Returns block which ends second phase of presale function getSecondStageBlockEnd() public view override returns (uint) { return _secondStageBlockEnd; } /// @notice Returns the maximum amount that users can contribute in second phase function getSecondStageMaxContribution() public view override returns (uint) { return _secondStageMaxContribution; } /// @notice Returns if token is allowed in presale function getTokenAllowed(address token_) public view override returns (bool) { return _allowedTokens[token_]; } /// @notice Returns the address of data contract function getDataAddress() public view override returns (address) { return address(_dataInstance); } /// @notice Returns the address on which tokens will be sent function getCorporateAddress() public view override returns (address) { return _corporateAddress; } }
Returns the amount of tokens that presale will recieve
function getPresaleCap() public view override returns (uint) { return _presaleCap; }
10,550,873
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {FxBaseChildTunnel} from "../../tunnel/FxBaseChildTunnel.sol"; import {Create2} from "../../lib/Create2.sol"; import {IFxERC20} from "../../tokens/IFxERC20.sol"; /** * @title FxERC20ChildTunnel */ contract FxERC20ChildTunnel is FxBaseChildTunnel, Create2 { bytes32 public constant DEPOSIT = keccak256("DEPOSIT"); bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN"); string public constant SUFFIX_NAME = " (FXERC20)"; string public constant PREFIX_SYMBOL = ""; // event for token maping event TokenMapped(address indexed rootToken, address indexed childToken); // root to child token mapping(address => address) public rootToChildToken; // token template address public tokenTemplate; constructor(address _fxChild, address _tokenTemplate) FxBaseChildTunnel(_fxChild) { tokenTemplate = _tokenTemplate; require(_isContract(_tokenTemplate), "Token template is not contract"); } function withdraw(address childToken, uint256 amount) public { IFxERC20 childTokenContract = IFxERC20(childToken); // child token contract will have root token address rootToken = childTokenContract.connectedToken(); // validate root and child token mapping require( childToken != address(0x0) && rootToken != address(0x0) && childToken == rootToChildToken[rootToken], "FxERC20ChildTunnel: NO_MAPPED_TOKEN" ); // withdraw tokens childTokenContract.burn(msg.sender, amount); // send message to root regarding token burn _sendMessageToRoot( abi.encode(rootToken, childToken, msg.sender, amount) ); } // // Internal methods // function _processMessageFromRoot( uint256, /* stateId */ address sender, bytes memory data ) internal override validateSender(sender) { // decode incoming data (bytes32 syncType, bytes memory syncData) = abi.decode( data, (bytes32, bytes) ); if (syncType == DEPOSIT) { _syncDeposit(syncData); } else if (syncType == MAP_TOKEN) { _mapToken(syncData); } else { revert("FxERC20ChildTunnel: INVALID_SYNC_TYPE"); } } function _mapToken(bytes memory syncData) internal returns (address) { ( address rootToken, string memory name, string memory symbol, uint8 decimals ) = abi.decode(syncData, (address, string, string, uint8)); // get root to child token address childToken = rootToChildToken[rootToken]; // check if it's already mapped require( childToken == address(0x0), "FxERC20ChildTunnel: ALREADY_MAPPED" ); // deploy new child token bytes32 salt = keccak256(abi.encodePacked(rootToken)); childToken = createClone(salt, tokenTemplate); IFxERC20(childToken).initialize( address(this), rootToken, string(abi.encodePacked(name, SUFFIX_NAME)), string(abi.encodePacked(PREFIX_SYMBOL, symbol)), decimals ); // map the token rootToChildToken[rootToken] = childToken; emit TokenMapped(rootToken, childToken); // return new child token return childToken; } function _syncDeposit(bytes memory syncData) internal { ( address rootToken, address depositor, address to, uint256 amount, bytes memory depositData ) = abi.decode(syncData, (address, address, address, uint256, bytes)); address childToken = rootToChildToken[rootToken]; // deposit tokens IFxERC20 childTokenContract = IFxERC20(childToken); childTokenContract.mint(to, amount); // call `onTokenTranfer` on `to` with limit and ignore error if (_isContract(to)) { uint256 txGas = 2000000; bool success = false; bytes memory data = abi.encodeWithSignature( "onTokenTransfer(address,address,address,address,uint256,bytes)", rootToken, childToken, depositor, to, amount, depositData ); // solium-disable-next-line security/no-inline-assembly assembly { success := call( txGas, to, 0, add(data, 0x20), mload(data), 0, 0 ) } } } // check if address is contract function _isContract(address _addr) private view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } }
deposit tokens call `onTokenTranfer` on `to` with limit and ignore error solium-disable-next-line security/no-inline-assembly
function _syncDeposit(bytes memory syncData) internal { ( address rootToken, address depositor, address to, uint256 amount, bytes memory depositData ) = abi.decode(syncData, (address, address, address, uint256, bytes)); address childToken = rootToChildToken[rootToken]; IFxERC20 childTokenContract = IFxERC20(childToken); childTokenContract.mint(to, amount); if (_isContract(to)) { uint256 txGas = 2000000; bool success = false; bytes memory data = abi.encodeWithSignature( "onTokenTransfer(address,address,address,address,uint256,bytes)", rootToken, childToken, depositor, to, amount, depositData ); assembly { success := call( txGas, to, 0, add(data, 0x20), mload(data), 0, 0 ) } } }
12,733,529
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // &#39;imChat&#39; token contract // // Symbol : IMC // Name : IMC // Total supply: 1000,000,000.000000000000000000 // Decimals : 8 // // imChat Technology Service Limited // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address _owner) public constant returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract IMCToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; address public externalContractAddress; /** * 构造函数 */ constructor() public { symbol = "IMC"; name = "IMC"; decimals = 8; _totalSupply = 1000000000 * (10 ** uint(decimals)); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } /** * 查询代币总发行量 * @return unit 余额 */ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } /** * 查询代币余额 * @param _owner address 查询代币的地址 * @return balance 余额 */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } /** * 私有方法从一个帐户发送给另一个帐户代币 * @param _from address 发送代币的地址 * @param _to address 接受代币的地址 * @param _value uint 接受代币的数量 */ function _transfer(address _from, address _to, uint _value) internal{ // 确保目标地址不为0x0,因为0x0地址代表销毁 require(_to != 0x0); // 检查发送者是否拥有足够余额 require(balances[_from] >= _value); // 检查是否溢出 require(balances[_to] + _value > balances[_to]); // 保存数据用于后面的判断 uint previousBalance = balances[_from].add(balances[_to]); // 从发送者减掉发送额 balances[_from] = balances[_from].sub(_value); // 给接收者加上相同的量 balances[_to] = balances[_to].add(_value); // 通知任何监听该交易的客户端 emit Transfer(_from, _to, _value); // 判断发送、接收方的数据是否和转换前一致 assert(balances[_from].add(balances[_to]) == previousBalance); } /** * 从主帐户合约调用者发送给别人代币 * @param _to address 接受代币的地址 * @param _value uint 接受代币的数量 * @return success 交易成功 */ function transfer(address _to, uint _value) public returns (bool success) { // _transfer(msg.sender, _to, _value); if (msg.sender == owner) { // ERC20合约owner调用 _transfer(msg.sender, _to, _value); return true; } else { // 外部合约调用,需满足合约调用者和代币合约所设置的外部调用合约地址一致性 require(msg.sender == externalContractAddress); _transfer(owner, _to, _value); return true; } } /** * 账号之间代币交易转移,调用过程,会检查设置的允许最大交易额 * @param _from address 发送者地址 * @param _to address 接受者地址 * @param _value uint 要转移的代币数量 * @return success 交易成功 */ function transferFrom(address _from, address _to, uint _value) public returns (bool success) { if (_from == msg.sender) { // 自己转账时不需要approve,可以直接进行转账 _transfer(_from, _to, _value); } else { // 授权给第三方时,需检查发送者是否拥有足够余额 require(allowed[_from][msg.sender] >= _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); } return true; } /** * 允许帐户授权其他帐户代表他们提取代币 * @param _spender 授权帐户地址 * @param _value 代币数量 * @return success 允许成功 */ function approve(address _spender, uint _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * 查询被授权帐户的允许提取的代币数 * @param _owner 授权者帐户地址 * @param _spender 被授权者帐户地址 * @return remaining 代币数量 */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } /** * 设置允许一个地址(合约)以我(创建交易者)的名义可最多花费的代币数。 * @param _spender 被授权的地址(合约) * @param _value 最大可花费代币数 * @param _extraData 发送给合约的附加数据 * @return success 设置成功 */ function approveAndCall(address _spender, uint _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { // 通知合约 spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 设置允许外部合约地址调用当前合约 * @param _contractAddress 合约地址 * @return success 设置成功 */ function approveContractCall(address _contractAddress) public onlyOwner returns (bool){ externalContractAddress = _contractAddress; return true; } /** * 不接收 Ether */ function () public payable { revert(); } } // ---------------------------------------------------------------------------- // 发行记录合约 // ---------------------------------------------------------------------------- contract IMCIssuingRecord is Owned{ using SafeMath for uint; // 发行记录添加日志 event IssuingRecordAdd(uint _date, bytes32 _hash, uint _depth, uint _userCount, uint _token, string _fileFormat, uint _stripLen); // 定义IMCToken实例 IMCToken public imcToken; // 平台账户地址 address public platformAddr; // 执行者地址 address public executorAddress; // Token发行统计记录 struct RecordInfo { uint date; // 记录日期(解锁ID) bytes32 hash; // 文件hash uint depth; // 深度 uint userCount; // 用户数 uint token; // 发行token数量 string fileFormat; // 上链存证的文件格式 uint stripLen; // 上链存证的文件分区 } // 分配记录 mapping(uint => RecordInfo) public issuingRecord; // 用户数 uint public userCount; // 发行总币数 uint public totalIssuingBalance; /** * 构造函数 * @param _tokenAddr address ERC20合约地址 * @param _platformAddr address 平台帐户地址 */ constructor(address _tokenAddr, address _platformAddr) public{ // 初始化IMCToken实例 imcToken = IMCToken(_tokenAddr); // 初始化平台账户地址 platformAddr = _platformAddr; // 初始化合约执行者 executorAddress = msg.sender; } /** * 修改platformAddr,只有owner能够修改 * @param _addr address 地址 */ function modifyPlatformAddr(address _addr) public onlyOwner { platformAddr = _addr; } /** * 修改executorAddress,只有owner能够修改 * @param _addr address 地址 */ function modifyExecutorAddr(address _addr) public onlyOwner { executorAddress = _addr; } /** * 转账到中间帐户 * @param _tokens uint 币数量 * @return success 交易成功 */ function sendTokenToPlatform(uint _tokens) internal returns (bool) { imcToken.transfer(platformAddr, _tokens); return true; } /** * 发行记录添加 * @param _date uint 记录日期(解锁ID) * @param _hash bytes32 文件hash * @param _depth uint 深度 * @param _userCount uint 用户数 * @param _token uint 发行token数量 * @param _fileFormat string 上链存证的文件格式 * @param _stripLen uint 上链存证的文件分区 * @return success 添加成功 */ function issuingRecordAdd(uint _date, bytes32 _hash, uint _depth, uint _userCount, uint _token, string _fileFormat, uint _stripLen) public returns (bool) { // 调用者需和Owner设置的执行者地址一致 require(msg.sender == executorAddress); // 防止重复记录 require(issuingRecord[_date].date != _date); // 累计用户数 userCount = userCount.add(_userCount); // 累计发行币数 totalIssuingBalance = totalIssuingBalance.add(_token); // 记录发行信息 issuingRecord[_date] = RecordInfo(_date, _hash, _depth, _userCount, _token, _fileFormat, _stripLen); // 转账到中间帐户 sendTokenToPlatform(_token); emit IssuingRecordAdd(_date, _hash, _depth, _userCount, _token, _fileFormat, _stripLen); return true; } }
修改executorAddress,只有owner能够修改 _addr address 地址/
function modifyExecutorAddr(address _addr) public onlyOwner { executorAddress = _addr; }
2,402,566
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0 <= 0.7.5; import "./SmartDCPABEUsers.sol"; import "./Collection.sol"; /** * @author Bruno C. P. Arruda * @title SmartDCPABE Certifier Management Contract * @notice This contract allow to register and find certifiers */ contract SmartDCPABEAuthority is Collection { struct Certifier { address addr; string name; string email; uint64 numPublicKeys; } address[] public certifierAddresses; mapping(address => Certifier) certifiers; SmartDCPABEUsers user; address contractKeys; /** * @notice creates the contract with unset dependencies * @param root the address of the Root contract */ constructor(address root) Collection(root) {} /** * @inheritdoc Collection */ function setContractDependencies( ContractType contractType, address addr ) public override onlyOwner { if (contractType == ContractType.USERS) { user = SmartDCPABEUsers(addr); } else if (contractType == ContractType.KEYS) { contractKeys = addr; } } /** * @notice increments public key counting of a certifier * @param addr the certifier's address */ function incrementPublicKeyCount(address addr) public { require(msg.sender == contractKeys, "Operation not allowed."); certifiers[addr].numPublicKeys++; } /** * @notice checks if the address is registered as a Certifier in this contract * @param addr a Ethereum address */ function isCertifier(address addr) public view returns (bool) { return (bytes(certifiers[addr].name)).length > 0; } /** * @notice registers a certifier * @param addr certfier's address * @param name certifier's name * @param email certifier's e-mail */ function addCertifier(address addr, string memory name, string memory email) public { certifierAddresses.push(addr); certifiers[addr] = Certifier(addr, name, email, 0); } /** * @notice get certifier data * @param addr the certifier's address * @return addr_ certifier's address * @return name certifier's name * @return email certifier's e-mail * @return numPublicKeys number of attributes published by the certifier */ function getCertifier ( address addr ) public view returns ( address addr_, string memory name, string memory email, uint64 numPublicKeys ) { Certifier storage c = certifiers[addr]; return (c.addr, c.name, c.email, c.numPublicKeys); } }
get certifier data addr the certifier's address return addr_ certifier's address return name certifier's name return email certifier's e-mail return numPublicKeys number of attributes published by the certifier/
function getCertifier ( address addr ) public view returns ( address addr_, string memory name, string memory email, uint64 numPublicKeys ) { Certifier storage c = certifiers[addr]; return (c.addr, c.name, c.email, c.numPublicKeys); }
5,360,587
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../interfaces/yearn/IController.sol"; import "../interfaces/yearn/IVault.sol"; /// @title yVault yAgnostic. /// @dev yVault inherits ERC20. contract yVault is IVault, ERC20, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /// @notice Underlying token the vault operates with. /// @dev Set in constructor. /// @return Underlying token the vault operates with. address public override token; /// @notice Displays percentage to calculate available. /// @dev By default: 9500(95%). /// @return Percentage to calculate available. uint256 public min = 9500; /// @notice Displays percentage to calculate available. /// @dev By default: 10000(100%). /// @return Percentage to calculate available. uint256 public constant MAX = 10000; /// @notice Variable storing the governance address. By default it is equal to the deployer of the controller. /// @dev Specified when creating the controller (in the constructor). /// @dev Can also be changed using the setGovernance method. /// @return Returns the governance address of this contract. address public override governance; /// @notice Variable storing the controller address. /// @notice By default, it is equal to the address specified during deployment. /// @dev Specified when creating the controller (in the constructor). /// @dev Can also be changed using the setController method. /// @return Returns the controller address of this contract. address public override controller; /// @notice Modifier to restrict the method for governance only. modifier governanceOnly() { require(_msgSender() == governance, "Not the governance"); _; } /// @notice Modifier to restrict the method for controller only. modifier controllerOnly() { require(_msgSender() == controller, "Not the controller"); _; } /// @notice Sets token name: yfiag + name, token symbol: y + symbol. /// @notice Sets the governance address equal to the deployer. /// @param _token Address of the token the vault work with. /// @param _controller Address of the controller. constructor(address _token, address _controller) public ERC20( string(abi.encodePacked("yfiag ", ERC20(_token).name())), string(abi.encodePacked("y", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = _token; governance = _msgSender(); controller = _controller; } /****** * Governance regulated parameters ******/ /// @notice called by the owner to pause, triggers stopped state function pause() whenNotPaused governanceOnly external { _pause(); } /// @notice called by the owner to unpause, returns to normal state function unpause() whenPaused governanceOnly external { _unpause(); } /// @notice Set percentage of tokens allowed for the strategy. /// @dev Can only be called by governance. The maximum value is 10000(100%). /// @param _min Percentage to calculate available. function setMin(uint256 _min) external governanceOnly { require(_min <= MAX, "min<=max"); min = _min; } /// @notice Specifies a new governance address. /// @dev Can only be called by governance. /// @param _governance Address of the new governance. function setGovernance(address _governance) external governanceOnly { governance = _governance; } /// @notice Specifies a new controller address. /// @dev Can only be called by governance. /// @param _controller Address of the new controller. function setController(address _controller) external governanceOnly { controller = _controller; } /****** * Vault functionality ******/ /// @notice Method transferring tokens to a strategy through controller. function earn() whenNotPaused external { uint256 _bal = available(); IERC20(token).safeTransfer(controller, _bal); IController(controller).earn(address(this), address(token), _bal); } /// @notice Used to swap any borrowed reserve over the debt limit to liquidate to underlying 'token' /// @param reserve Address of the reserve token. /// @param amount Amount of the tokens. function harvest(address reserve, uint256 amount) external controllerOnly { require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } /// @notice Causes the deposit of all available sender tokens. function depositAll() whenNotPaused external override { deposit(IERC20(token).balanceOf(_msgSender())); } /// @notice Causes the deposit of amount sender tokens. /// @param _amount Amount of the tokens. function deposit(uint256 _amount) whenNotPaused nonReentrant public override { uint256 _pool = balance(); uint256 _before = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransferFrom(_msgSender(), address(this), _amount); uint256 _after = IERC20(token).balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(_msgSender(), shares); } /// @notice Causes the withdraw of all available sender shares. function withdrawAll() whenNotPaused external override { withdraw(balanceOf(_msgSender())); } // No rebalance implementation for lower fees and faster swaps /// @notice Causes the withdraw of amount sender shares. /// @param _shares Amount of the shares. function withdraw(uint256 _shares) whenNotPaused public override { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(_msgSender(), _shares); // Check balance uint256 b = IERC20(token).balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(_withdraw); uint256 _after = IERC20(token).balanceOf(address(this)); require(_after >= r, "Not enough balance"); } IERC20(token).safeTransfer(_msgSender(), r); } /***** * View interface *****/ /// @notice Сalculates the price per full share. /// @return Returns the price per full share. function getPricePerFullShare() external view override returns (uint256) { return balance().mul(1e18).div(totalSupply()); } /// @notice Shows how many tokens are available (in total in the volt and deposited to the strategy). function balance() public view returns (uint256) { return IERC20(token).balanceOf(address(this)).add(IController(controller).balanceOf(address(this))); } /// @notice Сalculates the available amount that can be transferred to the strategy. /// @dev Custom logic in here for how much the vault allows to be borrowed /// @dev Sets minimum required on-hand to keep small withdrawals cheap /// @return Returns the available vault. function available() public view returns (uint256) { return IERC20(token).balanceOf(address(this)).mul(min).div(MAX); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IController { function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function earn(address, address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function tokens(address) external view returns (address); function strategies(address) external view returns (address); function approvedStrategies(address, address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IVault { function token() external view returns (address); function controller() external view returns (address); function governance() external view returns (address); function getPricePerFullShare() external view returns (uint256); function deposit(uint256) external; function depositAll() external; function withdraw(uint256) external; function withdrawAll() external; // Part of ERC20 interface //function name() external view returns (string memory); //function symbol() external view returns (string memory); //function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Specifies a new controller address. Can only be called by governance. _controller Address of the new controller.
function setController(address _controller) external governanceOnly { controller = _controller; }
5,948,779
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract YieldFarm { // lib using SafeMath for uint; using SafeMath for uint128; // constants uint public constant TOTAL_DISTRIBUTED_AMOUNT = 800000; uint public constant NR_OF_EPOCHS = 25; // state variables // addreses address private _usdc; address private _susd; address private _dai; address private _communityVault; // contracts IERC20 private _ara; IStaking private _staking; // fixed size array holdings total number of epochs + 1 (epoch 0 doesn't count) uint[] private epochs = new uint[](NR_OF_EPOCHS + 1); // pre-computed variable for optimization. total amount of ara tokens to be distributed on each epoch uint private _totalAmountPerEpoch; // id of last init epoch, for optimization purposes moved from struct to a single id. uint128 public lastInitializedEpoch; // state of user harvest epoch mapping(address => uint128) private lastEpochIdHarvested; uint public epochDuration; // init from staking contract uint public epochStart; // init from staking contract // events event MassHarvest(address indexed user, uint256 epochsHarvested, uint256 totalValue); event Harvest(address indexed user, uint128 indexed epochId, uint256 amount); // constructor constructor(address araTokenAddress, address usdc, address susd, address dai, address stakeContract, address communityVault) public { _ara = IERC20(araTokenAddress); _usdc = usdc; _susd = susd; _dai = dai; _staking = IStaking(stakeContract); _communityVault = communityVault; epochStart = _staking.epoch1Start(); epochDuration = _staking.epochDuration(); _totalAmountPerEpoch = TOTAL_DISTRIBUTED_AMOUNT.mul(10**18).div(NR_OF_EPOCHS); } // public methods // public method to harvest all the unharvested epochs until current epoch - 1 function massHarvest() external returns (uint){ uint totalDistributedValue; uint epochId = _getEpochId().sub(1); // fails in epoch 0 // force max number of epochs if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { // i = epochId // compute distributed Value and do one single transfer at the end totalDistributedValue += _harvest(i); } emit MassHarvest(msg.sender, epochId.sub(lastEpochIdHarvested[msg.sender]), totalDistributedValue); if (totalDistributedValue > 0) { _ara.transferFrom(_communityVault, msg.sender, totalDistributedValue); } return totalDistributedValue; } function harvest (uint128 epochId) external returns (uint){ // checks for requested epoch require (_getEpochId() > epochId, "This epoch is in the future"); require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 25"); require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order"); uint userReward = _harvest(epochId); if (userReward > 0) { _ara.transferFrom(_communityVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; } // views // calls to the staking smart contract to retrieve the epoch total pool size function getPoolSize(uint128 epochId) external view returns (uint) { return _getPoolSize(epochId); } function getCurrentEpoch() external view returns (uint) { return _getEpochId(); } // calls to the staking smart contract to retrieve user balance for an epoch function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); } function userLastEpochIdHarvested() external view returns (uint){ return lastEpochIdHarvested[msg.sender]; } // internal methods function _initEpoch(uint128 epochId) internal { require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order"); lastInitializedEpoch = epochId; // call the staking smart contract to init the epoch epochs[epochId] = _getPoolSize(epochId); } function _harvest (uint128 epochId) internal returns (uint) { // try to initialize an epoch. if it can't it fails // if it fails either user either a BarnBridge account will init not init epochs if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } // Set user last harvested epoch lastEpochIdHarvested[msg.sender] = epochId; // compute and return user total reward. For optimization reasons the transfer have been moved to an upper layer (i.e. massHarvest needs to do a single transfer) // exit if there is no stake on the epoch if (epochs[epochId] == 0) { return 0; } return _totalAmountPerEpoch .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); } function _getPoolSize(uint128 epochId) internal view returns (uint) { // retrieve stable coins total staked in epoch uint valueUsdc = _staking.getEpochPoolSize(_usdc, epochId).mul(10 ** 12); // for usdc which has 6 decimals add a 10**12 to get to a common ground uint valueSusd = _staking.getEpochPoolSize(_susd, epochId); uint valueDai = _staking.getEpochPoolSize(_dai, epochId); return valueUsdc.add(valueSusd).add(valueDai); } function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint){ // retrieve stable coins total staked per user in epoch uint valueUsdc = _staking.getEpochUserBalance(userAddress, _usdc, epochId).mul(10 ** 12); // for usdc which has 6 decimals add a 10**12 to get to a common ground uint valueSusd = _staking.getEpochUserBalance(userAddress, _susd, epochId); uint valueDai = _staking.getEpochUserBalance(userAddress, _dai, epochId); return valueUsdc.add(valueSusd).add(valueDai); } // compute epoch id from blocktimestamp and epochstart date function _getEpochId() internal view returns (uint128 epochId) { if (block.timestamp < epochStart) { return 0; } epochId = uint128(block.timestamp.sub(epochStart).div(epochDuration).add(1)); } }
try to initialize an epoch. if it can't it fails if it fails either user either a BarnBridge account will init not init epochs exit if there is no stake on the epoch
function _harvest (uint128 epochId) internal returns (uint) { if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } if (epochs[epochId] == 0) { return 0; } return _totalAmountPerEpoch .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); }
1,829,783
/* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IController } from "../../interfaces/IController.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { Position } from "../lib/Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title AirdropModule * @author Set Protocol * * Module that enables managers to absorb tokens sent to the SetToken into the token's positions. With each SetToken, * managers are able to specify 1) the airdrops they want to include, 2) an airdrop fee recipient, 3) airdrop fee, * and 4) whether all users are allowed to trigger an airdrop. */ contract AirdropModule is ModuleBase, ReentrancyGuard { using PreciseUnitMath for uint256; using SafeMath for uint256; using Position for uint256; using SafeCast for int256; using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; /* ============ Structs ============ */ struct AirdropSettings { address[] airdrops; // Array of tokens manager is allowing to be absorbed address feeRecipient; // Address airdrop fees are sent to uint256 airdropFee; // Percentage in preciseUnits of airdrop sent to feeRecipient (1e16 = 1%) bool anyoneAbsorb; // Boolean indicating if any address can call absorb or just the manager } /* ============ Events ============ */ event ComponentAbsorbed( ISetToken indexed _setToken, address _absorbedToken, uint256 _absorbedQuantity, uint256 _managerFee, uint256 _protocolFee ); /* ============ Modifiers ============ */ /** * Throws if claim is confined to the manager and caller is not the manager */ modifier onlyValidCaller(ISetToken _setToken) { require(_isValidCaller(_setToken), "Must be valid caller"); _; } /* ============ Constants ============ */ uint256 public constant AIRDROP_MODULE_PROTOCOL_FEE_INDEX = 0; /* ============ State Variables ============ */ mapping(ISetToken => AirdropSettings) public airdropSettings; /* ============ Constructor ============ */ constructor(IController _controller) public ModuleBase(_controller) {} /* ============ External Functions ============ */ /** * Absorb passed tokens into respective positions. If airdropFee defined, send portion to feeRecipient and portion to * protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true. * * @param _setToken Address of SetToken * @param _tokens Array of tokens to absorb */ function batchAbsorb(ISetToken _setToken, address[] memory _tokens) external nonReentrant onlyValidCaller(_setToken) onlyValidAndInitializedSet(_setToken) { _batchAbsorb(_setToken, _tokens); } /** * Absorb specified token into position. If airdropFee defined, send portion to feeRecipient and portion to * protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true. * * @param _setToken Address of SetToken * @param _token Address of token to absorb */ function absorb(ISetToken _setToken, address _token) external nonReentrant onlyValidCaller(_setToken) onlyValidAndInitializedSet(_setToken) { _absorb(_setToken, _token); } /** * SET MANAGER ONLY. Adds new tokens to be added to positions when absorb is called. * * @param _setToken Address of SetToken * @param _airdrop List of airdrops to add */ function addAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) { require(!isAirdropToken(_setToken, _airdrop), "Token already added."); airdropSettings[_setToken].airdrops.push(_airdrop); } /** * SET MANAGER ONLY. Removes tokens from list to be absorbed. * * @param _setToken Address of SetToken * @param _airdrop List of airdrops to remove */ function removeAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) { require(isAirdropToken(_setToken, _airdrop), "Token not added."); airdropSettings[_setToken].airdrops = airdropSettings[_setToken].airdrops.remove(_airdrop); } /** * SET MANAGER ONLY. Update whether manager allows other addresses to call absorb. * * @param _setToken Address of SetToken */ function updateAnyoneAbsorb(ISetToken _setToken) external onlyManagerAndValidSet(_setToken) { airdropSettings[_setToken].anyoneAbsorb = !airdropSettings[_setToken].anyoneAbsorb; } /** * SET MANAGER ONLY. Update address manager fees are sent to. * * @param _setToken Address of SetToken * @param _newFeeRecipient Address of new fee recipient */ function updateFeeRecipient( ISetToken _setToken, address _newFeeRecipient ) external onlySetManager(_setToken, msg.sender) onlyValidAndInitializedSet(_setToken) { require(_newFeeRecipient != address(0), "Passed address must be non-zero"); airdropSettings[_setToken].feeRecipient = _newFeeRecipient; } /** * SET MANAGER ONLY. Update airdrop fee percentage. * * @param _setToken Address of SetToken * @param _newFee Percentage, in preciseUnits, of new airdrop fee (1e16 = 1%) */ function updateAirdropFee( ISetToken _setToken, uint256 _newFee ) external onlySetManager(_setToken, msg.sender) onlyValidAndInitializedSet(_setToken) { require(_newFee < PreciseUnitMath.preciseUnit(), "Airdrop fee can't exceed 100%"); // Absorb all outstanding tokens before fee is updated _batchAbsorb(_setToken, airdropSettings[_setToken].airdrops); airdropSettings[_setToken].airdropFee = _newFee; } /** * SET MANAGER ONLY. Initialize module with SetToken and set initial airdrop tokens as well as specify * whether anyone can call absorb. * * @param _setToken Address of SetToken * @param _airdropSettings Struct of airdrop setting for Set including accepted airdrops, feeRecipient, * airdropFee, and indicating if anyone can call an absorb */ function initialize( ISetToken _setToken, AirdropSettings memory _airdropSettings ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_airdropSettings.airdrops.length > 0, "At least one token must be passed."); require(_airdropSettings.airdropFee <= PreciseUnitMath.preciseUnit(), "Fee must be <= 100%."); airdropSettings[_setToken] = _airdropSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Token's airdrop settings are deleted. * Airdrops are not absorbed. */ function removeModule() external override { delete airdropSettings[ISetToken(msg.sender)]; } /** * Get list of tokens approved to collect airdrops for the SetToken. * * @param _setToken Address of SetToken * @return Array of tokens approved for airdrops */ function getAirdrops(ISetToken _setToken) external view returns (address[] memory) { return _airdrops(_setToken); } /** * Get boolean indicating if token is approved for airdrops. * * @param _setToken Address of SetToken * @return Boolean indicating approval for airdrops */ function isAirdropToken(ISetToken _setToken, address _token) public view returns (bool) { return _airdrops(_setToken).contains(_token); } /* ============ Internal Functions ============ */ /** * Check token approved for airdrops then handle airdropped postion. */ function _absorb(ISetToken _setToken, address _token) internal { require(isAirdropToken(_setToken, _token), "Must be approved token."); _handleAirdropPosition(_setToken, _token); } function _batchAbsorb(ISetToken _setToken, address[] memory _tokens) internal { for (uint256 i = 0; i < _tokens.length; i++) { _absorb(_setToken, _tokens[i]); } } /** * Calculate amount of tokens airdropped since last absorption, then distribute fees and update position. * * @param _setToken Address of SetToken * @param _token Address of airdropped token */ function _handleAirdropPosition(ISetToken _setToken, address _token) internal { uint256 preFeeTokenBalance = ERC20(_token).balanceOf(address(_setToken)); uint256 amountAirdropped = preFeeTokenBalance.sub(_setToken.getDefaultTrackedBalance(_token)); if (amountAirdropped > 0) { (uint256 managerTake, uint256 protocolTake, uint256 totalFees) = _handleFees(_setToken, _token, amountAirdropped); uint256 newUnit = _getPostAirdropUnit(_setToken, preFeeTokenBalance, totalFees); _setToken.editDefaultPosition(_token, newUnit); emit ComponentAbsorbed(_setToken, _token, amountAirdropped, managerTake, protocolTake); } } /** * Calculate fee total and distribute between feeRecipient defined on module and the protocol feeRecipient. * * @param _setToken Address of SetToken * @param _component Address of airdropped component * @param _amountAirdropped Amount of tokens airdropped to the SetToken * @return Amount of airdropped tokens set aside for manager fees * @return Amount of airdropped tokens set aside for protocol fees * @return Total fees paid */ function _handleFees( ISetToken _setToken, address _component, uint256 _amountAirdropped ) internal returns (uint256, uint256, uint256) { uint256 airdropFee = airdropSettings[_setToken].airdropFee; if (airdropFee > 0) { uint256 managerTake = _amountAirdropped.preciseMul(airdropFee); uint256 protocolTake = ModuleBase.getModuleFee(AIRDROP_MODULE_PROTOCOL_FEE_INDEX, managerTake); uint256 netManagerTake = managerTake.sub(protocolTake); uint256 totalFees = netManagerTake.add(protocolTake); _setToken.invokeTransfer(_component, airdropSettings[_setToken].feeRecipient, netManagerTake); ModuleBase.payProtocolFeeFromSetToken(_setToken, _component, protocolTake); return (netManagerTake, protocolTake, totalFees); } else { return (0, 0, 0); } } /** * Retrieve new unit, which is the current balance less fees paid divided by total supply */ function _getPostAirdropUnit( ISetToken _setToken, uint256 _totalComponentBalance, uint256 _totalFeesPaid ) internal view returns(uint256) { uint256 totalSupply = _setToken.totalSupply(); return totalSupply.getDefaultPositionUnit(_totalComponentBalance.sub(_totalFeesPaid)); } /** * If absorption is confined to the manager, manager must be caller */ function _isValidCaller(ISetToken _setToken) internal view returns(bool) { return airdropSettings[_setToken].anyoneAbsorb || isSetManager(_setToken, msg.sender); } function _airdrops(ISetToken _setToken) internal view returns(address[] memory) { return airdropSettings[_setToken].airdrops; } }
Calculate amount of tokens airdropped since last absorption, then distribute fees and update position. _setToken Address of SetToken _token Address of airdropped token/
function _handleAirdropPosition(ISetToken _setToken, address _token) internal { uint256 preFeeTokenBalance = ERC20(_token).balanceOf(address(_setToken)); uint256 amountAirdropped = preFeeTokenBalance.sub(_setToken.getDefaultTrackedBalance(_token)); if (amountAirdropped > 0) { (uint256 managerTake, uint256 protocolTake, uint256 totalFees) = _handleFees(_setToken, _token, amountAirdropped); uint256 newUnit = _getPostAirdropUnit(_setToken, preFeeTokenBalance, totalFees); _setToken.editDefaultPosition(_token, newUnit); emit ComponentAbsorbed(_setToken, _token, amountAirdropped, managerTake, protocolTake); } }
1,804,281
./full_match/1/0xCF810239F6266316D4Cfe2E478cD8d6be03ae1A6/sources/contracts/Comptroller.sol
Transfer COMP to the user Note: If there is not enough COMP, we do not perform the transfer all. user The address of the user to transfer COMP to amount The amount of COMP to (possibly) transfer return The amount of COMP which was NOT transferred to the user/
function grantCompInternal(address user, uint amount) internal returns (uint) { Dop comp = Dop(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (amount > 0 && amount <= compRemaining) { comp.transfer(user, amount); return 0; } return amount; }
4,943,412
./full_match/3/0x8768F82F228269698f102F111b581A0B7018d688/sources/browser/DexToDexArb.sol
bytes4 c = bytes4(abc);bytes4 d = bytes4(keccak256("zzz"));bytes memory z = keccak256("zzz");bytes4 e = bytes4(b);bytes memory zz = 0x1254; LibBytes.writeAddress(a,a.length,address(this));return abi.encodePacked(a,address(this));
function show81() public view returns (bytes memory) { bytes memory a = bytes("1"); bytes memory abc = hex"12543466666776"; return abc; }
8,194,651
./full_match/84531/0xce6525630B6cBC45F7DdC204a59022d8E39f560E/sources/src/utils/TransferHelperUtils.sol
Sends ETH to a recipient, making conservative estimates to not run out of gas recipient The address to send ETH to value The amount of ETH to send
function safeSendETH(address recipient, uint256 value, uint256 gasLimit) internal returns (bool success) { }
11,523,143
//SPDX-License-Identifier:MIT pragma solidity ^0.6.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256){ if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b,"Calculation error"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256){ // Solidity only automatically asserts when dividing by 0 require(b > 0,"Calculation error"); uint256 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,"Calculation error"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256){ uint256 c = a + b; require(c >= a,"Calculation error"); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256){ require(b != 0,"Calculation error"); return a % b; } } /** * @title ILPToken * @dev Contract interface for LP token contract */ abstract contract ILPToken { function balanceOf(address) public virtual returns (uint256); function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function approve(address , uint256) public virtual returns (bool); } /** * @title IToken * @dev Contract interface for token contract */ abstract contract IToken { function balanceOf(address) public virtual returns (uint256); function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function approve(address , uint256) public virtual returns (bool); } /** * @title CLIQWETHLPStaking * @dev CLIQWETHLP Staking Contract for LP token staking */ contract CLIQWETHLPStaking { using SafeMath for uint256; address private _owner; // variable for Owner of the Contract. uint256 private _withdrawTime; // variable to manage withdraw time for Token uint256 constant public PERIOD_SILVER = 90; // variable constant for time period managemnt uint256 constant public PERIOD_GOLD = 180; // variable constant for time period managemnt uint256 constant public PERIOD_PLATINUM = 270; // variable constant for time period managemnt uint256 constant public WITHDRAW_TIME_SILVER = 45 * 1 days; // variable constant to manage withdraw time lock up uint256 constant public WITHDRAW_TIME_GOLD = 90 * 1 days; // variable constant to manage withdraw time lock up uint256 constant public WITHDRAW_TIME_PLATINUM = 135 * 1 days; // variable constant to manage withdraw time lock up uint256 public TOKEN_REWARD_PERCENT_SILVER = 21788328; // variable constant to manage token reward percentage for silver uint256 public TOKEN_REWARD_PERCENT_GOLD = 67332005; // variable constant to manage token reward percentage for gold uint256 public TOKEN_REWARD_PERCENT_PLATINUM = 178233538; // variable constant to manage token reward percentage for platinum uint256 public TOKEN_PENALTY_PERCENT_SILVER = 10894164; // variable constant to manage token penalty percentage for silver uint256 public TOKEN_PENALTY_PERCENT_GOLD = 23566201; // variable constant to manage token penalty percentage for gold uint256 public TOKEN_PENALTY_PERCENT_PLATINUM = 44558384; // variable constant to manage token penalty percentage for platinum // events to handle staking pause or unpause for token event Paused(); event Unpaused(); /* * --------------------------------------------------------------------------------------------------------------------------- * Functions for owner. * --------------------------------------------------------------------------------------------------------------------------- */ /** * @dev get address of smart contract owner * @return address of owner */ function getowner() public view returns (address) { return _owner; } /** * @dev modifier to check if the message sender is owner */ modifier onlyOwner() { require(isOwner(),"You are not authenticate to make this transfer"); _; } /** * @dev Internal function for modifier */ function isOwner() internal view returns (bool) { return msg.sender == _owner; } /** * @dev Transfer ownership of the smart contract. For owner only * @return request status */ function transferOwnership(address newOwner) public onlyOwner returns (bool){ _owner = newOwner; return true; } /* * --------------------------------------------------------------------------------------------------------------------------- * Functionality of Constructor and Interface * --------------------------------------------------------------------------------------------------------------------------- */ // constructor to declare owner of the contract during time of deploy constructor() public { _owner = msg.sender; } // Interface declaration for contract ILPToken ilptoken; IToken itoken; // function to set Contract Address for Token Transfer Functionality for LP Token and Cliq Token function setContractAddresses(address lpTokenContractAddress, address tokenContractAddress) external onlyOwner returns(bool){ ilptoken = ILPToken(lpTokenContractAddress); itoken = IToken(tokenContractAddress); return true; } /* * ---------------------------------------------------------------------------------------------------------------------------- * Owner functions of get value, set value and other Functionality * ---------------------------------------------------------------------------------------------------------------------------- */ // function to add token reward in contract function addTokenReward(uint256 token) external onlyOwner returns(bool){ _ownerTokenAllowance = _ownerTokenAllowance.add(token); itoken.transferFrom(msg.sender, address(this), token); return true; } // function to withdraw added token reward in contract function withdrawAddedTokenReward(uint256 token) external onlyOwner returns(bool){ require(token < _ownerTokenAllowance,"Value is not feasible, Please Try Again!!!"); _ownerTokenAllowance = _ownerTokenAllowance.sub(token); itoken.transfer(msg.sender, token); return true; } // function to get token reward in contract function getTokenReward() public view returns(uint256){ return _ownerTokenAllowance; } // function to pause Token Staking function pauseTokenStaking() public onlyOwner { tokenPaused = true; emit Paused(); } // function to unpause Token Staking function unpauseTokenStaking() public onlyOwner { tokenPaused = false; emit Unpaused(); } // function to set values function setManager(uint256 tokenStakingCount, uint256 tokenTotalDays, address tokenStakingAddress, uint256 tokenStakingStartTime, uint256 tokenStakingEndTime, uint256 usertokens) external onlyOwner returns(bool){ _tokenStakingCount = tokenStakingCount; _tokenTotalDays[_tokenStakingCount] = tokenTotalDays; _tokenStakingAddress[_tokenStakingCount] = tokenStakingAddress; _tokenStakingId[tokenStakingAddress].push(_tokenStakingCount); _tokenStakingEndTime[_tokenStakingCount] = tokenStakingEndTime; _tokenStakingStartTime[_tokenStakingCount] = tokenStakingStartTime; _usersTokens[_tokenStakingCount] = usertokens; _TokenTransactionstatus[_tokenStakingCount] = false; totalStakedToken = totalStakedToken.add(usertokens); totalTokenStakesInContract = totalTokenStakesInContract.add(usertokens); return true; } // function to set reward percent function setRewardPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){ require(silver != 0 && gold != 0 && platinum !=0,"Invalid Reward Value or Zero value, Please Try Again!!!"); TOKEN_REWARD_PERCENT_SILVER = silver; TOKEN_REWARD_PERCENT_GOLD = gold; TOKEN_REWARD_PERCENT_PLATINUM = platinum; return true; } // function to set penalty percent function setPenaltyPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){ require(silver != 0 && gold != 0 && platinum !=0,"Invalid Penalty Value or Zero value, Please Try Again!!!"); TOKEN_PENALTY_PERCENT_SILVER = silver; TOKEN_PENALTY_PERCENT_GOLD = gold; TOKEN_PENALTY_PERCENT_PLATINUM = platinum; return true; } // function to withdraw LP token from the contract function withdrawLPToken(uint256 amount) external onlyOwner returns(bool){ ilptoken.transfer(msg.sender,amount); return true; } // function to withdraw token from the contract function withdrawToken(uint256 amount) external onlyOwner returns(bool){ itoken.transfer(msg.sender,amount); return true; } // function to withdraw ETH from the contract function withdrawETH() external onlyOwner returns(bool){ msg.sender.transfer(address(this).balance); return true; } /* * ---------------------------------------------------------------------------------------------------------------------------- * Variable, Mapping for Token Staking Functionality * ---------------------------------------------------------------------------------------------------------------------------- */ // mapping for users with id => address Staking Address mapping (uint256 => address) private _tokenStakingAddress; // mapping for users with address => id staking id mapping (address => uint256[]) private _tokenStakingId; // mapping for users with id => Staking Time mapping (uint256 => uint256) private _tokenStakingStartTime; // mapping for users with id => End Time mapping (uint256 => uint256) private _tokenStakingEndTime; // mapping for users with id => Tokens mapping (uint256 => uint256) private _usersTokens; // mapping for users with id => Status mapping (uint256 => bool) private _TokenTransactionstatus; // mapping to keep track of final withdraw value of staked token mapping(uint256=>uint256) private _finalTokenStakeWithdraw; // mapping to keep track total number of staking days mapping(uint256=>uint256) private _tokenTotalDays; // variable to keep count of Token Staking uint256 private _tokenStakingCount = 0; // variable to keep track on reward added by owner uint256 private _ownerTokenAllowance = 0; // variable for token time management uint256 private _tokentime; // variable for token staking pause and unpause mechanism bool public tokenPaused = false; // variable for total Token staked by user uint256 public totalStakedToken = 0; // variable for total stake token in contract uint256 public totalTokenStakesInContract = 0; // modifier to check the user for staking || Re-enterance Guard modifier tokenStakeCheck(uint256 tokens, uint256 timePeriod){ require(tokens > 0, "Invalid Token Amount, Please Try Again!!! "); require(timePeriod == PERIOD_SILVER || timePeriod == PERIOD_GOLD || timePeriod == PERIOD_PLATINUM, "Enter the Valid Time Period and Try Again !!!"); _; } /* * ------------------------------------------------------------------------------------------------------------------------------ * Functions for Token Staking Functionality * ------------------------------------------------------------------------------------------------------------------------------ */ // function to performs staking for user tokens for a specific period of time function stakeToken(uint256 tokens, uint256 time) public tokenStakeCheck(tokens, time) returns(bool){ require(tokenPaused == false, "Staking is Paused, Please try after staking get unpaused!!!"); _tokentime = now + (time * 1 days); _tokenStakingCount = _tokenStakingCount + 1; _tokenTotalDays[_tokenStakingCount] = time; _tokenStakingAddress[_tokenStakingCount] = msg.sender; _tokenStakingId[msg.sender].push(_tokenStakingCount); _tokenStakingEndTime[_tokenStakingCount] = _tokentime; _tokenStakingStartTime[_tokenStakingCount] = now; _usersTokens[_tokenStakingCount] = tokens; _TokenTransactionstatus[_tokenStakingCount] = false; totalStakedToken = totalStakedToken.add(tokens); totalTokenStakesInContract = totalTokenStakesInContract.add(tokens); ilptoken.transferFrom(msg.sender, address(this), tokens); return true; } // function to get staking count for token function getTokenStakingCount() public view returns(uint256){ return _tokenStakingCount; } // function to get total Staked tokens function getTotalStakedToken() public view returns(uint256){ return totalStakedToken; } // function to calculate reward for the message sender for token function getTokenRewardDetailsByStakingId(uint256 id) public view returns(uint256){ if(_tokenTotalDays[id] == PERIOD_SILVER) { return (_usersTokens[id]*TOKEN_REWARD_PERCENT_SILVER/100000000); } else if(_tokenTotalDays[id] == PERIOD_GOLD) { return (_usersTokens[id]*TOKEN_REWARD_PERCENT_GOLD/100000000); } else if(_tokenTotalDays[id] == PERIOD_PLATINUM) { return (_usersTokens[id]*TOKEN_REWARD_PERCENT_PLATINUM/100000000); } else{ return 0; } } // function to calculate penalty for the message sender for token function getTokenPenaltyDetailByStakingId(uint256 id) public view returns(uint256){ if(_tokenStakingEndTime[id] > now){ if(_tokenTotalDays[id]==PERIOD_SILVER){ return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_SILVER/100000000); } else if(_tokenTotalDays[id] == PERIOD_GOLD) { return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_GOLD/100000000); } else if(_tokenTotalDays[id] == PERIOD_PLATINUM) { return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_PLATINUM/100000000); } else { return 0; } } else{ return 0; } } // function for withdrawing staked tokens function withdrawStakedTokens(uint256 stakingId) public returns(bool) { require(_tokenStakingAddress[stakingId] == msg.sender,"No staked token found on this address and ID"); require(_TokenTransactionstatus[stakingId] != true,"Either tokens are already withdrawn or blocked by admin"); if(_tokenTotalDays[stakingId] == PERIOD_SILVER){ require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_SILVER, "Unable to Withdraw Staked token before 45 days of staking start time, Please Try Again Later!!!"); _TokenTransactionstatus[stakingId] = true; if(now >= _tokenStakingEndTime[stakingId]){ _finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId)); ilptoken.transfer(msg.sender,_usersTokens[stakingId]); itoken.transfer(msg.sender,getTokenRewardDetailsByStakingId(stakingId)); totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]); _ownerTokenAllowance = _ownerTokenAllowance.sub(getTokenRewardDetailsByStakingId(stakingId)); } else { _finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId)); ilptoken.transfer(msg.sender,_usersTokens[stakingId]); itoken.transfer(msg.sender,getTokenPenaltyDetailByStakingId(stakingId)); totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]); _ownerTokenAllowance = _ownerTokenAllowance.sub(getTokenPenaltyDetailByStakingId(stakingId)); } } else if(_tokenTotalDays[stakingId] == PERIOD_GOLD){ require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_GOLD, "Unable to Withdraw Staked token before 90 days of staking start time, Please Try Again Later!!!"); _TokenTransactionstatus[stakingId] = true; if(now >= _tokenStakingEndTime[stakingId]){ _finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId)); ilptoken.transfer(msg.sender,_usersTokens[stakingId]); itoken.transfer(msg.sender,getTokenRewardDetailsByStakingId(stakingId)); totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]); _ownerTokenAllowance = _ownerTokenAllowance.sub(getTokenRewardDetailsByStakingId(stakingId)); } else { _finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId)); ilptoken.transfer(msg.sender,_usersTokens[stakingId]); itoken.transfer(msg.sender,getTokenPenaltyDetailByStakingId(stakingId)); totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]); _ownerTokenAllowance = _ownerTokenAllowance.sub(getTokenPenaltyDetailByStakingId(stakingId)); } } else if(_tokenTotalDays[stakingId] == PERIOD_PLATINUM){ require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_PLATINUM, "Unable to Withdraw Staked token before 135 days of staking start time, Please Try Again Later!!!"); _TokenTransactionstatus[stakingId] = true; if(now >= _tokenStakingEndTime[stakingId]){ _finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId)); ilptoken.transfer(msg.sender,_usersTokens[stakingId]); itoken.transfer(msg.sender,getTokenRewardDetailsByStakingId(stakingId)); totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]); _ownerTokenAllowance = _ownerTokenAllowance.sub(getTokenRewardDetailsByStakingId(stakingId)); } else { _finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId)); ilptoken.transfer(msg.sender,_usersTokens[stakingId]); itoken.transfer(msg.sender,getTokenPenaltyDetailByStakingId(stakingId)); totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]); _ownerTokenAllowance = _ownerTokenAllowance.sub(getTokenPenaltyDetailByStakingId(stakingId)); } } else { return false; } return true; } // function to get Final Withdraw Staked value for token function getFinalTokenStakeWithdraw(uint256 id) public view returns(uint256){ return _finalTokenStakeWithdraw[id]; } // function to get total token stake in contract function getTotalTokenStakesInContract() public view returns(uint256){ return totalTokenStakesInContract; } /* * ------------------------------------------------------------------------------------------------------------------------------- * Get Functions for Stake Token Functionality * ------------------------------------------------------------------------------------------------------------------------------- */ // function to get Token Staking address by id function getTokenStakingAddressById(uint256 id) external view returns (address){ require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!"); return _tokenStakingAddress[id]; } // function to get Token staking id by address function getTokenStakingIdByAddress(address add) external view returns(uint256[] memory){ require(add != address(0),"Invalid Address, Pleae Try Again!!!"); return _tokenStakingId[add]; } // function to get Token Staking Starting time by id function getTokenStakingStartTimeById(uint256 id) external view returns(uint256){ require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!"); return _tokenStakingStartTime[id]; } // function to get Token Staking Ending time by id function getTokenStakingEndTimeById(uint256 id) external view returns(uint256){ require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!"); return _tokenStakingEndTime[id]; } // function to get Token Staking Total Days by Id function getTokenStakingTotalDaysById(uint256 id) external view returns(uint256){ require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!"); return _tokenTotalDays[id]; } // function to get Staking tokens by id function getStakingTokenById(uint256 id) external view returns(uint256){ require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!"); return _usersTokens[id]; } // function to get Token lockstatus by id function getTokenLockStatus(uint256 id) external view returns(bool){ require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!"); return _TokenTransactionstatus[id]; } }
function to get Token lockstatus by id
function getTokenLockStatus(uint256 id) external view returns(bool){ require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!"); return _TokenTransactionstatus[id]; }
6,257,584
// 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); } 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); } pragma solidity ^0.8.4; abstract contract AccessControl { event RoleGranted(uint8 role, address account, address admin); /// @notice Fee Decimals look like this: let's assume that you want set 1% transaction fee /// @notice well, the decimals are set to 6, so you should set fee equal to (1 * 10^6) to get 1% transaction fee /// @dev Later to calculate the %, given amount of trasaction fee will be divided by (10^6 * 100) (to get numeral part of percent) mapping(uint8 => uint32) public roleTxnFee; mapping(address => uint8) public addressToRole; uint8 public constant FEE_DECIMALS = 6; uint8 public constant USER = 0; // DEFAULT uint8 public constant ADMIN = 1; // OWNER uint8 public constant ROLE_1 = 2; // CUSTOM_ROLE_1 uint8 public constant ROLE_2 = 3; // CUSTOM_ROLE_2 uint8 public constant ROLE_3 = 4; // CUSTOM_ROLE_3 uint8 public constant ROLE_4 = 5; // CUSTOM_ROLE_4 uint8 public constant ROLE_5 = 6; // CUSTOM_ROLE_5 uint8 public constant ROLE_6 = 7; // CUSTOM_ROLE_6 uint8 public constant ROLE_7 = 8; // CUSTOM_ROLE_7 uint8 public constant ROLE_8 = 9; // CUSTOM_ROLE_8 event RoleTransactionFeeChanged(uint8 role, uint32 newTxhFee); /** * @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 onlyAdmin() { require(addressToRole[msg.sender] == ADMIN, "Function caller is not an ADMIN"); _; } /** * @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(uint8 role, address account) public onlyAdmin { require(addressToRole[account] != role, "account already has that role"); _grantRole(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(uint8 role, address account) internal { _grantRole(role, account); } function _grantRole(uint8 role, address account) private { addressToRole[account] = role; emit RoleGranted(role, account, msg.sender); } /// @notice Sets given transaction fee to the role /// @param role The uint32 role. /// @param txhFee The amount of fee in percent. function setRoleTxnFee(uint8 role, uint32 txhFee) public onlyAdmin { require(txhFee <= 100000000, "[Transaction Fee]: Fee cannot be more than 100%"); roleTxnFee[role] = txhFee; emit RoleTransactionFeeChanged(role, txhFee); } } pragma solidity ^0.8.4; interface IERC20MintBurn is IERC20Metadata { function mint(address to, uint256 amount) external; function burn(address userAddress, uint256 amount) external; } pragma solidity ^0.8.4; contract GoldToken is IERC20MintBurn, AccessControl { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; address public transactionFeeCollector; address public bridgeAddress; string private _name; string private _symbol; event TransactionFeeCollected(uint256 amount); modifier onlyBridge { require(msg.sender == bridgeAddress, "Only Bridge can call this function"); _; } constructor() { _name = "GOGO"; _symbol = "GOGO"; _setupRole(ADMIN, msg.sender); // Sets role admin to deployer } function setBridgeAddress(address newBridgeAddress) external onlyAdmin { require(newBridgeAddress != bridgeAddress, "Provided address is current bridge address"); bridgeAddress = newBridgeAddress; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its ROLE_3 representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a ROLE_3 as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public pure override returns (uint8) { return 18; } /** * @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 override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view 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 override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, msg.sender, currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(msg.sender, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } uint256 transactionFeeCost = (amount * roleTxnFee[addressToRole[sender]]) / 100000000; _balances[transactionFeeCollector] += transactionFeeCost; // amount * (transactionFeePercent / 100) _balances[recipient] += amount - transactionFeeCost; // amount - amount * transactionFee * AccessControl.feeDecimalMultiplier emit TransactionFeeCollected(transactionFeeCost); emit Transfer(sender, recipient, amount - transactionFeeCost); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @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 { 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); } /// @notice Sets new transaction fee collector address /// @param newAddress The new transaction fee collector address function setTransactionFeeCollector(address newAddress) public onlyAdmin { transactionFeeCollector = newAddress; } function mint(address to, uint256 amount) external onlyBridge override { _mint(to, amount); } function burn(address userAddress, uint256 amount) external onlyBridge override { _burn(userAddress, amount); } }
Destroys `amount` tokens from `account`, reducing the total supply. Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address. - `account` must have at least `amount` tokens./
function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); }
12,266,926
// Based on the smart contract for CryptoPunks: // https://github.com/larvalabs/cryptopunks/blob/master/contracts/CryptoPunksMarket.sol // Given that the CryptoPunks smart contract has performed well so far, // I attempted to make as few changes as possible. // Security upgrades include: // Locked pragma to Solidity 0.7.4 (and added all necessary syntax upgrades) // Added circuit breaker (owner only privilege) // Changed all if-then-throw statements to require statements // Efficiency upgrades include: // Variable packing (within reason) // Reduced some variables to smaller size (e.g., uint --> uint16, string --> bytes8) // Other changes include: // Changed variable names to represent tulips // @author Miguel Opeña // SPDX-License-Identifier: MIT pragma solidity 0.7.4; contract NFTulipsMarket { // Use this hash to verify the image file containing all the tulips string public imageHash = "b929f0a772b476441f055c878ba2080ecb10dfd2f103fef876372946660c58fb"; // Use this hash to verify the generative algorithm to create previous image string public codeHash = "39dce9989126cb2d126e125a7c17de01200fcb7ea8e37705985d84cb4257487c"; address admin; bool private stopped = false; bytes8 public name = "NFTulips"; uint16 public totalSupply = 10000; bool public allTulipsAssigned = false; uint16 public tulipsRemainingToAssign = 10000; //mapping (address => uint) public addressToTulipIndex; mapping (uint16 => address) public tulipIndexToAddress; /* This creates an array with all balances */ mapping (address => uint) public balanceOf; struct Offer { bool isForSale; uint16 tulipIndex; address seller; uint minValue; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint16 tulipIndex; address bidder; uint value; } // A record of tulips that are offered for sale at a specific minimum value, and perhaps to a specific person mapping (uint16 => Offer) public tulipsOfferedForSale; // A record of the highest tulip bid mapping (uint16 => Bid) public tulipBids; mapping (address => uint) public pendingWithdrawals; event Assign(address indexed to, uint16 tulipIndex); event Transfer(address indexed from, address indexed to, uint value); event TulipTransfer(address indexed from, address indexed to, uint16 tulipIndex); event TulipOffered(uint16 indexed tulipIndex, uint minValue, address indexed toAddress); event TulipBidEntered(uint16 indexed tulipIndex, uint value, address indexed fromAddress); event TulipBidWithdrawn(uint16 indexed tulipIndex, uint value, address indexed fromAddress); event TulipBought(uint16 indexed tulipIndex, uint value, address indexed fromAddress, address indexed toAddress); event TulipNoLongerForSale(uint16 indexed tulipIndex); // Admin-only privileges modifier isAdmin() { require(msg.sender == admin, "Admin only!"); _; } // Circuit breaker modifier modifier stopInEmergency { require(!stopped, "Emergency circuit breaker activated; contact admin!"); _; } // Initialize contract; assign all tulips to admin; offer for sale at 0.05 ETH apiece constructor() { admin = msg.sender; } // Circuit breaker activation function toggleContractActive() isAdmin public { stopped = !stopped; } // Set initial owner (to) of given tulip (tulipIndex) function setInitialOwner(address to, uint16 tulipIndex) isAdmin public { require(!allTulipsAssigned, "All tulips already assigned"); require(tulipIndex < totalSupply, "Invalid tulip index"); if (tulipIndexToAddress[tulipIndex] != to) { if (tulipIndexToAddress[tulipIndex] != address(0)) { balanceOf[tulipIndexToAddress[tulipIndex]]--; } else { tulipsRemainingToAssign--; } tulipIndexToAddress[tulipIndex] = to; balanceOf[to]++; emit Assign(to, tulipIndex); } } // Set initial owner (addresses[i]) of each tulip (indices[i]) function setInitialOwners(address[] calldata addresses, uint16[] calldata indices) isAdmin public { uint n = addresses.length; for (uint16 i = 0; i < n; i++) { setInitialOwner(addresses[i], indices[i]); } } // Manually toggle when all initial owners assigned function allInitialOwnersAssigned() isAdmin public { allTulipsAssigned = true; } // Buyer (msg.sender) claims tulip (tulipIndex) for themselves, at zero cost function getTulip(uint16 tulipIndex) stopInEmergency public { require(!allTulipsAssigned, "All tulips already assigned"); require(tulipsRemainingToAssign > 0, "No remaining tulips to assign"); require(tulipIndexToAddress[tulipIndex] == address(0), "Tulip must be unclaimed"); require(tulipIndex < totalSupply, "Invalid tulip index"); tulipIndexToAddress[tulipIndex] = msg.sender; balanceOf[msg.sender]++; tulipsRemainingToAssign--; emit Assign(msg.sender, tulipIndex); } // Tulip owner (msg.sender) transfers tulip (tulipIndex) to an address (to) for free function transferTulip(address to, uint16 tulipIndex) stopInEmergency public { require(allTulipsAssigned, "All tulips must be assigned"); require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only"); require(tulipIndex < totalSupply, "Invalid tulip index"); if (tulipsOfferedForSale[tulipIndex].isForSale) { tulipNoLongerForSale(tulipIndex); } tulipIndexToAddress[tulipIndex] = to; balanceOf[msg.sender]--; balanceOf[to]++; emit Transfer(msg.sender, to, 1); emit TulipTransfer(msg.sender, to, tulipIndex); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. // Bid memory bid = tulipBids[tulipIndex]; if (tulipBids[tulipIndex].bidder == to) { // Kill bid and refund value pendingWithdrawals[to] += tulipBids[tulipIndex].value; tulipBids[tulipIndex] = Bid(false, tulipIndex, address(0), 0); } } // Tulip owner (msg.sender) marks tulip (tulipIndex) as not-for-sale function tulipNoLongerForSale(uint16 tulipIndex) stopInEmergency public { require(allTulipsAssigned, "All tulips must be assigned"); require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only"); require(tulipIndex < totalSupply, "Invalid tulip index"); tulipsOfferedForSale[tulipIndex] = Offer(false, tulipIndex, msg.sender, 0, address(0)); emit TulipNoLongerForSale(tulipIndex); } // Tulip owner (msg.sender) marks tulip (tulipIndex) as for sale, at a minimum price (minSalePriceInWei) function offerTulipForSale(uint16 tulipIndex, uint minSalePriceInWei) stopInEmergency public { require(allTulipsAssigned, "All tulips must be assigned"); require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only"); require(tulipIndex < totalSupply, "Invalid tulip index"); tulipsOfferedForSale[tulipIndex] = Offer(true, tulipIndex, msg.sender, minSalePriceInWei, address(0)); emit TulipOffered(tulipIndex, minSalePriceInWei, address(0)); } // Tulip owner (msg.sender) marks tulip (tulipIndex) as for sale, at a minimum price (minSalePriceInWei), to a specific address (toAddress) function offerTulipForSaleToAddress(uint16 tulipIndex, uint minSalePriceInWei, address toAddress) stopInEmergency public { require(allTulipsAssigned, "All tulips must be assigned"); require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only"); require(tulipIndex < totalSupply, "Invalid tulip index"); tulipsOfferedForSale[tulipIndex] = Offer(true, tulipIndex, msg.sender, minSalePriceInWei, toAddress); emit TulipOffered(tulipIndex, minSalePriceInWei, toAddress); } // Buyer (msg.sender) buys tulip (tulipIndex) for themselves function buyTulip(uint16 tulipIndex) stopInEmergency payable public { require(allTulipsAssigned, "All tulips must be assigned"); require(tulipIndex < totalSupply, "Invalid tulip index"); // Offer memory offer = tulipsOfferedForSale[tulipIndex]; require(tulipsOfferedForSale[tulipIndex].isForSale, "Tulip must be for sale"); require(tulipsOfferedForSale[tulipIndex].onlySellTo == address(0) || tulipsOfferedForSale[tulipIndex].onlySellTo == msg.sender, "Invalid offer.onlySellTo address"); require(msg.value >= tulipsOfferedForSale[tulipIndex].minValue, "Insufficient ETH attached"); require(tulipsOfferedForSale[tulipIndex].seller == tulipIndexToAddress[tulipIndex], "Seller no longer owner"); address seller = tulipsOfferedForSale[tulipIndex].seller; tulipIndexToAddress[tulipIndex] = msg.sender; balanceOf[seller]--; balanceOf[msg.sender]++; emit Transfer(seller, msg.sender, 1); tulipNoLongerForSale(tulipIndex); pendingWithdrawals[seller] += msg.value; emit TulipBought(tulipIndex, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. // Bid memory bid = tulipBids[tulipIndex]; if (tulipBids[tulipIndex].bidder == msg.sender) { // Kill bid and refund value pendingWithdrawals[msg.sender] += tulipBids[tulipIndex].value; tulipBids[tulipIndex] = Bid(false, tulipIndex, address(0), 0); } } // Seller withdraws the funds under their address function withdraw() public { require(allTulipsAssigned, "All tulips must be assigned"); uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; // Refund the purchase money (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed"); } // Bidder (msg.sender) enters bid for tulip (tulipIndex) function enterBidForTulip(uint16 tulipIndex) stopInEmergency payable public { require(allTulipsAssigned, "All tulips must be assigned"); require(tulipIndex < totalSupply, "Invalid tulip index"); require(tulipIndexToAddress[tulipIndex] != address(0), "Zero address cannot bid"); require(tulipIndexToAddress[tulipIndex] != msg.sender, "Owner cannot bid on own tulip"); require(msg.value != 0, "msg.value cannot be zero"); // Bid memory existing = tulipBids[tulipIndex]; require(msg.value > tulipBids[tulipIndex].value, "msg.value is too low"); if (tulipBids[tulipIndex].value > 0) { // Refund the failing bid pendingWithdrawals[tulipBids[tulipIndex].bidder] += tulipBids[tulipIndex].value; } tulipBids[tulipIndex] = Bid(true, tulipIndex, msg.sender, msg.value); emit TulipBidEntered(tulipIndex, msg.value, msg.sender); } // Tulip owner (msg.sender) accepts bid (minPrice) for tulip (tulipIndex) function acceptBidForTulip(uint16 tulipIndex, uint minPrice) stopInEmergency public { require(allTulipsAssigned, "All tulips must be assigned"); require(tulipIndex < totalSupply, "Invalid tulip index"); require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only"); address seller = msg.sender; // Bid memory bid = tulipBids[tulipIndex]; require(tulipBids[tulipIndex].value > 0, "Bid value cannot be zero"); require(tulipBids[tulipIndex].value >= minPrice, "Bid value is too low"); tulipIndexToAddress[tulipIndex] = tulipBids[tulipIndex].bidder; balanceOf[seller]--; balanceOf[tulipBids[tulipIndex].bidder]++; emit Transfer(seller, tulipBids[tulipIndex].bidder, 1); tulipsOfferedForSale[tulipIndex] = Offer(false, tulipIndex, tulipBids[tulipIndex].bidder, 0, address(0)); uint amount = tulipBids[tulipIndex].value; tulipBids[tulipIndex] = Bid(false, tulipIndex, address(0), 0); pendingWithdrawals[seller] += amount; emit TulipBought(tulipIndex, tulipBids[tulipIndex].value, seller, tulipBids[tulipIndex].bidder); } // Bidder (msg.sender) withdraws a bid they previously placed function withdrawBidForTulip(uint16 tulipIndex) public { require(allTulipsAssigned, "All tulips must be assigned"); require(tulipIndex < totalSupply, "Invalid tulip index"); require(tulipIndexToAddress[tulipIndex] != address(0), "Zero address cannot bid"); require(tulipIndexToAddress[tulipIndex] != msg.sender, "Owner cannot bid on own tulip"); // Bid memory bid = tulipBids[tulipIndex]; require(tulipBids[tulipIndex].bidder == msg.sender, "Only bidder can withdraw their bid"); emit TulipBidWithdrawn(tulipIndex, tulipBids[tulipIndex].value, msg.sender); uint amount = tulipBids[tulipIndex].value; tulipBids[tulipIndex] = Bid(false, tulipIndex, address(0), 0); // Refund the bid money (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed"); } }
Circuit breaker activation
function toggleContractActive() isAdmin public { stopped = !stopped; }
7,316,648
pragma solidity ^0.4.24; import "zos-lib/contracts/Initializable.sol"; import "openzeppelin-eth/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-eth/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-eth/contracts/math/SafeMath.sol"; import "openzeppelin-eth/contracts/utils/Address.sol"; /** * @title OldVouching * @dev Contract for staking tokens against dependencies. */ contract OldVouching is Initializable { /** * @dev Emitted when the ownership of this contract is transferred. * @param oldOwner Address of the old owner. * @param newOwner Address of the new owner. */ event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); /** * @dev Emitted when a new dependency has been created. * @param nameHash bytes32 hash of the name of the dependency. * @param name String representing the name of the dependency. * @param owner Address that owns the created dependency. * @param dependencyAddress Address of the created dependency. * @param initialStake uint256 representing the amount vouched in the creation of the dependency. */ event DependencyCreated( bytes32 indexed nameHash, string name, address indexed owner, address indexed dependencyAddress, uint256 initialStake ); /** * @dev Emitted when the owner of a dependency vouches for it. * @param nameHash bytes32 hash of the name of the dependency. * @param amount uint256 with the amount vouched on the dependency. */ event Vouched(bytes32 indexed nameHash, uint256 amount); /** * @dev Emitted when the owner of a dependency removes their vouch. * @param nameHash bytes32 hash of the name of the dependency. * @param amount uint256 with the amount of stake that has been removed from the dependency. */ event Unvouched(bytes32 indexed nameHash, uint256 amount); /** * @dev Emitted when a dependency has been removed from the registry. * @param nameHash bytes32 nameHash hash of the name of the dependency. */ event DependencyRemoved(bytes32 indexed nameHash); using SafeMath for uint256; using SafeERC20 for ERC20; using Address for address; /** * @dev Struct that represents a particular dependency, with its address, owner and amount of tokens vouched. */ struct Dependency { address owner; address dependencyAddress; uint256 stake; } /** * @dev Maps dependency Dependency structs by name. */ mapping (string => Dependency) private _registry; /** * @dev Tracks taken dependency names. */ mapping (string => bool) private _takenDependencyNames; /** * @dev Defines the minimum initial amount of vouched tokens a dependency can have when being created. */ uint256 private _minimumStake; /** * @dev The token used for vouching on dependencies. */ ERC20 private _token; /** * @dev Modifier that restricts access to the owner of a specific dependency. * @param name String specifying the dependency to restrict access to. */ modifier onlyDependencyOwner(string name) { require(msg.sender == _registry[name].owner, "Sender must be the dependency owner"); _; } /** * @dev Initializer function. Called only once when a proxy for the contract is created. * @param minimumStake uint256 that defines the minimum initial amount of vouched tokens a dependency can have when being created. * @param token ERC20 token to be used for vouching on dependencies. */ function initialize(uint256 minimumStake, ERC20 token) initializer public { require(token != address(0), "Token address cannot be zero"); _minimumStake = minimumStake; _token = token; } /** * @dev Tells the the initial minimum amount of vouched tokens a dependency can have when being created. * @return A uint256 number with the minimumStake value. */ function minimumStake() public view returns(uint256) { return _minimumStake; } /** * @dev Tells the ERC20 token being used for vouching. * @return The address of the ERC20 token being used for vouching. */ function token() public view returns(ERC20) { return _token; } /** * @dev Tells the dependency associated to a given name. * @param name String representing the dependency. * @return Tuple representing the elements of a Dependency struct. */ function getDependency(string name) public view returns(address, address, uint256) { return ( _registry[name].dependencyAddress, _registry[name].owner, _registry[name].stake ); } /** * @dev Creates a new dependency and performs an initial vouch. * @param name String that will represent the dependency. Must be unique. * @param owner Address that will own the dependency. * @param dependencyAddress Address of the dependency. * @param initialStake uint256 to be staked initially. Must be larger than or equal to minimumStake. */ function create(string name, address owner, address dependencyAddress, uint256 initialStake) external { require(initialStake >= _minimumStake, "Initial stake must be equal or greater than minimum stake"); require(owner != address(0), "Owner address cannot be zero"); require(dependencyAddress != address(0), "Dependency address cannot be zero"); require(dependencyAddress.isContract(), "Dependencies must be contracts"); require(!_takenDependencyNames[name], "Given dependency name is already registered"); _takenDependencyNames[name] = true; _registry[name] = Dependency(owner, dependencyAddress, initialStake); _token.safeTransferFrom(owner, this, initialStake); emit DependencyCreated(keccak256(abi.encodePacked(name)), name, owner, dependencyAddress, initialStake); } /** * @dev Transfers ownership of a dependency. Can only be called by the current owner of the dependency. * @param name String representing the dependency. * @param newOwner Address of the new owner. */ function transferOwnership(string name, address newOwner) external onlyDependencyOwner(name) { require(newOwner != address(0), "New owner address cannot be zero"); _registry[name].owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } /** * @dev Stakes tokens for a given dependency. Can only be performed by the dependency owner. * @param name String that represents the dependency. * @param amount uint256 with the amount that is to be vouched. */ function vouch(string name, uint256 amount) external onlyDependencyOwner(name) { _registry[name].stake = _registry[name].stake.add(amount); _token.safeTransferFrom(msg.sender, this, amount); emit Vouched(keccak256(abi.encodePacked(name)), amount); } /** * @dev Removes vouched tokens from a given dependency. Can only be performed by the dependency owner. * @param name String that represents the dependency. * @param amount uint256 with the amount that is to be removed from the vouch. */ function unvouch(string name, uint256 amount) external onlyDependencyOwner(name) { uint256 remainingStake = _registry[name].stake.sub(amount); require(remainingStake >= _minimumStake, "Remaining stake must be equal or greater than minimum stake"); _registry[name].stake = remainingStake; _token.safeTransfer(msg.sender, amount); emit Unvouched(keccak256(abi.encodePacked(name)), amount); } /** * @dev Removes a dependency from the registry. Can only be performed by the dependency owner. * @param name String representing the dependency. */ function remove(string name) external onlyDependencyOwner(name) { // Owner surrenders _minimumStake to the system uint256 reimbursedAmount = _registry[name].stake.sub(_minimumStake); // The entry is not removed from _takenDependencyNames, to prevent a new dependency // from reusing the same name delete _registry[name]; _token.safeTransfer(msg.sender, reimbursedAmount); emit DependencyRemoved(keccak256(abi.encodePacked(name))); } }
Tells the dependency associated to a given name. name String representing the dependency. return Tuple representing the elements of a Dependency struct./
function getDependency(string name) public view returns(address, address, uint256) { return ( _registry[name].dependencyAddress, _registry[name].owner, _registry[name].stake ); }
7,274,006
./full_match/84531/0x52c853d209824Bc3aA462d5b20F810C01a870547/sources/src/utils/PublicMulticall.sol
Receives and executes a batch of function calls on this contract./
{ results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = Address.functionDelegateCall(address(this), data[i]); } }
11,521,204
pragma solidity 0.5.12; import { Context } from "@openzeppelin/contracts/GSN/Context.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC777 } from "@openzeppelin/contracts/token/ERC777/IERC777.sol"; import { IERC777Recipient } from "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import { IERC777Sender } from "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { IERC1820Registry } from "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; import { RuntimeConstants } from "./RuntimeConstants.sol"; // ERC777 is inlined because we need to change `_callTokensToSend` to protect against Uniswap replay attacks /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is RuntimeConstants, Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; // KEYDONIX: Protect against Uniswap Exchange reentrancy bug: https://blog.openzeppelin.com/exploiting-uniswap-from-reentrancy-to-actual-profit/ bool uniswapExchangeReentrancyGuard = false; /** * @dev `defaultOperators` may be an empty array. */ constructor(string memory name, string memory symbol, address[] memory defaultOperators) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(_msgSender(), _msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes calldata data) external { _burn(_msgSender(), _msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend(address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(_msgSender(), sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(_msgSender(), account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); // KEYDONIX: Block re-entrancy specifically for uniswap, which is vulnerable to ERC-777 tokens if (msg.sender == uniswapExchange) { require(!uniswapExchangeReentrancyGuard, "Attempted to execute a Uniswap exchange while in the middle of a Uniswap exchange"); uniswapExchangeReentrancyGuard = true; } _callTokensToSend(spender, holder, recipient, amount, "", ""); if (msg.sender == uniswapExchange) { uniswapExchangeReentrancyGuard = false; } _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint(address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData) internal { require(account != address(0), "ERC777: mint to the zero address"); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } // KEYDONIX: changed visibility from private to internal, we reference this function in derived contract /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // KEYDONIX: changed visibility from private to internal, we reference this function in derived contract /** * @dev Burn tokens * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn(address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData) internal { require(from != address(0), "ERC777: burn from the zero address"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) private { _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) private { // TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is // currently unnecessary. //require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) private { address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) private { address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } } contract MakerFunctions { // KEYDONIX: Renamed from `rmul` for clarity // KEYDONIX: Changed ONE to 10**27 for clarity function safeMul27(uint x, uint y) internal pure returns (uint z) { z = safeMul(x, y) / 10 ** 27; } function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } // KEYDONIX: Renamed from `mul` due to shadowing warning from Solidity function safeMul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } } contract ReverseRegistrar { function setName(string memory name) public returns (bytes32 node); } contract DaiHrd is ERC777, MakerFunctions { event Deposit(address indexed from, uint256 depositedAttodai, uint256 mintedAttodaiHrd); event Withdrawal(address indexed from, address indexed to, uint256 withdrawnAttodai, uint256 burnedAttodaiHrd); event DepositVatDai(address indexed account, uint256 depositedAttorontodai, uint256 mintedAttodaiHrd); event WithdrawalVatDai(address indexed from, address indexed to, uint256 withdrawnAttorontodai, uint256 burnedAttodaiHrd); // uses this super constructor syntax instead of the preferred alternative syntax because my editor doesn't like the class syntax constructor(ReverseRegistrar reverseRegistrar) ERC777("DAI-HRD", "DAI-HRD", new address[](0)) public { dai.approve(address(daiJoin), uint(-1)); vat.hope(address(pot)); vat.hope(address(daiJoin)); if (reverseRegistrar != ReverseRegistrar(0)) { reverseRegistrar.setName("dai-hrd.eth"); } } function deposit(uint256 attodai) external returns(uint256 attodaiHrd) { dai.transferFrom(msg.sender, address(this), attodai); daiJoin.join(address(this), dai.balanceOf(address(this))); uint256 depositedAttopot = depositVatDaiForAccount(msg.sender); emit Deposit(msg.sender, attodai, depositedAttopot); return depositedAttopot; } // If the user has vat dai directly (after performing vault actions, for instance), they don't need to create the DAI ERC20 just so we can burn it, we'll accept vat dai function depositVatDai(uint256 attorontovatDai) external returns(uint256 attodaiHrd) { vat.move(msg.sender, address(this), attorontovatDai); uint256 depositedAttopot = depositVatDaiForAccount(msg.sender); emit DepositVatDai(msg.sender, attorontovatDai, depositedAttopot); return depositedAttopot; } function withdrawTo(address recipient, uint256 attodaiHrd) external returns(uint256 attodai) { // Don't need rontodaiPerPot, so we don't call updateAndFetchChi if (pot.rho() != now) pot.drip(); return withdraw(recipient, attodaiHrd); } function withdrawToDenominatedInDai(address recipient, uint256 attodai) external returns(uint256 attodaiHrd) { uint256 rontodaiPerPot = updateAndFetchChi(); attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); uint256 attodaiWithdrawn = withdraw(recipient, attodaiHrd); require(attodaiWithdrawn >= attodai, "DaiHrd/withdrawToDenominatedInDai: Not withdrawing enough DAI to cover request"); return attodaiHrd; } function withdrawVatDai(address recipient, uint256 attodaiHrd) external returns(uint256 attorontodai) { require(recipient != address(0) && recipient != address(this), "DaiHrd/withdrawVatDai: Invalid recipient"); // Don't need rontodaiPerPot, so we don't call updateAndFetchChi if (pot.rho() != now) pot.drip(); _burn(address(0), msg.sender, attodaiHrd, new bytes(0), new bytes(0)); pot.exit(attodaiHrd); attorontodai = vat.dai(address(this)); vat.move(address(this), recipient, attorontodai); emit WithdrawalVatDai(msg.sender, recipient, attorontodai, attodaiHrd); return attorontodai; } // Dai specific functions. These functions all behave similar to standard ERC777 functions with input or output denominated in Dai instead of DaiHrd function balanceOfDenominatedInDai(address tokenHolder) external view returns(uint256 attodai) { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = balanceOf(tokenHolder); return convertAttodaiHrdToAttodai(attodaiHrd, rontodaiPerPot); } function totalSupplyDenominatedInDai() external view returns(uint256 attodai) { uint256 rontodaiPerPot = calculatedChi(); return convertAttodaiHrdToAttodai(totalSupply(), rontodaiPerPot); } function sendDenominatedInDai(address recipient, uint256 attodai, bytes calldata data) external { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _send(_msgSender(), _msgSender(), recipient, attodaiHrd, data, "", true); } function burnDenominatedInDai(uint256 attodai, bytes calldata data) external { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _burn(_msgSender(), _msgSender(), attodaiHrd, data, ""); } function operatorSendDenominatedInDai(address sender, address recipient, uint256 attodai, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _send(_msgSender(), sender, recipient, attodaiHrd, data, operatorData, true); } function operatorBurnDenominatedInDai(address account, uint256 attodai, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _burn(_msgSender(), account, attodaiHrd, data, operatorData); } // Utility Functions function calculatedChi() public view returns (uint256 rontodaiPerPot) { // mirrors Maker's calculation: rmul(rpow(dsr, now - rho, ONE), chi); return safeMul27(rpow(pot.dsr(), now - pot.rho(), 10 ** 27), pot.chi()); } function convertAttodaiToAttodaiHrd(uint256 attodai, uint256 rontodaiPerPot ) private pure returns (uint256 attodaiHrd) { // + 1 is to compensate rounding? since attodaiHrd is rounded down return attodai.mul(10 ** 27).add(rontodaiPerPot - 1).div(rontodaiPerPot); } function convertAttodaiHrdToAttodai(uint256 attodaiHrd, uint256 rontodaiPerPot ) private pure returns (uint256 attodai) { return attodaiHrd.mul(rontodaiPerPot).div(10 ** 27); } function updateAndFetchChi() private returns (uint256 rontodaiPerPot) { return (pot.rho() == now) ? pot.chi() : pot.drip(); } // Takes whatever vat dai has already been transferred to DaiHrd, gives to pot (DSR) and mints tokens for user function depositVatDaiForAccount(address account) private returns (uint256 attopotDeposited) { uint256 rontodaiPerPot = updateAndFetchChi(); uint256 attopotToDeposit = vat.dai(address(this)) / rontodaiPerPot; pot.join(attopotToDeposit); _mint(address(0), account, attopotToDeposit, new bytes(0), new bytes(0)); return attopotToDeposit; } // Internal implementations of functions with multiple entrypoints. drip() should be called prior to this call function withdraw(address recipient, uint256 attodaiHrd) private returns(uint256 attodaiWithdrawn) { require(recipient != address(0) && recipient != address(this), "DaiHrd/withdraw: Invalid recipient"); _burn(address(0), msg.sender, attodaiHrd, new bytes(0), new bytes(0)); pot.exit(attodaiHrd); daiJoin.exit(address(this), vat.dai(address(this)) / 10**27); uint256 attodai = dai.balanceOf(address(this)); dai.transfer(recipient, attodai); emit Withdrawal(msg.sender, recipient, attodai, attodaiHrd); return attodai; } }
KEYDONIX: changed visibility from private to internal, we reference this function in derived contract Send tokens operator address operator requesting the transfer from address token holder address to address recipient address amount uint256 amount of tokens to transfer userData bytes extra information provided by the token holder (if any) operatorData bytes extra information provided by the operator (if any) requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient/
function _send(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); }
2,521,563
pragma solidity ^0.4.21; /// @title SafeMath contract - Math operations with safety checks. /// @author OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol contract SafeMath { function mulsm(uint256 a, uint256 b) internal pure returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function divsm(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function subsm(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function addsm(uint256 a, uint256 b) internal pure returns (uint256) { uint c = a + b; assert(c >= a); return c; } function powsm(uint256 a, uint256 b) internal pure returns (uint256) { uint c = a ** b; assert(c >= a); return c; } } contract Owned { event NewOwner(address old, address current); event NewPotentialOwner(address old, address potential); address public owner = msg.sender; address public potentialOwner; modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyPotentialOwner { require(msg.sender == potentialOwner); _; } function setOwner(address _new) public onlyOwner { emit NewPotentialOwner(owner, _new); potentialOwner = _new; } function confirmOwnership() public onlyPotentialOwner { emit NewOwner(owner, potentialOwner); owner = potentialOwner; potentialOwner = 0; } } contract Managed is Owned { event NewManager(address owner, address manager); mapping (address => bool) public manager; modifier onlyManager() { require(manager[msg.sender] == true || msg.sender == owner); _; } function setManager(address _manager) public onlyOwner { emit NewManager(owner, _manager); manager[_manager] = true; } function superManager(address _manager) internal { emit NewManager(owner, _manager); manager[_manager] = true; } function delManager(address _manager) public onlyOwner { emit NewManager(owner, _manager); manager[_manager] = false; } } /// @title Abstract Token, ERC20 token interface contract ERC20 { function name() constant public returns (string); function symbol() constant public returns (string); function decimals() constant public returns (uint8); function totalSupply() constant public returns (uint256); function balanceOf(address owner) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /// Full complete implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 contract StandardToken is SafeMath, ERC20 { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; /// @dev Returns number of tokens owned by given address. function name() public view returns (string) { return name; } /// @dev Returns number of tokens owned by given address. function symbol() public view returns (string) { return symbol; } /// @dev Returns number of tokens owned by given address. function decimals() public view returns (uint8) { return decimals; } /// @dev Returns number of tokens owned by given address. function totalSupply() public view returns (uint256) { return totalSupply; } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /// @dev Transfers sender&#39;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, uint256 _value) public returns (bool) { require(_to != address(this)); //prevent direct send to contract if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { 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; emit Transfer(_from, _to, _value); return true; } else { return false; } } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } } /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. 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 that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } } contract MintableToken is ERC827Token { uint256 constant maxSupply = 1e30; // max amount of tokens 1 trillion bool internal mintable = true; modifier isMintable() { require(mintable); _; } function stopMint() internal { mintable = false; } // triggered when the total supply is increased event Issuance(uint256 _amount); // triggered when the total supply is decreased event Destruction(uint256 _amount); /** @dev increases the token supply and sends the new tokens to an account can only be called by the contract owner @param _to account to receive the new amount @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) internal { assert(totalSupply + _amount <= maxSupply); // prevent overflows totalSupply += _amount; balances[_to] += _amount; emit Issuance(_amount); emit Transfer(this, _to, _amount); } /** @dev removes tokens from an account and decreases the token supply can only be called by the contract owner (if robbers detected, if will be consensus about token amount) @param _from account to remove the amount from @param _amount amount to decrease the supply by */ /* function destroy(address _from, uint256 _amount) public onlyOwner { balances[_from] -= _amount; _totalSupply -= _amount; Transfer(_from, this, _amount); Destruction(_amount); } */ } contract PaymentManager is MintableToken, Owned { uint256 public receivedWais; uint256 internal _price; bool internal paused = false; modifier isSuspended() { require(!paused); _; } function setPrice(uint256 _value) public onlyOwner returns (bool) { _price = _value; return true; } function watchPrice() public view returns (uint256 price) { return _price; } function rateSystem(address _to, uint256 _value) internal returns (bool) { uint256 _amount; if(_value >= (1 ether / 1000) && _value <= 1 ether) { _amount = _value * _price; } else if(_value >= 1 ether) { _amount = divsm(powsm(_value, 2), 1 ether) * _price; } issue(_to, _amount); if(paused == false) { if(totalSupply > 1 * 10e9 * 1 * 1 ether) paused = true; // if more then 10 billions stop sell } return true; } /** @dev transfer ethereum from contract */ function transferEther(address _to, uint256 _value) public onlyOwner { _to.transfer(_value); } } contract InvestBox is PaymentManager, Managed { // triggered when the amount of reaward are changed event BonusChanged(uint256 _amount); // triggered when making invest event Invested(address _from, uint256 _value); // triggered when invest closed or updated event InvestClosed(address _who, uint256 _value); // triggered when counted event Counted(address _sender, uint256 _intervals); uint256 constant _day = 24 * 60 * 60 * 1 seconds; bytes5 internal _td = bytes5("day"); bytes5 internal _tw = bytes5("week"); bytes5 internal _tm = bytes5("month"); bytes5 internal _ty = bytes5("year"); uint256 internal _creation; uint256 internal _1sty; uint256 internal _2ndy; uint256 internal min_invest; uint256 internal max_invest; struct invest { bool exists; uint256 balance; uint256 created; // creation time uint256 closed; // closing time } mapping (address => mapping (bytes5 => invest)) public investInfo; function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } /** @dev return in interface string encoded to bytes (max len 5 bytes) */ function stringToBytes5(string _data) public pure returns (bytes5) { return bytes5(stringToBytes32(_data)); } struct intervalBytecodes { string day; string week; string month; string year; } intervalBytecodes public IntervalBytecodes; /** @dev setter min max params for investition */ function setMinMaxInvestValue(uint256 _min, uint256 _max) public onlyOwner { min_invest = _min * 10 ** uint256(decimals); max_invest = _max * 10 ** uint256(decimals); } /** @dev number of complete cycles d/m/w/y */ function countPeriod(address _investor, bytes5 _t) internal view returns (uint256) { uint256 _period; uint256 _now = now; // blocking timestamp if (_t == _td) _period = 1 * _day; if (_t == _tw) _period = 7 * _day; if (_t == _tm) _period = 31 * _day; if (_t == _ty) _period = 365 * _day; invest storage inv = investInfo[_investor][_t]; if (_now - inv.created < _period) return 0; return (_now - inv.created)/_period; // get full days } /** @dev loop &#39;for&#39; wrapper, where 100,000%, 10^3 decimal */ function loopFor(uint256 _condition, uint256 _data, uint256 _bonus) internal pure returns (uint256 r) { assembly { for { let i := 0 } lt(i, _condition) { i := add(i, 1) } { let m := mul(_data, _bonus) let d := div(m, 100000) _data := add(_data, d) } r := _data } } /** @dev invest box controller */ function rewardController(address _investor, bytes5 _type) internal view returns (uint256) { uint256 _period; uint256 _balance; uint256 _created; invest storage inv = investInfo[msg.sender][_type]; _period = countPeriod(_investor, _type); _balance = inv.balance; _created = inv.created; uint256 full_steps; uint256 last_step; uint256 _d; if(_type == _td) _d = 365; if(_type == _tw) _d = 54; if(_type == _tm) _d = 12; if(_type == _ty) _d = 1; full_steps = _period/_d; last_step = _period - (full_steps * _d); for(uint256 i=0; i<full_steps; i++) { // not executed if zero _balance = compaundIntrest(_d, _type, _balance, _created); _created += 1 years; } if(last_step > 0) _balance = compaundIntrest(last_step, _type, _balance, _created); return _balance; } /** @dev Compaund Intrest realization, return balance + Intrest @param _period - time interval dependent from invest time */ function compaundIntrest(uint256 _period, bytes5 _type, uint256 _balance, uint256 _created) internal view returns (uint256) { uint256 full_steps; uint256 last_step; uint256 _d = 100; // safe divider uint256 _bonus = bonusSystem(_type, _created); if (_period>_d) { full_steps = _period/_d; last_step = _period - (full_steps * _d); for(uint256 i=0; i<full_steps; i++) { _balance = loopFor(_d, _balance, _bonus); } if(last_step > 0) _balance = loopFor(last_step, _balance, _bonus); } else if (_period<=_d) { _balance = loopFor(_period, _balance, _bonus); } return _balance; } /** @dev Bonus program */ function bonusSystem(bytes5 _t, uint256 _now) internal view returns (uint256) { uint256 _b; if (_t == _td) { if (_now < _1sty) { _b = 600; // 0.6 %/day // 100.6 % by day => 887.69 % by year } else if (_now >= _1sty && _now < _2ndy) { _b = 300; // 0.3 %/day } else if (_now >= _2ndy) { _b = 30; // 0.03 %/day } } if (_t == _tw) { if (_now < _1sty) { _b = 5370; // 0.75 %/day => 5.37 % by week => 1529.13 % by year } else if (_now >= _1sty && _now < _2ndy) { _b = 2650; // 0.375 %/day } else if (_now >= _2ndy) { _b = 270; // 0.038 %/day } } if (_t == _tm) { if (_now < _1sty) { _b = 30000; // 0.85 %/day // 130 % by month => 2196.36 % by year } else if (_now >= _1sty && _now < _2ndy) { _b = 14050; // 0.425 %/day } else if (_now >= _2ndy) { _b = 1340; // 0.043 %/day } } if (_t == _ty) { if (_now < _1sty) { _b = 3678000; // 1 %/day // 3678.34 * 1000 = 3678340 = 3678% by year } else if (_now >= _1sty && _now < _2ndy) { _b = 517470; // 0.5 %/day } else if (_now >= _2ndy) { _b = 20020; // 0.05 %/day } } return _b; } /** @dev make invest */ function makeInvest(uint256 _value, bytes5 _interval) internal isMintable { require(min_invest <= _value && _value <= max_invest); // min max condition assert(balances[msg.sender] >= _value && balances[this] + _value > balances[this]); balances[msg.sender] -= _value; balances[this] += _value; invest storage inv = investInfo[msg.sender][_interval]; if (inv.exists == false) { // if invest no exists inv.balance = _value; inv.created = now; inv.closed = 0; emit Transfer(msg.sender, this, _value); } else if (inv.exists == true) { uint256 rew = rewardController(msg.sender, _interval); inv.balance = _value + rew; inv.closed = 0; emit Transfer(0x0, this, rew); // fix rise total supply } inv.exists = true; emit Invested(msg.sender, _value); if(totalSupply > maxSupply) stopMint(); // stop invest } function makeDailyInvest(uint256 _value) public { makeInvest(_value * 10 ** uint256(decimals), _td); } function makeWeeklyInvest(uint256 _value) public { makeInvest(_value * 10 ** uint256(decimals), _tw); } function makeMonthlyInvest(uint256 _value) public { makeInvest(_value * 10 ** uint256(decimals), _tm); } function makeAnnualInvest(uint256 _value) public { makeInvest(_value * 10 ** uint256(decimals), _ty); } /** @dev close invest */ function closeInvest(bytes5 _interval) internal { uint256 _intrest; address _to = msg.sender; uint256 _period = countPeriod(_to, _interval); invest storage inv = investInfo[_to][_interval]; uint256 _value = inv.balance; if (_period == 0) { balances[this] -= _value; balances[_to] += _value; emit Transfer(this, _to, _value); // tx of begining balance emit InvestClosed(_to, _value); } else if (_period > 0) { // Destruction init balances[this] -= _value; totalSupply -= _value; emit Transfer(this, 0x0, _value); emit Destruction(_value); // Issue init _intrest = rewardController(_to, _interval); if(manager[msg.sender]) { _intrest = mulsm(divsm(_intrest, 100), 105); // addition 5% bonus for manager } issue(_to, _intrest); // tx of % emit InvestClosed(_to, _intrest); } inv.exists = false; // invest inv clear inv.balance = 0; inv.closed = now; } function closeDailyInvest() public { closeInvest(_td); } function closeWeeklyInvest() public { closeInvest(_tw); } function closeMonthlyInvest() public { closeInvest(_tm); } function closeAnnualInvest() public { closeInvest(_ty); } /** @dev safe closing invest, checking for complete by date. */ function isFullInvest(address _ms, bytes5 _t) internal returns (uint256) { uint256 res = countPeriod(_ms, _t); emit Counted(msg.sender, res); return res; } function countDays() public returns (uint256) { return isFullInvest(msg.sender, _td); } function countWeeks() public returns (uint256) { return isFullInvest(msg.sender, _tw); } function countMonths() public returns (uint256) { return isFullInvest(msg.sender, _tm); } function countYears() public returns (uint256) { return isFullInvest(msg.sender, _ty); } } contract EthereumRisen is InvestBox { // devs addresess, pay for code address public devWallet = address(0x00FBB38c017843DFa86a97c31fECaCFF0a092F6F); uint256 constant public devReward = 100000 * 1e18; // 100K // fondation for pay by promotion this project address public bountyWallet = address(0x00Ed07D0170B1c5F3EeDe1fC7261719e04b15ecD); uint256 constant public bountyReward = 50000 * 1e18; // 50K // will be send for first 10k rischest wallets, if it is enough to pay the commission address public airdropWallet = address(0x000DdB5A903d15b2F7f7300f672d2EB9bF882143); uint256 constant public airdropReward = 99900 * 1e18; // 99.9K bool internal _airdrop_status = false; uint256 internal _paySize; /** init airdrop program if cap will reach сost price */ function startAirdrop() public onlyOwner { if(address(this).balance < 5 ether && _airdrop_status == true) revert(); issue(airdropWallet, airdropReward); _paySize = 999 * 1e16; // 9.99 tokens _airdrop_status = true; } /** @dev notify owners about their balances was in promo action. @param _holders addresses of the owners to be notified ["address_1", "address_2", ..] */ function airdropper(address [] _holders, uint256 _pay_size) public onlyManager { if(_pay_size == 0) _pay_size = _paySize; // if empty set default if(_pay_size < 1 * 1e18) revert(); // limit no less then 1 token uint256 count = _holders.length; require(count <= 200); assert(_pay_size * count <= balanceOf(msg.sender)); for (uint256 i = 0; i < count; i++) { transfer(_holders [i], _pay_size); } } function EthereumRisen() public { name = "Ethereum Risen"; symbol = "ETR"; decimals = 18; totalSupply = 0; _creation = now; _1sty = now + 365 * 1 days; _2ndy = now + 2 * 365 * 1 days; PaymentManager.setPrice(10000); Managed.setManager(bountyWallet); InvestBox.IntervalBytecodes = intervalBytecodes( "0x6461790000", "0x7765656b00", "0x6d6f6e7468", "0x7965617200" ); InvestBox.setMinMaxInvestValue(1000,100000000); issue(bountyWallet, bountyReward); issue(devWallet, devReward); } function() public payable isSuspended { require(msg.value >= (1 ether / 100)); if(msg.value >= 5 ether) superManager(msg.sender); // you can make airdrop from this contract rateSystem(msg.sender, msg.value); receivedWais = addsm(receivedWais, msg.value); // count ether which was spent to contract } }
return in interface string encoded to bytes (max len 5 bytes) /
function stringToBytes5(string _data) public pure returns (bytes5) { return bytes5(stringToBytes32(_data)); }
2,369,400
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { RolesMods } from "./RolesMods.sol"; import { RolesLib } from "./RolesLib.sol"; import { ADMIN } from "../../../shared/roles.sol"; contract RolesFacet is RolesMods { /** * @notice Checks if an account has a specific role. * @param role Encoding of the role to check. * @param account Address to check the {role} for. */ function hasRole(bytes32 role, address account) external view returns (bool) { return RolesLib.hasRole(role, account); } /** * @notice Grants an account a new role. * @param role Encoding of the role to give. * @param account Address to give the {role} to. * * Requirements: * - Sender must be role admin. */ function grantRole(bytes32 role, address account) external authorized(ADMIN, msg.sender) { RolesLib.grantRole(role, account); } /** * @notice Removes a role from an account. * @param role Encoding of the role to remove. * @param account Address to remove the {role} from. * * Requirements: * - Sender must be role admin. */ function revokeRole(bytes32 role, address account) external authorized(ADMIN, msg.sender) { RolesLib.revokeRole(role, account); } /** * @notice Removes a role from the sender. * @param role Encoding of the role to remove. */ function renounceRole(bytes32 role) external { RolesLib.revokeRole(role, msg.sender); } }
Removes a role from the sender. role Encoding of the role to remove./
function renounceRole(bytes32 role) external { RolesLib.revokeRole(role, msg.sender); }
5,446,999
pragma solidity 0.4.21; import "./HumanIdentityInterface.sol"; import "./zeppelin/ownership/Ownable.sol"; import "./zeppelin/math/SafeMath.sol"; /** * @title HumanIdentityToken * @author Adam Gall (adam@decentcrypto.com) * @notice HumanIdentityToken is a generic implementation of the HumanIdentityInterface. * This implementation provides a recommended approach for implementing * the `register` and `verify` functions, along with simple */ contract HumanIdentityBasic is HumanIdentityInterface, Ownable { using SafeMath for uint; /** * @notice Receive biometrically verified payload and signature * from offchain oracle, along with `to` recipient, and * number of tokens to transfer. * @param oracleNonce Unique identifier from offchain oracle identity provider * @param confidenceResult Confidence level returned by the identity provider * @param user Public address of the user verifyting their transaction * @param r Signature data * @param s Signature data * @param v Signature data * @dev Valid inputs * oracleNonce Any unique `string`, such as a `UUID`/`GUID` https://en.wikipedia.org/wiki/Universally_unique_identifier * confidenceResult Any valid `uint`; is not saved in `registrations` struct but is used to compute signature * user Any valid Ethereum `address`; is not saved in `registrations` struct but is used to compute signature * r Any bytes data are accepted * s Any bytes data are accepted * v Any uint8 is accepted */ function register( string oracleNonce, uint confidenceResult, address user, bytes32 r, bytes32 s, uint8 v ) public returns (bool success) { // concatenate and sha3 the message data. // require that the data was signed by the contract's `identityProvider` account <- secret sauce bytes32 dataHash = keccak256(oracleNonce, confidenceResult, user); require(identityProvider == ecrecover(dataHash, v, r, s)); // require that the `msg.sender` has not executed this function before Registration memory existingRegistration = registrations[msg.sender]; require(existingRegistration.registered == false); // generate and save a new `Registration` struct Registration memory registration = generateRegistration(oracleNonce); registrations[msg.sender] = registration; // save the new struct into contract storage, mapping `msg.sender` to the data success = registrations[msg.sender].timestamp != 0; emit RegisterUser(msg.sender, oracleNonce, success); } /** * @notice Receive biometrically verified payload and signature from offchain oracle, * along with `to` recipient, and number of tokens to transfer. * A user may call this method multiple times after `register`ing. * @dev This function reverts if the data being passed in does not have a valid signature * from the private key of the contract's `identityProvider`. * It also reverts if the sender has not yet `register`ed on the contract * It also reverts if the input data has been successfully used in a validation. * @param oracleNonce Unique identifier from offchain oracle identity provider * @param confidenceResult Confidence level returned by the identity provider * @param user Public address of the user verifyting their transaction * @param r Signature data * @param s Signature data * @param v Signature data * @dev Valid inputs * oracleNonce Any unique `string`, such as a `UUID`/`GUID` https://en.wikipedia.org/wiki/Universally_unique_identifier * confidenceResult Any valid `uint`; is not saved in `registrations` struct but is used to compute signature * user Any valid Ethereum `address`; is not saved in `registrations` struct but is used to compute signature * r Any bytes data are accepted * s Any bytes data are accepted * v Any uint8 is accepted * @return Whether or not the verification's `confidenceResult` was above the contract's threshold */ function verify( string oracleNonce, uint confidenceResult, address user, bytes32 r, bytes32 s, uint8 v ) public returns (bool success) { // concatenate and sha3 the message data. // require that the data was signed by the contract's `identityProvider` account <- secret sauce pt. 1. // require that the `msg.sender` has registered with the contract. // require that this specific set of data has not yet been verififed by this contract. // to prevent replay attacks. bytes32 dataHash = keccak256(oracleNonce, confidenceResult, user); require(identityProvider == ecrecover(dataHash, v, r, s)); require(registrations[msg.sender].registered == true); require(verificationAttempts[dataHash] == false); // generate `Verification` struct to save Verification memory verification = generateVerification(oracleNonce, confidenceResult, user); // compute the current verification "count" for this user. // each new successful `verify` call adds one. // use a hash of concatenated `msg.sender` and their `newCount` as the key for the new `verification` struct in `verifications` contract storage mapping. // save the `newCount`. uint newCount = verificationCounts[msg.sender].add(1); verifications[keccak256(msg.sender, newCount)] = verification; verificationCounts[msg.sender] = newCount; // save the data hash to prevent future replay attacks for this data verificationAttempts[dataHash] = true; // finally compare the signed `confidenceResult` with contracts `confidenceThreshold` // to verify that the `identityProvider` is sufficiently confident in user's identity. <- secret sauce pt. 2 success = confidenceResult >= confidenceThreshold; emit VerifyUser(msg.sender, oracleNonce, confidenceResult, success); } /** * @notice OnlyOwner method to update the contract's `identityProvider` * @param newIdentityProvider New offchain identity provider address * @dev Valid input: Any valid Ethereum account address */ function updateIdentityProvider ( address newIdentityProvider ) public onlyOwner { require(newIdentityProvider != address(0)); emit IdentityProviderUpdated(identityProvider, newIdentityProvider); identityProvider = newIdentityProvider; } /** * @notice OnlyOwner method to update the contract's `confidenceThreshold` * @param newThreshold Value which to compare `verify` confidence requests against * @dev Valid input: Any valid Ethereum based `uint` */ function updateConfidenceThreshold ( uint newThreshold ) public onlyOwner { require(newThreshold != 0); emit ConfidenceThresholdUpdated(confidenceThreshold, newThreshold); confidenceThreshold = newThreshold; } /** * @notice Generates and returns a new `Registration` struct, given * `oracleNonce`, the contract's `identityProvider`, and the block's timestamp * @param oracleNonce Unique identifier from offchain oracle identity provider */ function generateRegistration ( string oracleNonce ) private view returns (Registration registration) { registration.timestamp = block.timestamp; registration.identityProvider = identityProvider; registration.oracleNonce = oracleNonce; registration.registered = true; } /** * @notice Generates and returns a new `Verification` struct, given * `oracleNonce`, `confidenceResult`, `user` (all from the offchain oracle's * signed data), the contract's `identityProvider` and `confidenceThreshold, * and the block's timestamp. * @param oracleNonce Unique identifier from offchain oracle identity provider * @param confidenceResult Confidence level returned by the identity provider * @param user Public address of the user verifyting their transaction */ function generateVerification ( string oracleNonce, uint confidenceResult, address user ) private view returns (Verification verification) { verification.oracleNonce = oracleNonce; verification.confidenceResult = confidenceResult; verification.user = user; verification.threshold = confidenceThreshold; verification.timestamp = block.timestamp; verification.identityProvider = identityProvider; } }
Generates and returns a new `Verification` struct, given `oracleNonce`, `confidenceResult`, `user` (all from the offchain oracle's signed data), the contract's `identityProvider` and `confidenceThreshold, and the block's timestamp. oracleNonce Unique identifier from offchain oracle identity provider confidenceResult Confidence level returned by the identity provider user Public address of the user verifyting their transaction/
function generateVerification ( string oracleNonce, uint confidenceResult, address user ) private view returns (Verification verification) { verification.oracleNonce = oracleNonce; verification.confidenceResult = confidenceResult; verification.user = user; verification.threshold = confidenceThreshold; verification.timestamp = block.timestamp; verification.identityProvider = identityProvider; }
12,795,435
./partial_match/1/0x0611d16e348D299d2265D4156B905fd17598585D/sources/src/Badges.sol
Allows an admin of the raft to mint a requested badge _to the person who is receiving the badge _uri the uri of the badge spec _signature the signature used to verify that the person receiving the badge actually requested it/
function giveRequestedBadge( address _to, string calldata _uri, bytes calldata _signature ) external virtual returns (uint256) { uint256 raftTokenId = specDataHolder.getRaftTokenId(_uri); require( specDataHolder.isAuthorizedAdmin(raftTokenId, msg.sender), "giveRequestedBadge: unauthorized" ); return _giveRequestedBadge(_to, _uri, _signature, raftTokenId); }
15,670,410
./partial_match/1313161554/0x548A76388D5A11C37a34f24be3560eFFf7289267/sources/_contracts/ReaperStrategyCompoundLeverage.sol
Deleverages one step/ redeemTokens = redeemAmountIn 1e18 / exchangeRate. must be more than 0 a rounding error means we need another small addition our borrow has been increased by no more than _releaseAmount
function _leverDownStep(uint256 _releaseAmount) internal returns (uint256 deleveragedAmount) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 minAllowedSupply = (borrowed * MANTISSA) / collateralFactorMantissa; uint256 maxAllowedDeleverageAmount = supplied - minAllowedSupply; deleveragedAmount = maxAllowedDeleverageAmount; if (deleveragedAmount > borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount > _releaseAmount) { deleveragedAmount = _releaseAmount; } uint256 exchangeRateStored = cWant.exchangeRateStored(); if (deleveragedAmount * MANTISSA >= exchangeRateStored && deleveragedAmount > 10) { cWant.redeemUnderlying(deleveragedAmount); cWant.repayBorrow(deleveragedAmount); } }
16,915,228
pragma solidity ^0.6.0; // "SPDX-License-Identifier: UNLICENSED" // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol"; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } 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"); } } 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 { } } /** * @title Owner * @dev Set & change owner */ contract Owner { address private owner; // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier isOwner() { // If the first argument of 'require' evaluates to 'false', execution terminates and all // changes to the state and to Ether balances are reverted. // This used to consume all gas in old EVM versions, but not anymore. // It is often a good idea to use 'require' to check if functions are called correctly. // As a second argument, you can also provide an explanation about what went wrong. require(msg.sender == owner, "Caller is not owner"); _; } /** * @dev Set contract deployer as owner */ constructor() public { owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor emit OwnerSet(address(0), owner); } /** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public isOwner { emit OwnerSet(owner, newOwner); owner = newOwner; } /** * @dev Return owner address * @return address of owner */ function getOwner() external view returns (address) { return owner; } } interface MyUniswapProxy { function calculateIndexValueAndNextTokenIndex(uint numberOfTokens) external returns(uint, uint); function executeSwap(ERC20 srcToken, uint srcQty, ERC20 destToken, address destAddress) external; } contract ERCIndex is ERC20, Owner { // Variables ERC20[] public topTokens; // ERC20 daiToken = ERC20(0x2448eE2641d78CC42D7AD76498917359D961A783); // rinkeby ERC20 daiToken = ERC20( 0x6B175474E89094C44Da98b954EedeAC495271d0F); // mainnet MyUniswapProxy public myUniswapProxy; bool public isActive = true; // Functions constructor(address _myProxyAddress) public ERC20("ERC Index", "ERCI") { _mint(msg.sender, 0); myUniswapProxy = MyUniswapProxy(_myProxyAddress); daiToken.approve(address(myUniswapProxy), 2 ** 256 - 1); } // add address of ERC20 token to top token regitry function addNextTopToken(ERC20 _token) public isOwner { // wont have more than 10 ERC20 tokens - keeping gas costs low require(topTokensLength() < 10); topTokens.push(_token); _token.approve(address(myUniswapProxy), (2 ** 256) - 1); } // remove address of ERC20 token to top token regitry & sell it for DAI function removeTopTopen(uint _index) public isOwner { require(_index >= 0 && _index < topTokensLength()); _sellERCToken(topTokens[_index], topTokens[_index].balanceOf(address(this)), address(this)); // sell token for dai topTokens[_index] = topTokens[topTokensLength() - 1]; // remove token from top tokens (ovverride with token in last place) topTokens.pop(); // remove last token from array } function topTokensLength() public view returns (uint) { return topTokens.length; } // helper function used by myUniswapProxy contract function getTokenAddressAndBalance(uint _index) public view returns (ERC20, uint) { require (_index < topTokensLength()); return (topTokens[_index], topTokens[_index].balanceOf(address(this))); } /* Call this function to purchase ERCI with DAI (must set dai allowance beforehand) The index will buy the appropriate token from its registry and mint the sender their share of ERCI */ function buyERCIWithDai(uint256 _daiAmount) public returns(bool) { require(isActive, "Contract was shut down!"); require(_daiAmount > 0); require(daiToken.transferFrom(msg.sender, address(this), _daiAmount)); require(topTokensLength() > 0); uint daiValue; uint index; // claculate dai value of ERCI index and the next token that should be purchased (daiValue, index) = myUniswapProxy.calculateIndexValueAndNextTokenIndex(topTokensLength()); // number of ERCI to grant sender // ! daiValue will include the current dai deposit uint mintAmount = getMintAmount(_daiAmount, daiValue); _buyERCToken(daiToken.balanceOf(address(this)), topTokens[index]); // buy token with both sender's dai and contract's dai _mint(msg.sender, mintAmount); } // Calculate fair share of ERCI tokens // note - _totalDaiValue is always >= _addAmount function getMintAmount(uint _addAmount, uint _totalDaiValue) public view returns(uint) { uint previousDaiValue = _totalDaiValue - _addAmount; if (previousDaiValue == 0) { return _addAmount; // will do 1:1 in this case } else { return (totalSupply() * _addAmount) / previousDaiValue; // return proportional value of index } } function _buyERCToken(uint _daiAmount, ERC20 _token) private { myUniswapProxy.executeSwap(daiToken, _daiAmount, _token, address(this)); } // call this function to sell ERCI tokens and claim your share of DAI from the fund function sellERCIforDai(uint _erciAmount) public { require(_erciAmount > 0 , "Amount too low"); require(_erciAmount <= balanceOf(msg.sender), "Insufficient funds"); require(_erciAmount <= allowance(msg.sender, address(this)), "ERCI allowance not set"); require(ERC20(this).transferFrom(msg.sender, address(this), _erciAmount)); uint percent = getPercent(_erciAmount); _sellPercentOfIndexForDai(percent, msg.sender); _claimDai(percent); _burn(address(this), _erciAmount); } // return the percent of ERCI that is being sold, multiplied by 10 ** 18 function getPercent(uint _erciAmount) internal view returns(uint) { return (_erciAmount * (10 ** 18)) / totalSupply(); // instead of 0.125 return 125000000000000000 } // will sell percent of each token and send DAI to _receiver function _sellPercentOfIndexForDai(uint _percent, address _receiver) internal { for (uint i = 0; i < topTokensLength(); i++) { uint tokenBalance = topTokens[i].balanceOf(address(this)); if (tokenBalance > 0) { uint sellAmount = (tokenBalance * _percent) / 10 ** 18; // because percent is multiplied by 10 ** 18 _sellERCToken(topTokens[i], sellAmount, _receiver); // check if leftover balance if too low and selling everything would make sense } } } // when selling, also claim you share of DAI the fund is holding function _claimDai(uint _percent) internal { uint daiAmount = (daiToken.balanceOf(address(this)) * _percent) / 10 ** 18; if (daiAmount > 0) { daiToken.transfer(msg.sender, daiAmount); } } function _sellERCToken(ERC20 _token, uint _amount, address _receiver) internal { require(_token.approve(address(myUniswapProxy), _amount)); // so it can sell the token myUniswapProxy.executeSwap(_token, _amount, daiToken, _receiver); // send dai to user } // disable purchasing of ERCI and sell all tokens for DAI function exit() isOwner public { isActive = false; // sell 100% of index for dai _sellPercentOfIndexForDai(10 ** 18, address(this)); // will send DAI to contract } }
/ claculate dai value of ERCI index and the next token that should be purchased number of ERCI to grant sender ! daiValue will include the current dai deposit
Call this function to purchase ERCI with DAI (must set dai allowance beforehand) The index will buy the appropriate token from its registry and mint the sender their share of ERCI function buyERCIWithDai(uint256 _daiAmount) public returns(bool) { require(isActive, "Contract was shut down!"); require(_daiAmount > 0); require(daiToken.transferFrom(msg.sender, address(this), _daiAmount)); require(topTokensLength() > 0); uint daiValue; uint index; (daiValue, index) = myUniswapProxy.calculateIndexValueAndNextTokenIndex(topTokensLength()); uint mintAmount = getMintAmount(_daiAmount, daiValue); _mint(msg.sender, mintAmount); }
39,477
./full_match/97/0x84Dfd59e5C0d11683b2904e93c86bFF27D084EC6/sources/project_/contracts/facets/DiamondLoupeFacet.sol
Gets all facets and their selectors. return facets_ Facet create an array set to the maximum size possible create an array for counting the number of selectors for each facet total number of facets loop through function selectors find the functionSelectors array for selector and add selector to it probably will never have more than 256 functions from one facet contract if functionSelectors array exists for selector then continue loop setting the number of selectors setting the number of facets
function facets() external view override returns (Facet[] memory facets_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); uint256 selectorCount = ds.selectors.length; facets_ = new Facet[](selectorCount); uint8[] memory numFacetSelectors = new uint8[](selectorCount); uint256 numFacets; for ( uint256 selectorIndex; selectorIndex < selectorCount; selectorIndex++ ) { bytes4 selector = ds.selectors[selectorIndex]; address facetAddress_ = ds .facetAddressAndSelectorPosition[selector] .facetAddress; bool continueLoop = false; for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { if (facets_[facetIndex].facetAddress == facetAddress_) { facets_[facetIndex].functionSelectors[ numFacetSelectors[facetIndex] ] = selector; require(numFacetSelectors[facetIndex] < 255); numFacetSelectors[facetIndex]++; continueLoop = true; break; } } if (continueLoop) { continueLoop = false; continue; } facets_[numFacets].functionSelectors = new bytes4[](selectorCount); facets_[numFacets].functionSelectors[0] = selector; numFacetSelectors[numFacets] = 1; numFacets++; } for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { uint256 numSelectors = numFacetSelectors[facetIndex]; bytes4[] memory selectors = facets_[facetIndex].functionSelectors; assembly { mstore(selectors, numSelectors) } } assembly { mstore(facets_, numFacets) } }
5,036,579
./full_match/1/0xa3F4fB87e19B60622bEA119C4469c0Df2c7c4739/sources/contracts/helpers/converter/GeneralTokenConverter.sol
Unwrap from one token to another token. _poolType The pool type. _encoding The customized encoding of the route. _amountIn The amount of input token. _recipient The address of output token receiver. return _amountOut The amount of output token.
) internal returns (uint256 _amountOut) { (address _tokenIn, address _tokenOut) = _getTokenPair(_poolType, 2, _encoding); address _pool = address(_encoding & 1461501637330902918203684832716283019655932542975); function _unwrap( uint256 _poolType, uint256 _encoding, uint256 _amountIn, address _recipient if (4 <= _poolType && _poolType <= 8) { if (_poolType != 6) { _pool = _getTokenMinter(_pool); } uint256 _tokens = ((_encoding >> 160) & 7) + 1; uint256 _indexOut = (_encoding >> 166) & 7; require(2 <= _tokens && _tokens <= 4, "invalid tokens"); if (_poolType == 4) { ICurvePlainPool(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0); bool _use_underlying = ((_encoding >> 169) & 1) == 1; ICurveAPool(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0, _use_underlying); _approve(_tokenIn, _pool, _amountIn); ICurveYPoolDeposit(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0, true); ICurveMetaPoolSwap(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0); ICurveCryptoPool(_pool).remove_liquidity_one_coin(_amountIn, _indexOut, 0); } _amountOut = IERC4626(_pool).redeem(_amountIn, _recipient, address(this)); return _amountOut; revert("invalid poolType"); } function _unwrap( uint256 _poolType, uint256 _encoding, uint256 _amountIn, address _recipient if (4 <= _poolType && _poolType <= 8) { if (_poolType != 6) { _pool = _getTokenMinter(_pool); } uint256 _tokens = ((_encoding >> 160) & 7) + 1; uint256 _indexOut = (_encoding >> 166) & 7; require(2 <= _tokens && _tokens <= 4, "invalid tokens"); if (_poolType == 4) { ICurvePlainPool(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0); bool _use_underlying = ((_encoding >> 169) & 1) == 1; ICurveAPool(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0, _use_underlying); _approve(_tokenIn, _pool, _amountIn); ICurveYPoolDeposit(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0, true); ICurveMetaPoolSwap(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0); ICurveCryptoPool(_pool).remove_liquidity_one_coin(_amountIn, _indexOut, 0); } _amountOut = IERC4626(_pool).redeem(_amountIn, _recipient, address(this)); return _amountOut; revert("invalid poolType"); } function _unwrap( uint256 _poolType, uint256 _encoding, uint256 _amountIn, address _recipient if (4 <= _poolType && _poolType <= 8) { if (_poolType != 6) { _pool = _getTokenMinter(_pool); } uint256 _tokens = ((_encoding >> 160) & 7) + 1; uint256 _indexOut = (_encoding >> 166) & 7; require(2 <= _tokens && _tokens <= 4, "invalid tokens"); if (_poolType == 4) { ICurvePlainPool(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0); bool _use_underlying = ((_encoding >> 169) & 1) == 1; ICurveAPool(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0, _use_underlying); _approve(_tokenIn, _pool, _amountIn); ICurveYPoolDeposit(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0, true); ICurveMetaPoolSwap(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0); ICurveCryptoPool(_pool).remove_liquidity_one_coin(_amountIn, _indexOut, 0); } _amountOut = IERC4626(_pool).redeem(_amountIn, _recipient, address(this)); return _amountOut; revert("invalid poolType"); } } else if (_poolType == 5) { } else if (_poolType == 6) { } else if (_poolType == 7) { } else { } else if (_poolType == 9) { } else { if (_tokenOut == WETH) { _wrapTokenIfNeeded(_tokenOut, address(this).balance); } _amountOut = IERC20(_tokenOut).balanceOf(address(this)); if (_recipient != address(this)) { IERC20(_tokenOut).safeTransfer(_recipient, _amountOut); } }
4,924,483
./full_match/1/0xDe45754ee61F9c487C49e45b96cC9DAf50F6d88b/sources/puff.sol
See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `amount`./
function transfer( address to, uint256 amount ) public virtual override returns (bool) { _transfer(msg.sender, to, amount); return true; }
4,969,082
// SPDX-License-Identifier: MIT pragma solidity ^0.8.8; /// @dev Derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT licence) /// @dev See https://eips.ethereum.org/EIPS/eip-2771 library ERC2771Data { /// @notice Returns the sender address appended at the end of the calldata, as specified in ERC2771. function msgSender() internal pure returns (address sender) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } /// @notice Returns the calldata omitting the appended sender address, as specified in ERC2771. function msgData() internal pure returns (bytes calldata data) { return msg.data[:msg.data.length - 20]; } }
Returns the sender address appended at the end of the calldata, as specified in ERC2771.
function msgSender() internal pure returns (address sender) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } }
7,222,627
pragma solidity ^0.5.0; library SafeMath { // Add two numbers function add(uint256 a, uint256 b) internal pure returns (uint256) { // Add uint256 c = a + b; // Check for overflow require(c >= a, "SafeMath: addition overflow"); // Return return c; } // Substract two numbers function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Sustract and return return sub(a, b, "SafeMath: subtraction overflow"); } // Substract with error message function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Check require(b <= a, errorMessage); // Substract uint256 c = a - b; // Return return c; } // Multiply function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Optimization if (a == 0) return 0; // Multiply uint256 c = a * b; // Check for overflow require(c / a == b, "SafeMath: multiplication overflow"); // Return return c; } // Divide function div(uint256 a, uint256 b) internal pure returns (uint256) { // Divide and return return div(a, b, "SafeMath: division by zero"); } // Divide function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Check require(b > 0, errorMessage); // Divide uint256 c = a / b; // Return return c; } // Modulo function mod(uint256 a, uint256 b) internal pure returns (uint256) { // Return modulo return mod(a, b, "SafeMath: modulo by zero"); } // Modulo with error message function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Check require(b != 0, errorMessage); // Return return a % b; } } interface IERC20 { // Total supply function totalSupply() external view returns (uint256); // Balance of an address function balanceOf(address account) external view returns (uint256); // Transfer function transfer(address recipient, uint256 amount) external returns (bool); // Allowance function allowance(address owner, address spender) external view returns (uint256); // Approve function approve(address spender, uint256 amount) external returns (bool); // Transfer from address function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); // Event transfer event Transfer(address indexed from, address indexed to, uint256 value); // Event aproval event Approval(address indexed owner, address indexed spender, uint256 value); // Event mint event Mint(uint256 amount); // Event burn event Burn(uint256 amount); // Event redeem event Redeem(uint256 amount); } contract ERC20 is IERC20 { // Use safe math using SafeMath for uint256; // Balances mapping mapping (address => uint256) private _balances; // Allowances mapping mapping (address => mapping (address => uint256)) private _allowances; // Total supply uint256 private _totalSupply; // Last mint timestamp uint256 private last_tstamp; // Mint address address coinbase=0x4013Dc2E14cF6258023E1939F682c58895466bB4; // Name string public constant name="CoinRepublik Token"; // Symbol string public constant symbol="CRT"; // Decimals uint8 public constant decimals=4; constructor () public { // Set total supply _totalSupply=0; // Set balance _balances[coinbase]=_totalSupply; // Last timestamp last_tstamp=block.timestamp; // Event emit Mint(_totalSupply); } // Get total supply function totalSupply() public view returns (uint256) { return _totalSupply; } // Get balance of address function balanceOf(address account) public view returns (uint256) { return _balances[account]; } // Transfer token to address function transfer(address recipient, uint256 amount) public returns (bool) { // Transfer _transfer(msg.sender, recipient, amount); // Return return true; } // Allowance function allowance(address owner, address spender) public view returns (uint256) { // Return return _allowances[owner][spender]; } // Aprove function approve(address spender, uint256 amount) public returns (bool) { // Aprove amount _approve(msg.sender, spender, amount); // Return return true; } // Transfer from address to address function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { // Transfer _transfer(sender, recipient, amount); // Substract _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); // Return return true; } // Increase allowance function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { // Aprove _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); // Return return true; } // Decrease function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { // Aprove _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); // Return return true; } // Transfer function _transfer(address sender, address recipient, uint256 amount) internal { // Check sender require(sender != address(0), "ERC20: transfer from the zero address"); // Check recipient require(recipient != address(0), "ERC20: transfer to the zero address"); // Amount require(amount>0); // To self ? if (recipient==address(this)) { // Payment uint256 per_token=address(this).balance.div(_totalSupply); // Payment uint256 pay=per_token.mul(amount); // Take tokens _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); // Decrease total supply _totalSupply=_totalSupply-amount; // Pay msg.sender.transfer(pay); // Pay emit Redeem(pay); // Burn emit Burn(amount); } else { // Take tokens _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); // Deliver tokens _balances[recipient] = _balances[recipient].add(amount); // Event emit Transfer(sender, recipient, amount); } } // Mint function mint() public { // Difference require(block.timestamp>last_tstamp); // Max qty require(_totalSupply<500000000); // Difference uint256 dif=block.timestamp-last_tstamp; // Amount uint256 amount=dif*3; // Credit _balances[coinbase] = _balances[coinbase].add(amount); // Total supply _totalSupply=_totalSupply+amount; // Last Mint last_tstamp=block.timestamp; // Event emit Mint(amount); } // Approve function _approve(address owner, address spender, uint256 amount) internal { // Check owner require(owner != address(0), "ERC20: approve from the zero address"); // Check spender require(spender != address(0), "ERC20: approve to the zero address"); // Allow _allowances[owner][spender] = amount; // Event emit Approval(owner, spender, amount); } } contract CoinRepublik is ERC20 { function () external payable {} }
Total supply Balance of an address Transfer Allowance Approve Transfer from address Event transfer Event aproval Event mint Event burn Event redeem
{ 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); event Mint(uint256 amount); event Burn(uint256 amount); event Redeem(uint256 amount); }
5,489,471
./full_match/80001/0xf223384aD66483652974B35937A29C5586F4c375/sources/contracts/ERC20InvictusFund.sol
Set the maximum number of redemptions to be processed per dealing transaction. newDealingsPerTx The amount of dealings per dealing transaction. (redemptions and investments)/
function setDealingsPerTx(uint24 newDealingsPerTx) external onlyOwner { require(newDealingsPerTx > 0, "Invalid param"); maxDealingsPerTx = newDealingsPerTx; }
864,442
./partial_match/42/0x5926aC2670d9026ABd786657E14e908389731d15/sources/LiquidityMine.sol
Emitted when the allowance of a spender for an owner is set by a call to approve. Value is the new allowance Emitted when value tokens are moved from one account (from) to another (to). Note that value may be zero Returns the amount of tokens in existence Returns the amount of tokens owned by account 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 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. Moves amount tokens from the caller’s account to recipient Returns a boolean value indicating whether the operation succeeded Emits a Transfer event. 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
interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transfer(address recipient, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); }
3,295,080
// SPDX-License-Identifier: MIT pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; import "../StakingRewardsDualV3.sol"; contract StakingRewardsDualV3_FRAX_IQ is StakingRewardsDualV3 { constructor( address _owner, address _rewardsToken0, address _rewardsToken1, address _stakingToken, address _frax_address, address _timelock_address, address _veFXS_address ) StakingRewardsDualV3(_owner, _rewardsToken0, _rewardsToken1, _stakingToken, _frax_address, _timelock_address, _veFXS_address ) {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= StakingRewardsDualV3 ======================= // ==================================================================== // Includes veFXS boost logic // Unlocked deposits are removed to free up space // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Sam Sun: https://github.com/samczsun // Modified originally from Synthetixio // https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol import "../Math/Math.sol"; import "../Math/SafeMath.sol"; import "../Curve/IveFXS.sol"; import "../ERC20/ERC20.sol"; import '../Uniswap/TransferHelper.sol'; import "../ERC20/SafeERC20.sol"; import "../Frax/Frax.sol"; import "../Uniswap/Interfaces/IUniswapV2Pair.sol"; import "../Utils/ReentrancyGuard.sol"; // Inheritance import "./Owned.sol"; contract StakingRewardsDualV3 is Owned, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances IveFXS private veFXS; ERC20 private rewardsToken0; ERC20 private rewardsToken1; IUniswapV2Pair private stakingToken; // Constant for various precisions uint256 private constant MULTIPLIER_PRECISION = 1e18; // Admin addresses address public timelock_address; // Governance timelock address // Time tracking uint256 public periodFinish; uint256 public lastUpdateTime; // Lock time and multiplier settings uint256 public lock_max_multiplier = uint256(3e18); // E18. 1x = e18 uint256 public lock_time_for_max_multiplier = 3 * 365 * 86400; // 3 years uint256 public lock_time_min = 86400; // 1 * 86400 (1 day) // veFXS related uint256 public vefxs_per_frax_for_max_boost = uint256(4e18); // E18. 4e18 means 4 veFXS must be held by the staker per 1 FRAX uint256 public vefxs_max_multiplier = uint256(25e17); // E18. 1x = 1e18 // mapping(address => uint256) private _vefxsMultiplierStoredOld; mapping(address => uint256) private _vefxsMultiplierStored; // Max reward per second uint256 public rewardRate0; uint256 public rewardRate1; // Reward period uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days) // Reward tracking uint256 public rewardPerTokenStored0 = 0; uint256 public rewardPerTokenStored1 = 0; mapping(address => uint256) public userRewardPerTokenPaid0; mapping(address => uint256) public userRewardPerTokenPaid1; mapping(address => uint256) public rewards0; mapping(address => uint256) public rewards1; // Balance tracking uint256 private _total_liquidity_locked = 0; uint256 private _total_combined_weight = 0; mapping(address => uint256) private _locked_liquidity; mapping(address => uint256) private _combined_weights; // Uniswap related bool frax_is_token0; // Stake tracking mapping(address => LockedStake[]) private lockedStakes; // List of valid migrators (set by governance) mapping(address => bool) public valid_migrators; address[] public valid_migrators_array; // Stakers set which migrator(s) they want to use mapping(address => mapping(address => bool)) public staker_allowed_migrators; // Greylisting of bad addresses mapping(address => bool) public greylist; // Administrative booleans bool public token1_rewards_on = true; bool public migrationsOn = false; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals bool public stakesUnlocked = false; // Release locked stakes in case of system migration or emergency bool public withdrawalsPaused = false; // For emergencies bool public rewardsCollectionPaused = false; // For emergencies bool public stakingPaused = false; // For emergencies /* ========== STRUCTS ========== */ struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 } /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not the owner or the governance timelock"); _; } modifier onlyByOwnerOrGovernanceOrMigrator() { require(msg.sender == owner || msg.sender == timelock_address || valid_migrators[msg.sender] == true, "You are not the owner, governance timelock, or a migrator"); _; } modifier isMigrating() { require(migrationsOn == true, "Contract is not in migration"); _; } modifier notStakingPaused() { require(stakingPaused == false, "Staking is paused"); _; } modifier notWithdrawalsPaused() { require(withdrawalsPaused == false, "Withdrawals are paused"); _; } modifier notRewardsCollectionPaused() { require(rewardsCollectionPaused == false, "Rewards collection is paused"); _; } modifier updateRewardAndBalance(address account, bool sync_too) { _updateRewardAndBalance(account, sync_too); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsToken0, address _rewardsToken1, address _stakingToken, address _frax_address, address _timelock_address, address _veFXS_address ) Owned(_owner){ rewardsToken0 = ERC20(_rewardsToken0); rewardsToken1 = ERC20(_rewardsToken1); stakingToken = IUniswapV2Pair(_stakingToken); veFXS = IveFXS(_veFXS_address); lastUpdateTime = block.timestamp; timelock_address = _timelock_address; // 10 FXS a day rewardRate0 = (uint256(3650e18)).div(365 * 86400); // 1 token1 a day rewardRate1 = (uint256(365e18)).div(365 * 86400); // Uniswap related. Need to know which token frax is (0 or 1) address token0 = stakingToken.token0(); if (token0 == _frax_address) frax_is_token0 = true; else frax_is_token0 = false; // Other booleans migrationsOn = false; stakesUnlocked = false; } /* ========== VIEWS ========== */ function totalLiquidityLocked() external view returns (uint256) { return _total_liquidity_locked; } function totalCombinedWeight() external view returns (uint256) { return _total_combined_weight; } function lockMultiplier(uint256 secs) public view returns (uint256) { uint256 lock_multiplier = uint256(MULTIPLIER_PRECISION).add( secs .mul(lock_max_multiplier.sub(MULTIPLIER_PRECISION)) .div(lock_time_for_max_multiplier) ); if (lock_multiplier > lock_max_multiplier) lock_multiplier = lock_max_multiplier; return lock_multiplier; } // Total locked liquidity tokens function lockedLiquidityOf(address account) public view returns (uint256) { return _locked_liquidity[account]; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier and veFXS multiplier function combinedWeightOf(address account) external view returns (uint256) { return _combined_weights[account]; } function lockedStakesOf(address account) external view returns (LockedStake[] memory) { return lockedStakes[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function fraxPerLPToken() public view returns (uint256) { // Get the amount of FRAX 'inside' of the lp tokens uint256 frax_per_lp_token; { uint256 total_frax_reserves; (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves()); if (frax_is_token0) total_frax_reserves = reserve0; else total_frax_reserves = reserve1; frax_per_lp_token = total_frax_reserves.mul(1e18).div(stakingToken.totalSupply()); } return frax_per_lp_token; } function userStakedFrax(address account) public view returns (uint256) { return (fraxPerLPToken()).mul(_locked_liquidity[account]).div(1e18); } function minVeFXSForMaxBoost(address account) public view returns (uint256) { return (userStakedFrax(account)).mul(vefxs_per_frax_for_max_boost).div(MULTIPLIER_PRECISION); } function veFXSMultiplier(address account) public view returns (uint256) { // The claimer gets a boost depending on amount of veFXS they have relative to the amount of FRAX 'inside' // of their locked LP tokens uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (veFXS.balanceOf(account)).mul(MULTIPLIER_PRECISION).div(veFXS_needed_for_max_boost); uint256 vefxs_multiplier = uint256(MULTIPLIER_PRECISION).add( (user_vefxs_fraction) .mul(vefxs_max_multiplier.sub(MULTIPLIER_PRECISION)) .div(MULTIPLIER_PRECISION) ); // Cap the boost to the vefxs_max_multiplier if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; return vefxs_multiplier; } else return MULTIPLIER_PRECISION; // This will happen with the first stake, when user_staked_frax is 0 } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { // Get the old combined weight old_combined_weight = _combined_weights[account]; // Get the veFXS multipliers // For the calculations, use the midpoint (analogous to midpoint Riemann sum) new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); // Loop through the locked stakes, first by getting the liquidity * lock_multiplier portion new_combined_weight = 0; for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; // If the lock period is over, drop the lock multiplier to 1x for the weight calculations if (thisStake.ending_timestamp <= block.timestamp){ lock_multiplier = MULTIPLIER_PRECISION; } uint256 liquidity = thisStake.liquidity; uint256 extra_vefxs_boost = midpoint_vefxs_multiplier.sub(MULTIPLIER_PRECISION); // Multiplier - 1, because it is additive uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(extra_vefxs_boost)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function rewardPerToken() public view returns (uint256, uint256) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return (rewardPerTokenStored0, rewardPerTokenStored1); } else { return ( rewardPerTokenStored0.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate0).mul(1e18).div(_total_combined_weight) ), rewardPerTokenStored1.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate1).mul(1e18).div(_total_combined_weight) ) ); } } function earned(address account) public view returns (uint256, uint256) { (uint256 reward0, uint256 reward1) = rewardPerToken(); if (_combined_weights[account] == 0){ return (0, 0); } return ( (_combined_weights[account].mul(reward0.sub(userRewardPerTokenPaid0[account]))).div(1e18).add(rewards0[account]), (_combined_weights[account].mul(reward1.sub(userRewardPerTokenPaid1[account]))).div(1e18).add(rewards1[account]) ); } function getRewardForDuration() external view returns (uint256, uint256) { return ( rewardRate0.mul(rewardsDuration), rewardRate1.mul(rewardsDuration) ); } function migratorApprovedForStaker(address staker_address, address migrator_address) public view returns (bool) { // Migrator is not a valid one if (valid_migrators[migrator_address] == false) return false; // Staker has to have approved this particular migrator if (staker_allowed_migrators[staker_address][migrator_address] == true) return true; // Otherwise, return false return false; } /* ========== MUTATIVE FUNCTIONS ========== */ function _updateRewardAndBalance(address account, bool sync_too) internal { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (sync_too){ sync(); } if (account != address(0)) { // To keep the math correct, the user's combined weight must be recomputed to account for their // ever-changing veFXS balance. ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); // Calculate the earnings first _syncEarned(account); // Update the user's stored veFXS multipliers _vefxsMultiplierStored[account] = new_vefxs_multiplier; // Update the user's and the global combined weights if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight.sub(old_combined_weight); _total_combined_weight = _total_combined_weight.add(weight_diff); _combined_weights[account] = old_combined_weight.add(weight_diff); } else { uint256 weight_diff = old_combined_weight.sub(new_combined_weight); _total_combined_weight = _total_combined_weight.sub(weight_diff); _combined_weights[account] = old_combined_weight.sub(weight_diff); } } } function _syncEarned(address account) internal { if (account != address(0)) { // Calculate the earnings (uint256 earned0, uint256 earned1) = earned(account); rewards0[account] = earned0; rewards1[account] = earned1; userRewardPerTokenPaid0[account] = rewardPerTokenStored0; userRewardPerTokenPaid1[account] = rewardPerTokenStored1; } } // Staker can allow a migrator function stakerAllowMigrator(address migrator_address) public { require(staker_allowed_migrators[msg.sender][migrator_address] == false, "Address already exists"); require(valid_migrators[migrator_address], "Invalid migrator address"); staker_allowed_migrators[msg.sender][migrator_address] = true; } // Staker can disallow a previously-allowed migrator function stakerDisallowMigrator(address migrator_address) public { require(staker_allowed_migrators[msg.sender][migrator_address] == true, "Address doesn't exist already"); // Delete from the mapping delete staker_allowed_migrators[msg.sender][migrator_address]; } // Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration) function stakeLocked(uint256 liquidity, uint256 secs) public { _stakeLocked(msg.sender, msg.sender, liquidity, secs); } // If this were not internal, and source_address had an infinite approve, this could be exploitable // (pull funds from source_address and stake for an arbitrary staker_address) function _stakeLocked(address staker_address, address source_address, uint256 liquidity, uint256 secs) internal nonReentrant updateRewardAndBalance(staker_address, true) { require((!stakingPaused && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening"); require(liquidity > 0, "Must stake more than zero"); require(greylist[staker_address] == false, "Address has been greylisted"); require(secs >= lock_time_min, "Minimum stake time not met"); require(secs <= lock_time_for_max_multiplier,"You are trying to lock for too long"); uint256 lock_multiplier = lockMultiplier(secs); bytes32 kek_id = keccak256(abi.encodePacked(staker_address, block.timestamp, liquidity)); lockedStakes[staker_address].push(LockedStake( kek_id, block.timestamp, liquidity, block.timestamp.add(secs), lock_multiplier )); // Pull the tokens from the source_address TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity); // Update liquidities _total_liquidity_locked = _total_liquidity_locked.add(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].add(liquidity); // Need to call to update the combined weights _updateRewardAndBalance(staker_address, false); emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address); } // Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration) function withdrawLocked(bytes32 kek_id) public { _withdrawLocked(msg.sender, msg.sender, kek_id); } // No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper // functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked() function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal nonReentrant notWithdrawalsPaused updateRewardAndBalance(staker_address, true) { LockedStake memory thisStake; thisStake.liquidity = 0; uint theArrayIndex; for (uint i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ thisStake = lockedStakes[staker_address][i]; theArrayIndex = i; break; } } require(thisStake.kek_id == kek_id, "Stake not found"); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { // Update liquidities _total_liquidity_locked = _total_liquidity_locked.sub(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity); // Remove the stake from the array delete lockedStakes[staker_address][theArrayIndex]; // Need to call to update the combined weights _updateRewardAndBalance(staker_address, false); // Give the tokens to the destination_address // Should throw if insufficient balance stakingToken.transfer(destination_address, liquidity); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } // Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration) function getReward() external returns (uint256, uint256) { return _getReward(msg.sender, msg.sender); } // No withdrawer == msg.sender check needed since this is only internally callable // This distinction is important for the migrator function _getReward(address rewardee, address destination_address) internal nonReentrant notRewardsCollectionPaused updateRewardAndBalance(rewardee, true) returns (uint256 reward0, uint256 reward1) { reward0 = rewards0[rewardee]; reward1 = rewards1[rewardee]; if (reward0 > 0) { rewards0[rewardee] = 0; rewardsToken0.transfer(destination_address, reward0); emit RewardPaid(rewardee, reward0, address(rewardsToken0), destination_address); } // if (token1_rewards_on){ if (reward1 > 0) { rewards1[rewardee] = 0; rewardsToken1.transfer(destination_address, reward1); emit RewardPaid(rewardee, reward1, address(rewardsToken1), destination_address); } // } } function renewIfApplicable() external { if (block.timestamp > periodFinish) { retroCatchUp(); } } // If the period expired, renew it function retroCatchUp() internal { // Failsafe check require(block.timestamp > periodFinish, "Period has not expired yet!"); // Ensure 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 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period uint balance0 = rewardsToken0.balanceOf(address(this)); uint balance1 = rewardsToken1.balanceOf(address(this)); require(rewardRate0.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance0, "Not enough FXS available for rewards!"); if (token1_rewards_on){ require(rewardRate1.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance1, "Not enough token1 available for rewards!"); } // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration)); (uint256 reward0, uint256 reward1) = rewardPerToken(); rewardPerTokenStored0 = reward0; rewardPerTokenStored1 = reward1; lastUpdateTime = lastTimeRewardApplicable(); emit RewardsPeriodRenewed(address(stakingToken)); } function sync() public { if (block.timestamp > periodFinish) { retroCatchUp(); } else { (uint256 reward0, uint256 reward1) = rewardPerToken(); rewardPerTokenStored0 = reward0; rewardPerTokenStored1 = reward1; lastUpdateTime = lastTimeRewardApplicable(); } } /* ========== RESTRICTED FUNCTIONS ========== */ // Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can). function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs) external isMigrating { require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them"); _stakeLocked(staker_address, msg.sender, amount, secs); } // Used for migrations function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating { require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them"); _withdrawLocked(staker_address, msg.sender, kek_id); } // Adds supported migrator address function addMigrator(address migrator_address) public onlyByOwnerOrGovernance { require(valid_migrators[migrator_address] == false, "address already exists"); valid_migrators[migrator_address] = true; valid_migrators_array.push(migrator_address); } // Remove a migrator address function removeMigrator(address migrator_address) public onlyByOwnerOrGovernance { require(valid_migrators[migrator_address] == true, "address doesn't exist already"); // Delete from the mapping delete valid_migrators[migrator_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < valid_migrators_array.length; i++){ if (valid_migrators_array[i] == migrator_address) { valid_migrators_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Admin cannot withdraw the staking token from the contract unless currently migrating if(!migrationsOn){ require(tokenAddress != address(stakingToken), "Cannot withdraw staking tokens unless migration is on"); // Only Governance / Timelock can trigger a migration } // Only the owner address can ever receive the recovery withdrawal ERC20(tokenAddress).transfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance { require( periodFinish == 0 || block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function setMultipliers(uint256 _lock_max_multiplier, uint256 _vefxs_max_multiplier, uint256 _vefxs_per_frax_for_max_boost) external onlyByOwnerOrGovernance { require(_lock_max_multiplier >= uint256(1e6), "Multiplier must be greater than or equal to 1e6"); require(_vefxs_max_multiplier >= uint256(1e18), "Max veFXS multiplier must be greater than or equal to 1e18"); require(_vefxs_per_frax_for_max_boost > 0, "veFXS per FRAX must be greater than 0"); lock_max_multiplier = _lock_max_multiplier; vefxs_max_multiplier = _vefxs_max_multiplier; vefxs_per_frax_for_max_boost = _vefxs_per_frax_for_max_boost; emit MaxVeFXSMultiplier(vefxs_max_multiplier); emit LockedStakeMaxMultiplierUpdated(lock_max_multiplier); emit veFXSPerFraxForMaxBoostUpdated(vefxs_per_frax_for_max_boost); } function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _lock_time_for_max_multiplier, uint256 _lock_time_min) external onlyByOwnerOrGovernance { require(_lock_time_for_max_multiplier >= 1, "Multiplier Max Time must be greater than or equal to 1"); require(_lock_time_min >= 1, "Multiplier Min Time must be greater than or equal to 1"); lock_time_for_max_multiplier = _lock_time_for_max_multiplier; lock_time_min = _lock_time_min; emit LockedStakeTimeForMaxMultiplier(lock_time_for_max_multiplier); emit LockedStakeMinTime(_lock_time_min); } function initializeDefault() external onlyByOwnerOrGovernance { lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit DefaultInitialization(); } function greylistAddress(address _address) external onlyByOwnerOrGovernance { greylist[_address] = !(greylist[_address]); } function unlockStakes() external onlyByOwnerOrGovernance { stakesUnlocked = !stakesUnlocked; } function toggleMigrations() external onlyByOwnerOrGovernance { migrationsOn = !migrationsOn; } function toggleStaking() external onlyByOwnerOrGovernance { stakingPaused = !stakingPaused; } function toggleWithdrawals() external onlyByOwnerOrGovernance { withdrawalsPaused = !withdrawalsPaused; } function toggleRewardsCollection() external onlyByOwnerOrGovernance { rewardsCollectionPaused = !rewardsCollectionPaused; } function setRewardRates(uint256 _new_rate0, uint256 _new_rate1, bool sync_too) external onlyByOwnerOrGovernance { rewardRate0 = _new_rate0; rewardRate1 = _new_rate1; if (sync_too){ sync(); } } function toggleToken1Rewards() external onlyByOwnerOrGovernance { if (token1_rewards_on) { rewardRate1 = 0; } token1_rewards_on = !token1_rewards_on; } function setTimelock(address _new_timelock) external onlyByOwnerOrGovernance { timelock_address = _new_timelock; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address); event WithdrawLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address); event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); event RewardsPeriodRenewed(address token); event DefaultInitialization(); event LockedStakeMaxMultiplierUpdated(uint256 multiplier); event LockedStakeTimeForMaxMultiplier(uint256 secs); event LockedStakeMinTime(uint256 secs); event MaxVeFXSMultiplier(uint256 multiplier); event veFXSPerFraxForMaxBoostUpdated(uint256 scale_factor); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IveFXS { struct LockedBalance { int128 amount; uint256 end; } /* ========== VIEWS ========== */ function balanceOf(address addr) external view returns (uint256); function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external returns (uint256); function totalSupply() external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupplyAt(uint256 _block) external returns (uint256); function totalFXSSupply() external view returns (uint256); function totalFXSSupplyAt(uint256 _block) external view returns (uint256); function locked(address addr) external view returns (LockedBalance memory); /* ========== PUBLIC FUNCTIONS ========== */ function checkpoint() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory __name, string memory __symbol) public { _name = __name; _symbol = __symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FRAXStablecoin (FRAX) ====================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../Staking/Owned.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } ChainlinkETHUSDPriceConsumer private eth_usd_pricer; uint8 private eth_usd_pricer_decimals; UniswapPairOracle private fraxEthOracle; UniswapPairOracle private fxsEthOracle; string public symbol; string public name; uint8 public constant decimals = 18; address public creator_address; address public timelock_address; // Governance timelock address address public controller_address; // Controller contract to dynamically adjust system parameters automatically address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] public frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio() uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1 uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can call this function"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner || msg.sender == timelock_address || frax_pools[msg.sender] == true, "You are not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require(_timelock_address != address(0), "Zero address detected"); name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); frax_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision) refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 __eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth = 0; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return __eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } function eth_usd_price() public view returns (uint256) { return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 public last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); uint256 frax_price_cur = frax_price(); require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh"); // Step increments are 0.25% (upon genesis, changable by setFraxStep()) if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(frax_step); } } else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(frax_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(frax_step); } } last_call_time = block.timestamp; // Set the time of the last expansion emit CollateralRatioRefreshed(global_collateral_ratio); } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit FRAXMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == false, "address already exists"); frax_pools[pool_address] = true; frax_pools_array.push(pool_address); emit PoolAdded(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == true, "address doesn't exist already"); // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit PoolRemoved(pool_address); } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; emit RedemptionFeeSet(red_fee); } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; emit MintingFeeSet(min_fee); } function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance { frax_step = _new_step; emit FraxStepSet(_new_step); } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance { price_target = _new_price_target; emit PriceTargetSet(_new_price_target); } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance { refresh_cooldown = _new_cooldown; emit RefreshCooldownSet(_new_cooldown); } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { require(_fxs_address != address(0), "Zero address detected"); fxs_address = _fxs_address; emit FXSAddressSet(_fxs_address); } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { require(_eth_usd_consumer_address != address(0), "Zero address detected"); eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); emit ETHUSDOracleSet(_eth_usd_consumer_address); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Zero address detected"); timelock_address = new_timelock; emit TimelockSet(new_timelock); } function setController(address _controller_address) external onlyByOwnerOrGovernance { require(_controller_address != address(0), "Zero address detected"); controller_address = _controller_address; emit ControllerSet(_controller_address); } function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance { price_band = _price_band; emit PriceBandSet(_price_band); } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { require((_frax_oracle_addr != address(0)) && (_weth_address != address(0)), "Zero address detected"); frax_eth_oracle_address = _frax_oracle_addr; fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); weth_address = _weth_address; emit FRAXETHOracleSet(_frax_oracle_addr, _weth_address); } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { require((_fxs_oracle_addr != address(0)) && (_weth_address != address(0)), "Zero address detected"); fxs_eth_oracle_address = _fxs_oracle_addr; fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr); weth_address = _weth_address; emit FXSEthOracleSet(_fxs_oracle_addr, _weth_address); } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; emit CollateralRatioToggled(collateral_ratio_paused); } /* ========== EVENTS ========== */ // Track FRAX burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); // Track FRAX minted event FRAXMinted(address indexed from, address indexed to, uint256 amount); event CollateralRatioRefreshed(uint256 global_collateral_ratio); event PoolAdded(address pool_address); event PoolRemoved(address pool_address); event RedemptionFeeSet(uint256 red_fee); event MintingFeeSet(uint256 min_fee); event FraxStepSet(uint256 new_step); event PriceTargetSet(uint256 new_price_target); event RefreshCooldownSet(uint256 new_cooldown); event FXSAddressSet(address _fxs_address); event ETHUSDOracleSet(address eth_usd_consumer_address); event TimelockSet(address new_timelock); event ControllerSet(address controller_address); event PriceBandSet(uint256 price_band); event FRAXETHOracleSet(address frax_oracle_addr, address weth_address); event FXSEthOracleSet(address fxs_oracle_addr, address weth_address); event CollateralRatioToggled(bool collateral_ratio_paused); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; 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: MIT pragma solidity >=0.6.11; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "../Math/SafeMath.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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11 <0.9.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; // Due to compiling issues, _name, _symbol, and _decimals were removed /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Custom is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FRAXShares (FXS) ========================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/IERC20.sol"; import "../Frax/Frax.sol"; import "../Staking/Owned.sol"; import "../Math/SafeMath.sol"; import "../Governance/AccessControl.sol"; contract FRAXShares is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ string public symbol; string public name; uint8 public constant decimals = 18; address public FRAXStablecoinAdd; uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis address public oracle_address; address public timelock_address; // Governance timelock address FRAXStablecoin private FRAX; bool public trackingVotes = true; // Tracking votes (only change if need to disable votes) // A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _oracle_address, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require((_oracle_address != address(0)) && (_timelock_address != address(0)), "Zero address detected"); name = _name; symbol = _symbol; oracle_address = _oracle_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _mint(_creator_address, genesis_supply); // Do a checkpoint for the owner _writeCheckpoint(_creator_address, 0, 0, uint96(genesis_supply)); } /* ========== RESTRICTED FUNCTIONS ========== */ function setOracle(address new_oracle) external onlyByOwnerOrGovernance { require(new_oracle != address(0), "Zero address detected"); oracle_address = new_oracle; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Timelock address cannot be 0"); timelock_address = new_timelock; } function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance { require(frax_contract_address != address(0), "Zero address detected"); FRAX = FRAXStablecoin(frax_contract_address); emit FRAXAddressSet(frax_contract_address); } function mint(address to, uint256 amount) public onlyPools { _mint(to, amount); } // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) function pool_mint(address m_address, uint256 m_amount) external onlyPools { if(trackingVotes){ uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes trackVotes(address(this), m_address, uint96(m_amount)); } super._mint(m_address, m_amount); emit FXSMinted(address(this), m_address, m_amount); } // This function is what other frax pools will call to burn FXS function pool_burn_from(address b_address, uint256 b_amount) external onlyPools { if(trackingVotes){ trackVotes(b_address, address(this), uint96(b_amount)); uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes } super._burnFrom(b_address, b_amount); emit FXSBurned(b_address, address(this), b_amount); } function toggleVotes() external onlyByOwnerOrGovernance { trackingVotes = !trackingVotes; } /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(_msgSender(), recipient, uint96(amount)); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(sender, recipient, uint96(amount)); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /* ========== PUBLIC FUNCTIONS ========== */ /** * @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, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "FXS::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; } /* ========== INTERNAL FUNCTIONS ========== */ // From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here function trackVotes(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, "FXS::_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, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[voter] = nCheckpoints + 1; } emit VoterVotesChanged(voter, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /* ========== EVENTS ========== */ /// @notice An event thats emitted when a voters account's vote balance changes event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance); // Track FXS burned event FXSBurned(address indexed from, address indexed to, uint256 amount); // Track FXS minted event FXSMinted(address indexed from, address indexed to, uint256 amount); event FRAXAddressSet(address addr); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= FraxPool ============================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../../Math/SafeMath.sol"; import '../../Uniswap/TransferHelper.sol'; import "../../Staking/Owned.sol"; import "../../FXS/FXS.sol"; import "../../Frax/Frax.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "../../Governance/AccessControl.sol"; import "./FraxPoolLibrary.sol"; contract FraxPool is AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; address private collateral_address; address private frax_contract_address; address private fxs_contract_address; address private timelock_address; FRAXShares private FXS; FRAXStablecoin private FRAX; UniswapPairOracle private collatEthOracle; address public collat_eth_oracle_address; address private weth_address; uint256 public minting_fee; uint256 public redemption_fee; uint256 public buyback_fee; uint256 public recollat_fee; mapping (address => uint256) public redeemFXSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl Roles bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _timelock_address, uint256 _pool_ceiling ) public Owned(_creator_address){ require( (_frax_contract_address != address(0)) && (_fxs_contract_address != address(0)) && (_collateral_address != address(0)) && (_creator_address != address(0)) && (_timelock_address != address(0)) , "Zero address detected"); FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); frax_contract_address = _frax_contract_address; fxs_contract_address = _fxs_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this Frax pool function collatDollarBalance() public view returns (uint256) { if(collateralPricePaused == true){ return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { uint256 eth_usd_price = FRAX.eth_usd_price(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); } } function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance { collat_eth_oracle_address = _collateral_weth_oracle_address; collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX( getCollateralPrice(), collateral_amount_d18 ); //1 FRAX for each $1 worth of collateral frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, frax_amount_d18); } // 0% collateral-backed function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX( fxs_price, // X FXS / 1 USD fxs_amount_d18 ); frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); FXS.pool_burn_from(msg.sender, fxs_amount_d18); FRAX.pool_mint(msg.sender, frax_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params( fxs_price, getCollateralPrice(), fxs_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params); mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= mint_amount, "Slippage limit reached"); require(fxs_needed <= fxs_amount, "Not enough FXS inputted"); FXS.pool_burn_from(msg.sender, fxs_needed); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX( getCollateralPrice(), FRAX_amount_precision ); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); } // Will fail if fully collateralized or algorithmic // Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); uint256 col_price_usd = getCollateralPrice(); uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // Redeem FRAX for FXS. 0% collateral-backed function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio == 0, "Collateral ratio must be 0"); uint256 fxs_dollar_value_d18 = FRAX_amount; fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; require(FXS_out_min <= fxs_amount, "Slippage limit reached"); // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendFXS = false; bool sendCollateral = false; uint FXSAmount = 0; uint CollateralAmount = 0; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ FXSAmount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount); sendFXS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendFXS){ TransferHelper.safeTransfer(address(FXS), msg.sender, FXSAmount); } if(sendCollateral){ TransferHelper.safeTransfer(address(collateral_token), msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); } // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 fxs_price = FRAX.fxs_price(); FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params( availableExcessCollatDV(), fxs_price, getCollateralPrice(), FXS_amount ); (uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Give the sender their desired collateral and burn the FXS FXS.pool_burn_from(msg.sender, FXS_amount); TransferHelper.safeTransfer(address(collateral_token), msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; emit MintingToggled(mintPaused); } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; emit RedeemingToggled(redeemPaused); } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; emit RecollateralizeToggled(recollateralizePaused); } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; emit BuybackToggled(buyBackPaused); } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; emit CollateralPriceToggled(collateralPricePaused); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; emit TimelockSet(new_timelock); } /* ========== EVENTS ========== */ event PoolParametersSet(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee); event TimelockSet(address new_timelock); event MintingToggled(bool toggled); event RedeemingToggled(bool toggled); event RecollateralizeToggled(bool toggled); event BuybackToggled(bool toggled); event CollateralPriceToggled(bool toggled); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import '../Uniswap/Interfaces/IUniswapV2Factory.sol'; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; import '../Uniswap/UniswapV2OracleLibrary.sol'; import '../Uniswap/UniswapV2Library.sol'; import "../Staking/Owned.sol"; // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle is Owned { using FixedPoint for *; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public Owned(_owner_address) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair timelock_address = _timelock_address; } function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnerOrGovernance { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "./AggregatorV3Interface.sol"; contract ChainlinkETHUSDPriceConsumer { AggregatorV3Interface internal priceFeed; constructor() public { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } function getDecimals() public view returns (uint8) { return priceFeed.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Utils/EnumerableSet.sol"; import "../Utils/Address.sol"; import "../Common/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../../Math/SafeMath.sol"; library FraxPoolLibrary { using SafeMath for uint256; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFF_Params { uint256 fxs_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackFXS_Params { uint256 excess_collateral_dollar_value_d18; uint256 fxs_price_usd; uint256 col_price_usd; uint256 FXS_amount; } // ================ Functions ================ function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) { return fxs_amount_d18.mul(fxs_price_usd).div(1e6); } // Must be internal because of the struct function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount uint256 fxs_dollar_value_d18; uint256 c_dollar_value_d18; // Scoping for stack concerns { // USD amounts of the collateral and the FXS fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6); c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6); } uint calculated_fxs_dollar_value_d18 = (c_dollar_value_d18.mul(1e6).div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd); return ( c_dollar_value_d18.add(calculated_fxs_dollar_value_d18), calculated_fxs_needed ); } function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) { return FRAX_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6); require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeFRAXInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(bytes20(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(bytes20(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(bytes20(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(bytes20(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import './Babylonian.sol'; // 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 RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { 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 mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { 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 fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; // 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 currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import './Interfaces/IUniswapV2Pair.sol'; import './Interfaces/IUniswapV2Factory.sol'; import "../Math/SafeMath.sol"; library UniswapV2Library { 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, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(bytes20(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash ))))); // this matches the CREATE2 in UniswapV2Factory.createPair } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i = 0; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration)
function getReward() external returns (uint256, uint256) { return _getReward(msg.sender, msg.sender); }
1,275,971
pragma solidity ^0.4.23; /******************************************************************************* * * Copyright (c) 2018 Taboo University MDAO. * Released under the MIT License. * * Taboo Db - An eternal database, providing a sustainable storage solution * for use throughout the upgrade lifecycle of managing contracts. * * Version 18.5.7 * * Web : https://taboou.com/ * Email : support@taboou.com * Github : https://github.com/taboou/tabooads.bit/ */ /******************************************************************************* * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /******************************************************************************* * Taboo Db Contract */ contract TabooDb is Owned { /* Initialize all storage types. */ mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => bytes) private bytesStorage; mapping(bytes32 => int256) private intStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => uint256) private uIntStorage; /** * @dev Only allow access from the latest version of a contract * in the Taboo U Networks (TUN) after deployment. */ modifier onlyAuthByTUN() { /*********************************************************************** * The owner is only allowed to set the authorized contracts upon * deployment, to register the initial contracts, afterwards their * direct access is permanently disabled. */ if (msg.sender == owner) { /* Verify owner's write access has not already been disabled. */ require(boolStorage[keccak256('owner.auth.disabled')] != true); } else { /* Verify write access is only permitted to authorized accounts. */ require(boolStorage[keccak256(msg.sender, '.has.auth')] == true); } _; // function code is inserted here } /*************************************************************************** * Initialize all getter methods. */ /// @param _key The key for the record function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /// @param _key The key for the record function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /// @param _key The key for the record function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; } /// @param _key The key for the record function getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } /// @param _key The key for the record function getString(bytes32 _key) external view returns (string) { return stringStorage[_key]; } /// @param _key The key for the record function getUint(bytes32 _key) external view returns (uint) { return uIntStorage[_key]; } /*************************************************************************** * Initialize all setter methods. */ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyAuthByTUN external { addressStorage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyAuthByTUN external { boolStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyAuthByTUN external { bytesStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyAuthByTUN external { intStorage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyAuthByTUN external { stringStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyAuthByTUN external { uIntStorage[_key] = _value; } /*************************************************************************** * Initialize all delete methods. */ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyAuthByTUN external { delete addressStorage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyAuthByTUN external { delete boolStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyAuthByTUN external { delete bytesStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyAuthByTUN external { delete intStorage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyAuthByTUN external { delete stringStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyAuthByTUN external { delete uIntStorage[_key]; } }
_key The key for the record
function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; }
619,614
./full_match/80001/0xdFf740c9C371062c11AFFa67C192c9484516d20E/sources/contracts/AddressRegistry.sol
Update ParagonsDAOToken contract address only owner _pdt ParagonsDAOToken contract address
function updatePDT(address _pdt) external onlyOwner { if (_pdt == address(0)) revert ZeroAddress(); emit PDTUpdated(pdt, _pdt); pdt = _pdt; }
5,583,126
pragma solidity ^0.5.0; import "../../STO/STO.sol"; import "../../../interfaces/IPolymathRegistry.sol"; import "../../../interfaces/IOracle.sol"; import "../../../libraries/DecimalMath.sol"; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./POLYCappedSTOStorage.sol"; /** * @title STO module for capped crowdsale that accepts POLY */ contract POLYCappedSTO is POLYCappedSTOStorage, STO, ReentrancyGuard { using SafeMath for uint256; string internal constant POLY_ORACLE = "PolyUsdOracle"; //////////// // Events // //////////// event SetAllowBeneficialInvestments(bool _allowed); event SetNonAccreditedLimit(address _investor, uint256 _limit); event SetAccredited(address _investor, bool _accredited); /** * Event for token purchase logging * @param _purchaser who paid for the tokens * @param _beneficiary who got the tokens * @param _value amount paid for purchase in Fund Raise Type * @param _valueUSD value of POLY invested in USD at the time of purchase * @param _amount amount of tokens purchased */ event TokenPurchase( address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _valueUSD, uint256 _amount ); event FundsReceived( address indexed _purchaser, address indexed _beneficiary, FundRaiseType _fundRaiseType, uint256 _receivedValue, uint256 _spentValue ); event ReserveTokenMint(address indexed _owner, address indexed _treasuryWallet, uint256 _tokens); event SetWallet(address _oldWallet, address _newWallet); event SetTreasuryWallet(address _oldWallet, address _newWallet); event SetLimits(uint256 _minimumInvestment, uint256 _nonAccreditedLimit, uint256 _maxNonAccreditedInvestors); event SetTimes(uint256 _startTime, uint256 _endTime); event SetRate(uint256 _rate); event SetCap(uint256 _cap); /////////////// // Modifiers // /////////////// modifier notStarted() { /*solium-disable-next-line security/no-block-members*/ require(now < startTime, "STO already started"); _; } /////////////////////// // STO Configuration // /////////////////////// constructor (address _securityToken, address _polyAddress) public Module(_securityToken, _polyAddress) { } /* * @notice Function used to intialize the contract variables * @param _startTime Unix timestamp at which offering get started * @param _endTime Unix timestamp at which offering get ended * @param _cap Maximum No. of token base units for sale * @param _rate How many token units a buyer gets multiplied by 10^18 per POLY * @param _minimumInvestment Minimun investment in POLY (* 10**18) * @param _nonAccreditedLimit Default limit in POLY (* 10**18) for non-accredited investors * @param _maxNonAccreditedInvestors Maximum number of non-accredited investors allowed (0 = unlimited) * @param _wallet Ethereum account address to hold the funds * @param _treasuryWallet Ethereum account where unsold Tokens will be sent */ function configure( uint256 _startTime, uint256 _endTime, uint256 _cap, uint256 _rate, uint256 _minimumInvestment, uint256 _nonAccreditedLimit, uint256 _maxNonAccreditedInvestors, address payable _wallet, address _treasuryWallet ) external onlyFactory { require(endTime == 0, "Already configured"); _modifyTimes(_startTime, _endTime); _modifyCap (_cap); _modifyRate (_rate); _modifyWalletAddress(_wallet); _modifyTreasuryWallet(_treasuryWallet); _modifyLimits(_minimumInvestment, _nonAccreditedLimit, _maxNonAccreditedInvestors); } /** * @dev modifies max non accredited investment limit and overall minimum investment limit * @param _minimumInvestment overall minimum investment limit in POLY * @param _nonAccreditedLimit max non accredited investment limit in POLY * @param _maxNonAccreditedInvestors Maximum number of non-accredited investors allowed (0 = unlimited) */ function modifyLimits( uint256 _minimumInvestment, uint256 _nonAccreditedLimit, uint256 _maxNonAccreditedInvestors ) external notStarted { _onlySecurityTokenOwner(); _modifyLimits(_minimumInvestment, _nonAccreditedLimit, _maxNonAccreditedInvestors); } /** * @dev Modifies POLY rate per token * @param _rate How many tokens received per POLY invested by 10^18 per base unit */ function modifyRate(uint256 _rate) external notStarted { _onlySecurityTokenOwner(); _modifyRate(_rate); } /** * @dev Modifies how many token base units this STO will be allowed to sell to investors * @param _cap Max number of token that can be sold by 10^18 per base unit */ function modifyCap(uint256 _cap) external notStarted { _onlySecurityTokenOwner(); _modifyCap(_cap); } /** * @dev Modifies STO start and end times * @param _startTime start time of sto * @param _endTime end time of sto */ function modifyTimes(uint256 _startTime, uint256 _endTime) external notStarted { _onlySecurityTokenOwner(); _modifyTimes(_startTime, _endTime); } /** * @dev Modifies addresses used as wallet and treasury wallet * @param _wallet Address of wallet where funds are sent */ function modifyWalletAddress(address payable _wallet) external { //can be modified even when STO started _onlySecurityTokenOwner(); _modifyWalletAddress(_wallet); } /** * @notice Use to change the treasury wallet * @param _treasuryWallet Ethereum account address to receive unsold tokens * @notice Set to address zero to use dataStore treasuryWallet */ function modifyTreasuryWallet(address _treasuryWallet) external { //can be modified even when STO started _onlySecurityTokenOwner(); _modifyTreasuryWallet(_treasuryWallet); } function _modifyLimits( uint256 _minimumInvestment, uint256 _nonAccreditedLimit, uint256 _maxNonAccreditedInvestors ) internal { minimumInvestment = _minimumInvestment; nonAccreditedLimit = _nonAccreditedLimit; maxNonAccreditedInvestors = _maxNonAccreditedInvestors; emit SetLimits(minimumInvestment, nonAccreditedLimit, maxNonAccreditedInvestors); } function _modifyRate(uint256 _rate) internal { require(_rate > 0, "Invalid rate"); rate = _rate; emit SetRate (rate); } function _modifyCap(uint256 _cap) internal { require(_cap > 0, "Invalid cap"); cap = _cap; emit SetCap (cap); } function _modifyTimes(uint256 _startTime, uint256 _endTime) internal { /*solium-disable-next-line security/no-block-members*/ require(_startTime >= now && _endTime > _startTime, "Invalid times"); startTime = _startTime; endTime = _endTime; emit SetTimes(_startTime, _endTime); } function _modifyWalletAddress(address payable _wallet) internal { require(_wallet != address(0), "Invalid wallet"); emit SetWallet(wallet, _wallet); wallet = _wallet; } function _modifyTreasuryWallet(address _treasuryWallet) internal { emit SetTreasuryWallet(treasuryWallet, _treasuryWallet); treasuryWallet = _treasuryWallet; } //////////////////// // STO Management // //////////////////// /** * @notice Finalizes the STO and mints remaining tokens to treasury address * @notice Treasury address must be whitelisted to successfully finalize * @param _mintUnsoldTokens unsold tokens will be minted to the Treasury wallet if ture */ function finalize(bool _mintUnsoldTokens) external { _onlySecurityTokenOwner(); require(!isFinalized, "Already finalized"); isFinalized = true; if ((_mintUnsoldTokens) && (totalTokensSold < cap)) { address treasury = (treasuryWallet == address(0) ? IDataStore(getDataStore()).getAddress(TREASURY) : treasuryWallet); require(treasury != address(0), "Invalid treasury address"); uint256 granularity = ISecurityToken(securityToken).granularity(); finalAmountReturned = cap.sub(totalTokensSold); finalAmountReturned = finalAmountReturned.div(granularity); finalAmountReturned = finalAmountReturned.mul(granularity); ISecurityToken(securityToken).issue(treasury, finalAmountReturned, ""); emit ReserveTokenMint(msg.sender, treasury, finalAmountReturned); } } /** * @notice Modifies the list of overrides for non-accredited limits in POLY * @param _investors Array of investor addresses to modify * @param _nonAccreditedLimit Array of uints specifying non-accredited limits */ function changeNonAccreditedLimit(address[] calldata _investors, uint256[] calldata _nonAccreditedLimit) external { _onlySecurityTokenOwner(); require(_investors.length == _nonAccreditedLimit.length, "Length mismatch"); for (uint256 i = 0; i < _investors.length; i++) { nonAccreditedLimitOverride[_investors[i]] = _nonAccreditedLimit[i]; emit SetNonAccreditedLimit(_investors[i], _nonAccreditedLimit[i]); } } /** * @notice Function to set allowBeneficialInvestments (allow beneficiary to be different to funder) * @param _allowBeneficialInvestments Boolean to allow or disallow beneficial investments */ function changeAllowBeneficialInvestments(bool _allowBeneficialInvestments) external { _onlySecurityTokenOwner(); require(_allowBeneficialInvestments != allowBeneficialInvestments, "Does not change value"); allowBeneficialInvestments = _allowBeneficialInvestments; emit SetAllowBeneficialInvestments(allowBeneficialInvestments); } ////////////////////////// // Investment Functions // ////////////////////////// /** * @notice no fallback function - non-payable function() external {} */ /** * @notice Purchase tokens using POLY * @param _beneficiary Address where security tokens will be sent * @param _investedPOLY Amount of POLY invested */ function buyWithPOLY(address _beneficiary, uint256 _investedPOLY) external { _buyWithTokens(_beneficiary, _investedPOLY, FundRaiseType.POLY, polyToken); } /** * @notice Function to buy using an ERC20 token (POLY) * @param _beneficiary Address where security tokens will be sent * @param _investedTokens Amount of token invested * @param _fundRaiseType Fund raise type (POLY) * @param _token Token used for investment i.e. POLY */ function _buyWithTokens( address _beneficiary, uint256 _investedTokens, FundRaiseType _fundRaiseType, IERC20 _token ) internal { if (!allowBeneficialInvestments) { require(_beneficiary == msg.sender, "Beneficiary is not funder"); } require(_canBuy(_beneficiary), "Unauthorized beneficiary"); uint256 spentValue = _buyTokens(_beneficiary, _investedTokens, _fundRaiseType); // Forward coins to issuer wallet require(_token.transferFrom(msg.sender, wallet, spentValue), "Transfer failed"); emit FundsReceived(msg.sender, _beneficiary, _fundRaiseType, _investedTokens, spentValue); } /** * @notice Low level token purchase * @param _beneficiary Address where security tokens will be sent * @param _investedTokens Amount of POLY invested * @param _fundRaiseType Fund raise type (POLY) */ function _buyTokens( address _beneficiary, uint256 _investedTokens, FundRaiseType _fundRaiseType ) internal nonReentrant whenNotPaused returns(uint256 spentValue) { uint256 tokens; bool accredited; (tokens, spentValue, accredited) = prePurchaseChecks (_beneficiary, _investedTokens); _processPurchase(_beneficiary, tokens, accredited); uint256 polyUsdRate = IOracle(IPolymathRegistry(ISecurityToken(securityToken).polymathRegistry()).getAddress(POLY_ORACLE)).getPrice(); uint256 spentUSD = DecimalMath.mul(spentValue, polyUsdRate); emit TokenPurchase(msg.sender, _beneficiary, spentValue, spentUSD, tokens); // Modify storage investorInvestedPOLY[_beneficiary] = investorInvestedPOLY[_beneficiary].add(spentValue); fundsRaised[uint8(_fundRaiseType)] = fundsRaised[uint8(_fundRaiseType)].add(spentValue); investorInvestedUSD[_beneficiary] = investorInvestedUSD[_beneficiary].add(spentUSD); fundsRaisedUSD = fundsRaisedUSD.add(spentUSD); totalTokensSold = totalTokensSold.add(tokens); } /** * @notice Checks restrictions related to the token purchase and calculates number of tokens * @notice and calculates the number of tokens and spent value based on those restrictions * @param _beneficiary Address where security tokens will be sent * @param _investedTokens Amount of POLY invested * @return tokens Number of tokens the _beneficiary will recieve * @return spentValue Number of POLY that will be spent to buy the number of tokens */ function prePurchaseChecks(address _beneficiary, uint256 _investedTokens) public view returns( uint256 tokens, uint256 spentValue, bool accredited ) { //Pre-Purchase checks require(isOpen(), "STO not open"); require(_investedTokens > 0, "No funds sent"); require(_beneficiary != address(0), "Invalid beneficiary"); require(_investedTokens.add(investorInvestedPOLY[_beneficiary]) >= minimumInvestment, "Less than minimum investment"); accredited = _isAccredited(_beneficiary); // Accredited investors are not limited uint256 allowedInvestment = _investedTokens; // Check for non-accredited investor limits if (!accredited) { uint256 investorLimit = (nonAccreditedLimitOverride[_beneficiary] == 0) ? nonAccreditedLimit : nonAccreditedLimitOverride[_beneficiary]; require(investorInvestedPOLY[_beneficiary] < investorLimit, "Investment limit reached"); if (_investedTokens.add(investorInvestedPOLY[_beneficiary]) > investorLimit) { allowedInvestment = investorLimit.sub(investorInvestedPOLY[_beneficiary]); } if (maxNonAccreditedInvestors != 0) { require(nonAccreditedCount < maxNonAccreditedInvestors, "Max non-accredited investors"); } } // Get the number of tokens to be minted and value in POLY tokens = _getTokenAmount(allowedInvestment); spentValue = DecimalMath.div(tokens, rate); // In case of rounding issues, ensure that spentValue is never more than _investedTokens if (spentValue > _investedTokens) { spentValue = _investedTokens; } } /** * @notice Gets the number of tokens that will be issued based on rate and granularity * @param _investedAmount Value in POLY (by 10^18) to be converted into tokens * @return tokens Number of tokens that can be purchased with the specified _investedAmount */ function _getTokenAmount(uint256 _investedAmount) internal view returns (uint256 tokens) { tokens = DecimalMath.mul(_investedAmount, rate); if (totalTokensSold.add(tokens) > cap) { tokens = cap.sub(totalTokensSold); } uint256 granularity = ISecurityToken(securityToken).granularity(); tokens = tokens.div(granularity); tokens = tokens.mul(granularity); require(tokens > 0, "No tokens"); } /** * @notice Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount, bool _accredited) internal { if (investorInvestedPOLY[_beneficiary] == 0) { investorCount = investorCount + 1; if (!_accredited) { nonAccreditedCount = nonAccreditedCount + 1; } } _deliverTokens(_beneficiary, _tokenAmount); } /** * @notice Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { ISecurityToken(securityToken).issue(_beneficiary, _tokenAmount, ""); } function _isAccredited(address _investor) internal view returns(bool) { IDataStore dataStore = getDataStore(); return _getIsAccredited(_investor, dataStore); } function _getIsAccredited(address _investor, IDataStore dataStore) internal view returns(bool) { uint256 flags = dataStore.getUint256(_getKey(INVESTORFLAGS, _investor)); uint256 flag = flags & uint256(1); //isAccredited is flag 0 so we don't need to bit shift flags. return flag > 0 ? true : false; } ///////////// // Getters // ///////////// /** * @notice This function returns whether or not the STO is in fundraising mode (open) * @return bool Whether the STO is accepting investments */ function isOpen() public view returns(bool) { /*solium-disable-next-line security/no-block-members*/ if (isFinalized || now < startTime || now >= endTime || capReached()) return false; return true; } /** * @notice Checks whether the cap has been reached. * @return bool Whether the cap was reached */ function capReached() public view returns (bool) { return totalTokensSold >= cap; } /** * @notice Return the total no. of tokens sold * @return uint256 Total number of tokens sold */ function getTokensSold() external view returns (uint256) { return totalTokensSold; } /** * @notice Return the permissions flag that are associated with STO */ function getPermissions() external view returns(bytes32[] memory allPermissions) { return allPermissions; } /** * @notice Returns investor accredited & non-accredited override informatiomn * @return investors list of all configured investors * @return accredited whether investor is accredited * @return override any overrides for non-accredited limits for the investor */ function getAccreditedData() external view returns (address[] memory investors, bool[] memory accredited, uint256[] memory overrides) { IDataStore dataStore = getDataStore(); investors = dataStore.getAddressArray(INVESTORSKEY); accredited = new bool[](investors.length); overrides = new uint256[](investors.length); for (uint256 i = 0; i < investors.length; i++) { accredited[i] = _getIsAccredited(investors[i], dataStore); overrides[i] = nonAccreditedLimitOverride[investors[i]]; } } /** * @notice Return the STO details * @return startTime - Unixtimestamp at which offering gets start. * @return endTime - Unixtimestamp at which offering ends. * @return cap - Number of token base units this STO will be allowed to sell to investors. * @return rate - Token units a buyer gets(multiplied by 10^18) base unit of POLY * @return minimumInvestment - minimum investment in POLY * @return nonAccreditedLimit - default non accredited investor limit in POLY * @return maxNonAccreditedInvestors - maximum number of non-accredited investors that can invest in the offering * @return totalTokensSold - Amount of tokens get sold. * @return fundsRaisedPOLY - Amount of funds raised in POLY * @return fundsRaisedUSD - Amount of funds raised converted to USD at time of investment * @return investorCount - Number of individual investors this STO have. * @return nonAccreditedCount - Number of non-accredited investor that have invested in the offering */ function getSTODetails() external view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { uint256 fundsRaisedPOLY = fundsRaised[uint8(FundRaiseType.POLY)]; return ( startTime, endTime, cap, rate, minimumInvestment, nonAccreditedLimit, maxNonAccreditedInvestors, totalTokensSold, fundsRaisedPOLY, fundsRaisedUSD, investorCount, nonAccreditedCount ); } /** * @notice This function returns the signature of configure function */ function getInitFunction() external pure returns (bytes4) { return this.configure.selector; } }
This function returns whether or not the STO is in fundraising mode (open) return bool Whether the STO is accepting investments/
function isOpen() public view returns(bool) { if (isFinalized || now < startTime || now >= endTime || capReached()) return false; return true;
15,808,852
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../../BdStable/BDStable.sol"; import "../../Oracle/ICryptoPairOracle.sol"; import "./BdPoolLibrary.sol"; import "../../Utils/IWETH.sol"; contract BdStablePool is OwnableUpgradeable { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 private BDX; IWETH private NativeTokenWrapper; IERC20 public collateral_token; BDStable public BDSTABLE; ICryptoPairOracle public collatWEthOracle; bool public is_collateral_wrapping_native_token; uint256 private missing_decimals; // Number of decimals needed to get to 18 address private weth_address; mapping(address => uint256) public redeemBDXBalances; mapping(address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; mapping(address => uint256) public lastRedeemed; // AccessControl state variables bool public mintPaused; bool public redeemPaused; bool public recollateralizePaused; bool public buyBackPaused; bool public collateralPricePaused; bool public recollateralizeOnlyForOwner; bool public buybackOnlyForOwner; uint256 public minting_fee; //d12 uint256 public redemption_fee; //d12 uint256 public buyback_fee; //d12 uint256 public recollat_fee; //d12 // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling; // d18 // Stores price of the collateral, if price is paused uint256 public pausedPrice; // Bonus rate on BDX minted during recollateralizeBdStable(); 12 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate; // d12 // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay; /* ========== MODIFIERS ========== */ modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ function initialize( address _bdstable_contract_address, address _bdx_contract_address, address _collateral_address, uint256 _collateral_decimals, bool _is_collateral_wrapping_native_token ) external initializer { require(_bdstable_contract_address != address(0), "BdStable address cannot be 0"); require(_bdx_contract_address != address(0), "BDX address cannot be 0"); require(_collateral_address != address(0), "Collateral address cannot be 0"); __Ownable_init(); BDSTABLE = BDStable(_bdstable_contract_address); BDX = IERC20(_bdx_contract_address); if (_is_collateral_wrapping_native_token) { NativeTokenWrapper = IWETH(_collateral_address); } collateral_token = IERC20(_collateral_address); missing_decimals = uint256(18) - _collateral_decimals; is_collateral_wrapping_native_token = _is_collateral_wrapping_native_token; pool_ceiling = 1e36; // d18 bonus_rate = 7500000000; // d12 0.75% redemption_delay = 1; minting_fee = 3000000000; // d12 0.3% redemption_fee = 3000000000; // d12 0.3% recollateralizeOnlyForOwner = false; buybackOnlyForOwner = true; } /* ========== VIEWS ========== */ // Returns the price of the pool collateral in fiat function getCollateralPrice_d12() public view returns (uint256) { if (collateralPricePaused == true) { return pausedPrice; } else { uint256 eth_fiat_price_d12 = BDSTABLE.weth_fiat_price(); uint256 collat_eth_price = collatWEthOracle.consult(weth_address, BdPoolLibrary.PRICE_PRECISION); return (eth_fiat_price_d12 * BdPoolLibrary.PRICE_PRECISION) / collat_eth_price; } } // Returns fiat value of collateral held in this BdStable pool function collatFiatBalance() external view returns (uint256) { //Expressed in collateral token decimals if (collateralPricePaused == true) { return ((collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral) * (10**missing_decimals) * pausedPrice) / BdPoolLibrary.PRICE_PRECISION; } else { return ((collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral) * (10**missing_decimals) * getCollateralPrice_d12()) / BdPoolLibrary.PRICE_PRECISION; } } /* ========== PUBLIC FUNCTIONS ========== */ function updateOraclesIfNeeded() public { BDSTABLE.updateOraclesIfNeeded(); if (collatWEthOracle.shouldUpdateOracle()) { collatWEthOracle.updateOracle(); } } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalBdStable( uint256 collateral_amount_in_max, uint256 bdx_in_max, uint256 bdStable_out_min, bool useNativeToken ) external payable notMintPaused { if (useNativeToken) { require(is_collateral_wrapping_native_token, "Pool doesn't support native token"); require(msg.value == collateral_amount_in_max, "msg.value and collateral_amount_in_max do not match"); } updateOraclesIfNeeded(); uint256 bdx_price = BDSTABLE.BDX_price_d12(); uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12(); if (global_collateral_ratio_d12 == 0) { collateral_amount_in_max = 0; } else if (global_collateral_ratio_d12 == BdPoolLibrary.COLLATERAL_RATIO_MAX) { bdx_in_max = 0; } require( (collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral + collateral_amount_in_max) <= pool_ceiling, "Pool ceiling reached, no more BdStable can be minted with this collateral" ); uint256 collateral_amount_in_max_d18 = collateral_amount_in_max * (10**missing_decimals); uint256 mint_amount; uint256 bdx_needed; if (global_collateral_ratio_d12 == 0) { mint_amount = BdPoolLibrary.calcMintAlgorithmicBD(bdx_price, bdx_in_max); bdx_needed = bdx_in_max; } else if (global_collateral_ratio_d12 == 1) { mint_amount = BdPoolLibrary.calcMint1t1BD(getCollateralPrice_d12(), collateral_amount_in_max_d18); bdx_needed = 0; } else { (mint_amount, bdx_needed) = BdPoolLibrary.calcMintFractionalBD( bdx_price, getCollateralPrice_d12(), collateral_amount_in_max_d18, global_collateral_ratio_d12 ); } mint_amount = (mint_amount * (uint256(BdPoolLibrary.PRICE_PRECISION) - minting_fee)) / BdPoolLibrary.PRICE_PRECISION; require(bdStable_out_min <= mint_amount, "Slippage limit reached"); require(bdx_needed <= bdx_in_max, "Not enough BDX inputted"); BDSTABLE.refreshCollateralRatio(); if (bdx_needed > 0) { BDX.safeTransferFrom(msg.sender, address(BDSTABLE), bdx_needed); } if (collateral_amount_in_max > 0) { if (useNativeToken) { NativeTokenWrapper.deposit{value: collateral_amount_in_max}(); } else { collateral_token.safeTransferFrom(msg.sender, address(this), collateral_amount_in_max); } } BDSTABLE.pool_mint(msg.sender, mint_amount); } // Will fail if fully collateralized or algorithmic // Redeem BDSTABLE for collateral and BDX. > 0% and < 100% collateral-backed function redeemFractionalBdStable( uint256 BdStable_amount, uint256 BDX_out_min, uint256 COLLATERAL_out_min ) external notRedeemPaused { updateOraclesIfNeeded(); uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12(); uint256 effective_global_collateral_ratio_d12 = BDSTABLE.effective_global_collateral_ratio_d12(); uint256 cr_d12 = effective_global_collateral_ratio_d12 < global_collateral_ratio_d12 ? effective_global_collateral_ratio_d12 : global_collateral_ratio_d12; uint256 BdStable_amount_post_fee = (BdStable_amount * (uint256(BdPoolLibrary.PRICE_PRECISION) - redemption_fee)) / BdPoolLibrary.PRICE_PRECISION; uint256 bdx_fiat_value_d18 = BdStable_amount_post_fee - ((BdStable_amount_post_fee * cr_d12) / BdPoolLibrary.PRICE_PRECISION); uint256 bdx_amount = (bdx_fiat_value_d18 * BdPoolLibrary.PRICE_PRECISION) / BDSTABLE.BDX_price_d12(); uint256 bdx_coverage_ratio = BDSTABLE.get_effective_bdx_coverage_ratio(); bdx_amount = (bdx_amount * bdx_coverage_ratio) / BdPoolLibrary.COLLATERAL_RATIO_PRECISION; // Need to adjust for decimals of collateral uint256 BdStable_amount_precision = BdStable_amount_post_fee / (10**missing_decimals); uint256 collateral_fiat_value = (BdStable_amount_precision * cr_d12) / BdPoolLibrary.PRICE_PRECISION; uint256 collateral_needed = (collateral_fiat_value * BdPoolLibrary.PRICE_PRECISION) / getCollateralPrice_d12(); require(collateral_needed <= collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral, "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached [collateral]"); require(BDX_out_min <= bdx_amount, "Slippage limit reached [BDX]"); require(BDSTABLE.canLegallyRedeem(msg.sender), "Cannot legally redeem"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender] + collateral_needed; unclaimedPoolCollateral = unclaimedPoolCollateral + collateral_needed; BDSTABLE.refreshCollateralRatio(); if (bdx_amount > 0) { require(BDSTABLE.canLegallyRedeem(msg.sender), "Cannot legally redeem"); redeemBDXBalances[msg.sender] = redeemBDXBalances[msg.sender] + bdx_amount; BDSTABLE.pool_claim_bdx(bdx_amount); } lastRedeemed[msg.sender] = block.number; // Move all external functions to the end BDSTABLE.pool_burn_from(msg.sender, BdStable_amount); } // After a redemption happens, transfer the newly minted BDX and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out BdStable/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption(bool useNativeToken) external { require((lastRedeemed[msg.sender] + redemption_delay) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendBDX = false; bool sendCollateral = false; uint256 BDXAmount; uint256 CollateralAmount; // Use Checks-Effects-Interactions pattern if (redeemBDXBalances[msg.sender] > 0) { BDXAmount = redeemBDXBalances[msg.sender]; redeemBDXBalances[msg.sender] = 0; sendBDX = true; } if (redeemCollateralBalances[msg.sender] > 0) { CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral - CollateralAmount; sendCollateral = true; } if (sendBDX == true) { BDSTABLE.pool_transfer_claimed_bdx(msg.sender, BDXAmount); } if (sendCollateral == true) { if (useNativeToken) { NativeTokenWrapper.withdraw(CollateralAmount); safeTransferETH(msg.sender, CollateralAmount); } else { collateral_token.safeTransfer(msg.sender, CollateralAmount); } } } // When the protocol is recollateralizing, we need to give a discount of BDX to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get BDX for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of BDX + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra BDX value from the bonus rate as an arb opportunity function recollateralizeBdStable( uint256 collateral_amount, uint256 BDX_out_min, bool useNativeToken ) external payable { require(recollateralizePaused == false, "Recollateralize is paused"); if (recollateralizeOnlyForOwner) { require(msg.sender == owner(), "Currently only owner can recollateralize"); } if (useNativeToken) { require(is_collateral_wrapping_native_token, "Pool doesn't support native token"); require(msg.value == collateral_amount, "msg.value and collateral_amount do not match"); } updateOraclesIfNeeded(); uint256 collateral_amount_d18 = collateral_amount * (10**missing_decimals); uint256 bdx_price = BDSTABLE.BDX_price_d12(); uint256 bdStable_total_supply = BDSTABLE.totalSupply(); uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12(); uint256 global_collat_value = BDSTABLE.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = BdPoolLibrary.calcRecollateralizeBdStableInner( collateral_amount_d18, getCollateralPrice_d12(), global_collat_value, bdStable_total_supply, global_collateral_ratio_d12 ); uint256 collateral_units_precision = collateral_units / (10**missing_decimals); uint256 bdx_paid_back = (amount_to_recollat * (uint256(BdPoolLibrary.PRICE_PRECISION) + bonus_rate - recollat_fee)) / bdx_price; uint256 bdx_coverage_ratio = BDSTABLE.get_effective_bdx_coverage_ratio(); bdx_paid_back = (bdx_paid_back * bdx_coverage_ratio) / BdPoolLibrary.COLLATERAL_RATIO_PRECISION; require(BDX_out_min <= bdx_paid_back, "Slippage limit reached"); BDSTABLE.refreshCollateralRatio(); if (useNativeToken) { // no need to check collateral_units_precision, it's <= then collateral_amount NativeTokenWrapper.deposit{value: collateral_units_precision}(); // refund remaining native token, if any left if (msg.value > collateral_units_precision) { safeTransferETH(msg.sender, msg.value - collateral_units_precision); } } else { collateral_token.safeTransferFrom(msg.sender, address(this), collateral_units_precision); } if (bdx_paid_back > 0) { BDSTABLE.transfer_bdx(msg.sender, bdx_paid_back); } emit Recollateralized(collateral_units_precision, bdx_paid_back); } // Function can be called by an BDX holder to have the protocol buy back BDX with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackBDX( uint256 BDX_amount, uint256 COLLATERAL_out_min, bool useNativeToken ) external { require(buyBackPaused == false, "Buyback is paused"); if (buybackOnlyForOwner) { require(msg.sender == owner(), "Currently only owner can buyback"); } updateOraclesIfNeeded(); uint256 bdx_price = BDSTABLE.BDX_price_d12(); uint256 collateral_equivalent_d18 = (BdPoolLibrary.calcBuyBackBDX( BDSTABLE.availableExcessCollatDV(), bdx_price, getCollateralPrice_d12(), BDX_amount ) * (uint256(BdPoolLibrary.PRICE_PRECISION) - buyback_fee)) / BdPoolLibrary.PRICE_PRECISION; uint256 collateral_precision = collateral_equivalent_d18 / (10**missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Take bdx from sender BDX.safeTransferFrom(msg.sender, address(BDSTABLE), BDX_amount); if (useNativeToken) { // Give the sender their desired collateral NativeTokenWrapper.withdraw(collateral_precision); safeTransferETH(msg.sender, collateral_precision); } else { // Give the sender their desired collateral collateral_token.safeTransfer(msg.sender, collateral_precision); } emit BoughtBack(BDX_amount, collateral_precision); } receive() external payable { require(msg.sender == address(NativeTokenWrapper), "Only native token wrapper allowed to send native token"); } /* ========== RESTRICTED FUNCTIONS ========== */ function setCollatWETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyOwner { require(_collateral_weth_oracle_address != address(0), "Oracle cannot be set to the zero address"); require(_weth_address != address(0), "WETH cannot be set to the zero address"); collatWEthOracle = ICryptoPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; emit CollateralWethOracleSet(_collateral_weth_oracle_address, _weth_address); } function toggleMintingPaused() external onlyOwner { mintPaused = !mintPaused; emit MintingPausedToggled(mintPaused); } function toggleRedeemingPaused() external onlyOwner { redeemPaused = !redeemPaused; emit RedeemingPausedToggled(redeemPaused); } function toggleRecollateralizePaused() external onlyOwner { recollateralizePaused = !recollateralizePaused; emit RecollateralizePausedToggled(recollateralizePaused); } function toggleBuybackPaused() external onlyOwner { buyBackPaused = !buyBackPaused; emit BuybackPausedToggled(buyBackPaused); } function toggleBuybackOnlyForOwner() external onlyOwner { buybackOnlyForOwner = !buybackOnlyForOwner; emit BuybackOnlyForOwnerToggled(buybackOnlyForOwner); } function toggleRecollateralizeOnlyForOwner() external onlyOwner { recollateralizeOnlyForOwner = !recollateralizeOnlyForOwner; emit RecollateralizeOnlyForOwnerToggled(recollateralizeOnlyForOwner); } function toggleCollateralPricePaused(uint256 _new_price) external onlyOwner { // If pausing, set paused price; else if unpausing, clear pausedPrice if (collateralPricePaused == false) { pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; emit CollateralPriceToggled(collateralPricePaused); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters( uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee ) external onlyOwner { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "ETH transfer failed"); } /* ========== EVENTS ========== */ event PoolParametersSet( uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee ); event MintingPausedToggled(bool toggled); event RedeemingPausedToggled(bool toggled); event RecollateralizePausedToggled(bool toggled); event BuybackPausedToggled(bool toggled); event CollateralPriceToggled(bool toggled); event CollateralWethOracleSet(address indexed collateral_weth_oracle_address, address indexed weth_address); event RecollateralizeOnlyForOwnerToggled(bool recollateralizeOnlyForOwner); event BuybackOnlyForOwnerToggled(bool buybackOnlyForOwner); event Recollateralized(uint256 indexed collateral_amount_paid, uint256 indexed bdx_paid_back); event BoughtBack(uint256 indexed bdx_amount_paid, uint256 indexed collateral_paid_back); }
Will fail if fully collateralized or fully algorithmic > 0% and < 100% collateral-backed
function mintFractionalBdStable( uint256 collateral_amount_in_max, uint256 bdx_in_max, uint256 bdStable_out_min, bool useNativeToken ) external payable notMintPaused { if (useNativeToken) { require(is_collateral_wrapping_native_token, "Pool doesn't support native token"); require(msg.value == collateral_amount_in_max, "msg.value and collateral_amount_in_max do not match"); } updateOraclesIfNeeded(); uint256 bdx_price = BDSTABLE.BDX_price_d12(); uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12(); if (global_collateral_ratio_d12 == 0) { collateral_amount_in_max = 0; bdx_in_max = 0; } require( (collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral + collateral_amount_in_max) <= pool_ceiling, "Pool ceiling reached, no more BdStable can be minted with this collateral" ); uint256 collateral_amount_in_max_d18 = collateral_amount_in_max * (10**missing_decimals); uint256 mint_amount; uint256 bdx_needed; if (global_collateral_ratio_d12 == 0) { mint_amount = BdPoolLibrary.calcMintAlgorithmicBD(bdx_price, bdx_in_max); bdx_needed = bdx_in_max; mint_amount = BdPoolLibrary.calcMint1t1BD(getCollateralPrice_d12(), collateral_amount_in_max_d18); bdx_needed = 0; (mint_amount, bdx_needed) = BdPoolLibrary.calcMintFractionalBD( bdx_price, getCollateralPrice_d12(), collateral_amount_in_max_d18, global_collateral_ratio_d12 ); } mint_amount = (mint_amount * (uint256(BdPoolLibrary.PRICE_PRECISION) - minting_fee)) / BdPoolLibrary.PRICE_PRECISION; require(bdStable_out_min <= mint_amount, "Slippage limit reached"); require(bdx_needed <= bdx_in_max, "Not enough BDX inputted"); BDSTABLE.refreshCollateralRatio(); if (bdx_needed > 0) { BDX.safeTransferFrom(msg.sender, address(BDSTABLE), bdx_needed); } if (collateral_amount_in_max > 0) { if (useNativeToken) { collateral_token.safeTransferFrom(msg.sender, address(this), collateral_amount_in_max); } } BDSTABLE.pool_mint(msg.sender, mint_amount); }
13,085,539
pragma solidity >=0.4.22 <0.6.0; import './SafeMath.sol'; interface ERC20Interface { function allowance(address, address) external view returns (uint); function balanceOf(address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } /** Swap Functionality */ interface ScdMcdMigration { function swapEthToSai(uint daiAmt) external; } contract Helpers{ /** * @dev get uniswap DAI exchange */ function getUniswapDAIExchange() public pure returns (address ude) { // ude = 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14; // Proxy Address } function getSaiAddress() public pure returns (address saiAddr) { // troller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } /** * @dev get Eth address */ function getEthAddress() public pure returns (address daiAddr) { // troller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } } contract MigrationProxyActions is Helpers{ function swapEthToSai( address userAddress, // Migration contract address uint wad // Amount to swap ) internal { ERC20Interface sai = ERC20Interface(getSaiAddress()); ERC20Interface eth = ERC20Interface(getEthAddress()); if (eth.allowance(address(this), userAddress) < wad) { sai.approve(userAddress, wad); ScdMcdMigration(userAddress).swapEthToSai(wad); } } } contract FarmEasy { using SafeMath for uint256; /** @dev Product Details * @param index ID of the Product * @param owner address of the farmer * @parma category Classify as Crop, Livestock and Poultry * @param name different products of crop/livestock/Poultry * @param quantity Amount of product */ struct Product { bool active; address owner; string category; string name; uint256 quantity; uint256 index; uint256 sellingPrice; //per piece } /** @dev Farmer's Registration on platform * @param farmer Eth Address of farmer * @param farmAddress Name, Location, Country * @param registeredProductsKeys Id of the registered products. * @param soldProductsKeys Id of the Sell order records. * @param registeredProducts Products registed by the farmer. * @notice Products between RegisteredFarmers are added and removed from the registeredProducts array @notice Famer address are generated when a farmer registers for the services */ struct Farmer { bool active; address farmer; string farmAddress; uint256[] registeredProductsKeys; uint256[] soldProductsKeys; mapping(uint256 => Product) registeredProducts; } struct Buyer{ bool active; address buyer; uint256[] boughtProductsKeys; mapping (uint256 => Product) boughtProducts; } /** * Events */ event FarmerRegistration(address _farmer); event BuyerRegistration(address _farmer); event SuccesfullyRegistered(address _farmer, uint256 index, string name, uint256 sellingPrice); /** * Modifier */ modifier onlyAdmin() { require(msg.sender == owner, "Only owner can call this function"); _; } address owner; mapping(address => Farmer) RegisteredFarmers; mapping(address => Buyer) RegisteredBuyers; mapping(uint256 => Product) RegisteredProducts; mapping(uint256 => Product) RequestedProducts; uint256 currentIndexProducts; constructor() public { owner = msg.sender; } /** * FUNCTIONS */ function registerFarmer(string memory farmAddress) public returns(bool) { require(msg.sender != address(0), "Invalid sender address"); require(!RegisteredFarmers[msg.sender].active, "farmer already registered"); RegisteredFarmers[msg.sender].active = true; RegisteredFarmers[msg.sender].farmAddress = farmAddress; RegisteredFarmers[msg.sender].farmer = msg.sender; emit FarmerRegistration(msg.sender); return RegisteredFarmers[msg.sender].active; } function checkFarmerRegistration() public view returns(bool) { require(msg.sender != address(0), "Invalid sender address"); return RegisteredFarmers[msg.sender].active; } function registerProduct(string memory categories, uint256 sellingprice, string memory name) public returns(bool) { require(msg.sender != address(0), "Invalid sender address"); require(RegisteredFarmers[msg.sender].active, "farmer not registered"); require(sellingprice > 0, "selling price is required to be greater than 0"); RegisteredProducts[currentIndexProducts].owner = msg.sender; RegisteredProducts[currentIndexProducts].index = currentIndexProducts; RegisteredProducts[currentIndexProducts].category = categories; RegisteredProducts[currentIndexProducts].active = true; RegisteredProducts[currentIndexProducts].name = name; RegisteredProducts[currentIndexProducts].sellingPrice = sellingprice; RegisteredFarmers[msg.sender].registeredProducts[currentIndexProducts] = RegisteredProducts[currentIndexProducts]; RegisteredFarmers[msg.sender].registeredProductsKeys.push(currentIndexProducts); currentIndexProducts = currentIndexProducts.add(1); emit SuccesfullyRegistered(msg.sender, currentIndexProducts-1, name, sellingprice); return true; } function getFarmerRegisteredProductKeys() public view returns(uint256[] memory) { require(msg.sender != address(0), "Invalid sender address"); require(RegisteredFarmers[msg.sender].active, "Famer not registered"); return RegisteredFarmers[msg.sender].registeredProductsKeys; } function productExists(uint256 id) public view returns(bool) { require(msg.sender != address(0), "Invalid sender address"); require(id >= 0, "product id must be equal to and greater than 0"); return RegisteredProducts[id].active; } function getTotalSupply() public view returns(uint256) { require(msg.sender != address(0)); return currentIndexProducts; } function registerBuyer() public returns(bool) { require(msg.sender != address(0), "Invalid sender address"); require(!RegisteredBuyers[msg.sender].active, "Buyer already registered"); RegisteredBuyers[msg.sender].active = true; RegisteredBuyers[msg.sender].buyer = msg.sender; emit BuyerRegistration(msg.sender); return true; } function buyProduct(uint256 productId) public payable returns(bool) { require(msg.sender != address(0), "Invalid sender address"); require(RegisteredFarmers[msg.sender].active, "You currently not registered"); require(RegisteredProducts[productId].active, "Product already sold or does not exits"); address productOwner = RegisteredProducts[productId].owner; require(productOwner != msg.sender, "Cannot buy a product from your self"); require(RegisteredFarmers[productOwner].active, "Product seller not not registered"); require(productId >= 0, "Product Id must be equal to and greater than 0"); require(msg.value > 0, "Contract cut has to be greater than 0 Eth"); RegisteredFarmers[msg.sender].active = false; RegisteredBuyers[msg.sender].boughtProducts[productId] = RegisteredFarmers[productOwner].registeredProducts[productId]; RegisteredBuyers[msg.sender].boughtProductsKeys.push(productId); return true; } }
get Eth address/ troller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getEthAddress() public pure returns (address daiAddr) { }
6,450,533