file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/1/0x3c1164531d5857029ae5412E49999306547834d8/sources/@rmrk-team/evm-contracts/contracts/RMRK/equippable/RMRKMinifiedEquippable.sol
@inheritdoc IERC6220/
function getEquipment( uint256 tokenId, address targetCatalogAddress, uint64 slotPartId ) public view virtual returns (Equipment memory) { return _equipments[tokenId][targetCatalogAddress][slotPartId]; }
9,657,813
//Address: 0xa71074b6c4a31c1d1798b04801a89d78f6e26123 //Contract name: VNETToken //Balance: 0 Ether //Verification Date: 5/3/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed _from, address indexed _to, uint256 _value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } /** * @dev Rescue compatible ERC20Basic Token * * @param _token ERC20Basic The address of the token contract */ function rescueTokens(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); assert(_token.transfer(owner, balance)); } /** * @dev Withdraw Ether */ function withdrawEther() external onlyOwner { owner.transfer(address(this).balance); } } /** * @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) { 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 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; } /** * @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; } } /** * @title Basic token, Lockable * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; uint256 totalSupply_; mapping(address => uint256) balances; mapping(address => uint256) lockedBalanceMap; // locked balance: address => amount mapping(address => uint256) releaseTimeMap; // release time: address => timestamp event BalanceLocked(address indexed _addr, uint256 _amount); /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev function to make sure the balance is not locked * @param _addr address * @param _value uint256 */ function checkNotLocked(address _addr, uint256 _value) internal view returns (bool) { uint256 balance = balances[_addr].sub(_value); if (releaseTimeMap[_addr] > block.timestamp && balance < lockedBalanceMap[_addr]) { revert(); } return true; } /** * @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]); checkNotLocked(msg.sender, _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return Amount. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Gets the locked balance of the specified address. * @param _owner The address to query. * @return Amount. */ function lockedBalanceOf(address _owner) public view returns (uint256) { return lockedBalanceMap[_owner]; } /** * @dev Gets the release timestamp of the specified address if it has a locked balance. * @param _owner The address to query. * @return Timestamp. */ function releaseTimeOf(address _owner) public view returns (uint256) { return releaseTimeMap[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ 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]); checkNotLocked(_from, _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Abstract Standard ERC20 token */ contract AbstractToken is Ownable, StandardToken { string public name; string public symbol; uint256 public decimals; string public value; // Stable Value string public description; // Description string public website; // Website string public email; // Email string public news; // Latest News uint256 public cap; // Cap Limit mapping (address => bool) public mintAgents; // Mint Agents event Mint(address indexed _to, uint256 _amount); event MintAgentChanged(address _addr, bool _state); event NewsPublished(string _news); /** * @dev Set Info * * @param _description string * @param _website string * @param _email string */ function setInfo(string _description, string _website, string _email) external onlyOwner returns (bool) { description = _description; website = _website; email = _email; return true; } /** * @dev Set News * * @param _news string */ function setNews(string _news) external onlyOwner returns (bool) { news = _news; emit NewsPublished(_news); return true; } /** * @dev Set a mint agent address * * @param _addr address The address that will receive the minted tokens. * @param _state bool The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function setMintAgent(address _addr, bool _state) onlyOwner public returns (bool) { mintAgents[_addr] = _state; emit MintAgentChanged(_addr, _state); return true; } /** * @dev Constructor */ constructor() public { setMintAgent(msg.sender, true); } } /** * @dev VNET Token for Vision Network Project */ contract VNETToken is Ownable, AbstractToken { event Donate(address indexed _from, uint256 _amount); /** * @dev Constructor */ constructor() public { name = "VNET Token"; symbol = "VNET"; decimals = 6; value = "1 Token = 100 GByte client newtwork traffic flow"; // 35 Billion Total cap = 35000000000 * (10 ** decimals); } /** * @dev Sending eth to this contract will be considered as a donation */ function () public payable { emit Donate(msg.sender, msg.value); } /** * @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) external returns (bool) { require(mintAgents[msg.sender] && totalSupply_.add(_amount) <= cap); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to mint tokens, and lock some of them with a release time * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @param _lockedAmount The amount of tokens to be locked. * @param _releaseTime The timestamp about to release, which could be set just once. * @return A boolean that indicates if the operation was successful. */ function mintWithLock(address _to, uint256 _amount, uint256 _lockedAmount, uint256 _releaseTime) external returns (bool) { require(mintAgents[msg.sender] && totalSupply_.add(_amount) <= cap); require(_amount >= _lockedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); lockedBalanceMap[_to] = lockedBalanceMap[_to] > 0 ? lockedBalanceMap[_to].add(_lockedAmount) : _lockedAmount; releaseTimeMap[_to] = releaseTimeMap[_to] > 0 ? releaseTimeMap[_to] : _releaseTime; emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); emit BalanceLocked(_to, _lockedAmount); return true; } }
Set Info _description string _website string _email string/
function setInfo(string _description, string _website, string _email) external onlyOwner returns (bool) { description = _description; website = _website; email = _email; return true; }
1,004,979
pragma solidity ^0.6.6; import "./ERC20.sol"; import "./Address.sol"; import "./BokkyPooBahsDateTimeLibrary.sol"; import "./Strings.sol"; /** * @title ACOToken * @dev The implementation of the ACO token. * The token is ERC20 compliance. */ contract ACOToken is ERC20 { using Address for address; /** * @dev Struct to store the accounts that generated tokens with a collateral deposit. */ struct TokenCollateralized { /** * @dev Current amount of tokens. */ uint256 amount; /** * @dev Index on the collateral owners array. */ uint256 index; } /** * @dev Emitted when collateral is deposited on the contract. * @param account Address of the collateral owner. * @param amount Amount of collateral deposited. */ event CollateralDeposit(address indexed account, uint256 amount); /** * @dev Emitted when collateral is withdrawn from the contract. * @param account Address of the collateral destination. * @param amount Amount of collateral withdrawn. * @param fee The fee amount charged on the withdrawal. */ event CollateralWithdraw(address indexed account, uint256 amount, uint256 fee); /** * @dev Emitted when the collateral is used on an assignment. * @param from Address of the account of the collateral owner. * @param to Address of the account that exercises tokens to get the collateral. * @param paidAmount Amount paid to the collateral owner. * @param tokenAmount Amount of tokens used to exercise. */ event Assigned(address indexed from, address indexed to, uint256 paidAmount, uint256 tokenAmount); /** * @dev The ERC20 token address for the underlying asset (0x0 for Ethereum). */ address public underlying; /** * @dev The ERC20 token address for the strike asset (0x0 for Ethereum). */ address public strikeAsset; /** * @dev Address of the fee destination charged on the exercise. */ address payable public feeDestination; /** * @dev True if the type is CALL, false for PUT. */ bool public isCall; /** * @dev The strike price for the token with the strike asset precision. */ uint256 public strikePrice; /** * @dev The UNIX time for the token expiration. */ uint256 public expiryTime; /** * @dev The total amount of collateral on the contract. */ uint256 public totalCollateral; /** * @dev The fee value. It is a percentage value (100000 is 100%). */ uint256 public acoFee; /** * @dev Symbol of the underlying asset. */ string public underlyingSymbol; /** * @dev Symbol of the strike asset. */ string public strikeAssetSymbol; /** * @dev Decimals for the underlying asset. */ uint8 public underlyingDecimals; /** * @dev Decimals for the strike asset. */ uint8 public strikeAssetDecimals; /** * @dev Underlying precision. (10 ^ underlyingDecimals) */ uint256 internal underlyingPrecision; /** * @dev Accounts that generated tokens with a collateral deposit. */ mapping(address => TokenCollateralized) internal tokenData; /** * @dev Array with all accounts with collateral deposited. */ address[] internal _collateralOwners; /** * @dev Internal data to control the reentrancy. */ bool internal _notEntered; /** * @dev Modifier to check if the token is not expired. * It is executed only while the token is not expired. */ modifier notExpired() { require(_notExpired(), "ACOToken::Expired"); _; } /** * @dev Modifier to prevents a contract from calling itself during the function execution. */ modifier nonReentrant() { require(_notEntered, "ACOToken::Reentry"); _notEntered = false; _; _notEntered = true; } /** * @dev Function to initialize the contract. * It should be called when creating the token. * It must be called only once. The `assert` is to guarantee that behavior. * @param _underlying Address of the underlying asset (0x0 for Ethereum). * @param _strikeAsset Address of the strike asset (0x0 for Ethereum). * @param _isCall True if the type is CALL, false for PUT. * @param _strikePrice The strike price with the strike asset precision. * @param _expiryTime The UNIX time for the token expiration. * @param _acoFee Value of the ACO fee. It is a percentage value (100000 is 100%). * @param _feeDestination Address of the fee destination charged on the exercise. */ function init( address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime, uint256 _acoFee, address payable _feeDestination ) public { require(underlying == address(0) && strikeAsset == address(0) && strikePrice == 0, "ACOToken::init: Already initialized"); require(_expiryTime > now, "ACOToken::init: Invalid expiry"); require(_strikePrice > 0, "ACOToken::init: Invalid strike price"); require(_underlying != _strikeAsset, "ACOToken::init: Same assets"); require(_acoFee <= 500, "ACOToken::init: Invalid ACO fee"); // Maximum is 0.5% require(_isEther(_underlying) || _underlying.isContract(), "ACOToken::init: Invalid underlying"); require(_isEther(_strikeAsset) || _strikeAsset.isContract(), "ACOToken::init: Invalid strike asset"); underlying = _underlying; strikeAsset = _strikeAsset; isCall = _isCall; strikePrice = _strikePrice; expiryTime = _expiryTime; acoFee = _acoFee; feeDestination = _feeDestination; underlyingDecimals = _getAssetDecimals(_underlying); strikeAssetDecimals = _getAssetDecimals(_strikeAsset); underlyingSymbol = _getAssetSymbol(_underlying); strikeAssetSymbol = _getAssetSymbol(_strikeAsset); underlyingPrecision = 10 ** uint256(underlyingDecimals); _notEntered = true; } /** * @dev Function to guarantee that the contract will not receive ether directly. */ receive() external payable { revert(); } /** * @dev Function to get the token name. */ function name() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token symbol, that it is equal to the name. */ function symbol() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token decimals, that it is equal to the underlying asset decimals. */ function decimals() public view override returns(uint8) { return underlyingDecimals; } /** * @dev Function to get the current amount of collateral for an account. * @param account Address of the account. * @return The current amount of collateral. */ function currentCollateral(address account) public view returns(uint256) { return getCollateralAmount(currentCollateralizedTokens(account)); } /** * @dev Function to get the current amount of unassignable collateral for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the unassignable collateral is equal to the account's collateral balance. * @param account Address of the account. * @return The respective amount of unassignable collateral. */ function unassignableCollateral(address account) public view returns(uint256) { return getCollateralAmount(unassignableTokens(account)); } /** * @dev Function to get the current amount of assignable collateral for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the assignable collateral is zero. * @param account Address of the account. * @return The respective amount of assignable collateral. */ function assignableCollateral(address account) public view returns(uint256) { return getCollateralAmount(assignableTokens(account)); } /** * @dev Function to get the current amount of collateralized tokens for an account. * @param account Address of the account. * @return The current amount of collateralized tokens. */ function currentCollateralizedTokens(address account) public view returns(uint256) { return tokenData[account].amount; } /** * @dev Function to get the current amount of unassignable tokens for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the unassignable tokens is equal to the account's collateralized tokens. * @param account Address of the account. * @return The respective amount of unassignable tokens. */ function unassignableTokens(address account) public view returns(uint256) { if (balanceOf(account) > tokenData[account].amount) { return tokenData[account].amount; } else { return balanceOf(account); } } /** * @dev Function to get the current amount of assignable tokens for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the assignable tokens is zero. * @param account Address of the account. * @return The respective amount of assignable tokens. */ function assignableTokens(address account) public view returns(uint256) { return _getAssignableAmount(account); } /** * @dev Function to get the equivalent collateral amount for a token amount. * @param tokenAmount Amount of tokens. * @return The respective amount of collateral. */ function getCollateralAmount(uint256 tokenAmount) public view returns(uint256) { if (isCall) { return tokenAmount; } else if (tokenAmount > 0) { return _getTokenStrikePriceRelation(tokenAmount); } else { return 0; } } /** * @dev Function to get the equivalent token amount for a collateral amount. * @param collateralAmount Amount of collateral. * @return The respective amount of tokens. */ function getTokenAmount(uint256 collateralAmount) public view returns(uint256) { if (isCall) { return collateralAmount; } else if (collateralAmount > 0) { return collateralAmount.mul(underlyingPrecision).div(strikePrice); } else { return 0; } } /** * @dev Function to get the data for exercise of an amount of token. * @param tokenAmount Amount of tokens. * @return The asset and the respective amount that should be sent to get the collateral. */ function getExerciseData(uint256 tokenAmount) public view returns(address, uint256) { if (isCall) { return (strikeAsset, _getTokenStrikePriceRelation(tokenAmount)); } else { return (underlying, tokenAmount); } } /** * @dev Function to get the collateral asset. * @return The address of the collateral asset. */ function collateral() public view returns(address) { if (isCall) { return underlying; } else { return strikeAsset; } } /** * @dev Function to mint tokens with Ether deposited as collateral. * NOTE: The function only works when the token is NOT expired yet. */ function mintPayable() external payable { require(_isEther(collateral()), "ACOToken::mintPayable: Invalid call"); _mintToken(msg.sender, msg.value); } /** * @dev Function to mint tokens with Ether deposited as collateral to an informed account. * However, the minted tokens are assigned to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account that will be the collateral owner. */ function mintToPayable(address account) external payable { require(_isEther(collateral()), "ACOToken::mintToPayable: Invalid call"); _mintToken(account, msg.value); } /** * @dev Function to mint tokens with ERC20 deposited as collateral. * NOTE: The function only works when the token is NOT expired yet. * @param collateralAmount Amount of collateral deposited. */ function mint(uint256 collateralAmount) external { address _collateral = collateral(); require(!_isEther(_collateral), "ACOToken::mint: Invalid call"); require(IERC20(_collateral).transferFrom(msg.sender, address(this), collateralAmount), "ACOToken::mint: Invalid transfer"); _mintToken(msg.sender, collateralAmount); } /** * @dev Function to mint tokens with ERC20 deposited as collateral to an informed account. * However, the minted tokens are assigned to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account that will be the collateral owner. * @param collateralAmount Amount of collateral deposited. */ function mintTo(address account, uint256 collateralAmount) external { address _collateral = collateral(); require(!_isEther(_collateral), "ACOToken::mintTo: Invalid call"); require(IERC20(_collateral).transferFrom(msg.sender, address(this), collateralAmount), "ACOToken::mintTo: Invalid transfer"); _mintToken(account, collateralAmount); } /** * @dev Function to burn tokens and get the collateral, not assigned, back. * NOTE: The function only works when the token is NOT expired yet. * @param tokenAmount Amount of tokens to be burned. */ function burn(uint256 tokenAmount) external { _burn(msg.sender, tokenAmount); } /** * @dev Function to burn tokens from a specific account and send the collateral to its address. * The token allowance must be respected. * The collateral is returned to the account address, not to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function burnFrom(address account, uint256 tokenAmount) external { _burn(account, tokenAmount); } /** * @dev Function to get the collateral, not assigned, back. * NOTE: The function only works when the token IS expired. */ function redeem() external { _redeem(msg.sender); } /** * @dev Function to get the collateral from a specific account sent back to its address . * The token allowance must be respected. * The collateral is returned to the account address, not to the transaction sender. * NOTE: The function only works when the token IS expired. * @param account Address of the account. */ function redeemFrom(address account) external { _redeem(account); } /** * @dev Function to exercise the tokens, paying to get the equivalent collateral. * The paid amount is sent to the collateral owners that were assigned. * NOTE: The function only works when the token is NOT expired. * @param tokenAmount Amount of tokens. */ function exercise(uint256 tokenAmount) external payable { _exercise(msg.sender, tokenAmount); } /** * @dev Function to exercise the tokens from an account, paying to get the equivalent collateral. * The token allowance must be respected. * The paid amount is sent to the collateral owners that were assigned. * The collateral is transferred to the account address, not to the transaction sender. * NOTE: The function only works when the token is NOT expired. * @param account Address of the account. * @param tokenAmount Amount of tokens. */ function exerciseFrom(address account, uint256 tokenAmount) external payable { _exercise(account, tokenAmount); } /** * @dev Function to exercise the tokens, paying to get the equivalent collateral. * The paid amount is sent to the collateral owners (on accounts list) that were assigned. * NOTE: The function only works when the token is NOT expired. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get collateral from. */ function exerciseAccounts(uint256 tokenAmount, address[] calldata accounts) external payable { _exerciseFromAccounts(msg.sender, tokenAmount, accounts); } /** * @dev Function to exercise the tokens from a specific account, paying to get the equivalent collateral sent to its address. * The token allowance must be respected. * The paid amount is sent to the collateral owners (on accounts list) that were assigned. * The collateral is transferred to the account address, not to the transaction sender. * NOTE: The function only works when the token is NOT expired. * @param account Address of the account. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the deposited collateral. */ function exerciseAccountsFrom(address account, uint256 tokenAmount, address[] calldata accounts) external payable { _exerciseFromAccounts(account, tokenAmount, accounts); } /** * @dev Function to burn the tokens after expiration. * It is an optional function to `clear` the account wallet from an expired and not functional token. * NOTE: The function only works when the token IS expired. */ function clear() external { _clear(msg.sender); } /** * @dev Function to burn the tokens from an account after expiration. * It is an optional function to `clear` the account wallet from an expired and not functional token. * The token allowance must be respected. * NOTE: The function only works when the token IS expired. * @param account Address of the account. */ function clearFrom(address account) external { _clear(account); } /** * @dev Internal function to burn the tokens from an account after expiration. * @param account Address of the account. */ function _clear(address account) internal { require(!_notExpired(), "ACOToken::_clear: Token not expired yet"); require(!_accountHasCollateral(account), "ACOToken::_clear: Must call the redeem method"); _callBurn(account, balanceOf(account)); } /** * @dev Internal function to redeem respective collateral from an account. * @param account Address of the account. * @param tokenAmount Amount of tokens. */ function _redeemCollateral(address account, uint256 tokenAmount) internal { require(_accountHasCollateral(account), "ACOToken::_redeemCollateral: No collateral available"); require(tokenAmount > 0, "ACOToken::_redeemCollateral: Invalid token amount"); TokenCollateralized storage data = tokenData[account]; data.amount = data.amount.sub(tokenAmount); _removeCollateralDataIfNecessary(account); _transferCollateral(account, getCollateralAmount(tokenAmount), false); } /** * @dev Internal function to mint tokens. * The tokens are minted for the transaction sender. * @param account Address of the account. * @param collateralAmount Amount of collateral deposited. */ function _mintToken(address account, uint256 collateralAmount) nonReentrant notExpired internal { require(collateralAmount > 0, "ACOToken::_mintToken: Invalid collateral amount"); if (!_accountHasCollateral(account)) { tokenData[account].index = _collateralOwners.length; _collateralOwners.push(account); } uint256 tokenAmount = getTokenAmount(collateralAmount); tokenData[account].amount = tokenData[account].amount.add(tokenAmount); totalCollateral = totalCollateral.add(collateralAmount); emit CollateralDeposit(account, collateralAmount); super._mintAction(msg.sender, tokenAmount); } /** * @dev Internal function to transfer tokens. * The token transfer only works when the token is NOT expired. * @param sender Source of the tokens. * @param recipient Destination address for the tokens. * @param amount Amount of tokens. */ function _transfer(address sender, address recipient, uint256 amount) notExpired internal override { super._transferAction(sender, recipient, amount); } /** * @dev Internal function to set the token permission from an account to another address. * The token approval only works when the token is NOT expired. * @param owner Address of the token owner. * @param spender Address of the spender authorized. * @param amount Amount of tokens authorized. */ function _approve(address owner, address spender, uint256 amount) notExpired internal override { super._approveAction(owner, spender, amount); } /** * @dev Internal function to transfer collateral. * When there is a fee, the calculated fee is also transferred to the destination fee address. * @param recipient Destination address for the collateral. * @param collateralAmount Amount of collateral. * @param hasFee Whether a fee should be applied to the collateral amount. */ function _transferCollateral(address recipient, uint256 collateralAmount, bool hasFee) internal { require(recipient != address(0), "ACOToken::_transferCollateral: Invalid recipient"); totalCollateral = totalCollateral.sub(collateralAmount); uint256 fee = 0; if (hasFee) { fee = collateralAmount.mul(acoFee).div(100000); collateralAmount = collateralAmount.sub(fee); } address _collateral = collateral(); if (_isEther(_collateral)) { payable(recipient).transfer(collateralAmount); if (fee > 0) { feeDestination.transfer(fee); } } else { require(IERC20(_collateral).transfer(recipient, collateralAmount), "ACOToken::_transferCollateral: Invalid transfer"); if (fee > 0) { require(IERC20(_collateral).transfer(feeDestination, fee), "ACOToken::_transferCollateral: Invalid transfer fee"); } } emit CollateralWithdraw(recipient, collateralAmount, fee); } /** * @dev Internal function to exercise the tokens from an account. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _exercise(address account, uint256 tokenAmount) nonReentrant internal { _validateAndBurn(account, tokenAmount); _exerciseOwners(account, tokenAmount); _transferCollateral(account, getCollateralAmount(tokenAmount), true); } /** * @dev Internal function to exercise the tokens from an account. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the collateral from. */ function _exerciseFromAccounts(address account, uint256 tokenAmount, address[] memory accounts) nonReentrant internal { _validateAndBurn(account, tokenAmount); _exerciseAccounts(account, tokenAmount, accounts); _transferCollateral(account, getCollateralAmount(tokenAmount), true); } /** * @dev Internal function to exercise the assignable tokens from the stored list of collateral owners. * @param exerciseAccount Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _exerciseOwners(address exerciseAccount, uint256 tokenAmount) internal { uint256 start = _collateralOwners.length - 1; for (uint256 i = start; i >= 0; --i) { if (tokenAmount == 0) { break; } tokenAmount = _exerciseAccount(_collateralOwners[i], tokenAmount, exerciseAccount); } require(tokenAmount == 0, "ACOToken::_exerciseOwners: Invalid remaining amount"); } /** * @dev Internal function to exercise the assignable tokens from an accounts list. * @param exerciseAccount Address of the account that is exercising. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the collateral from. */ function _exerciseAccounts(address exerciseAccount, uint256 tokenAmount, address[] memory accounts) internal { for (uint256 i = 0; i < accounts.length; ++i) { if (tokenAmount == 0) { break; } tokenAmount = _exerciseAccount(accounts[i], tokenAmount, exerciseAccount); } require(tokenAmount == 0, "ACOToken::_exerciseAccounts: Invalid remaining amount"); } /** * @dev Internal function to exercise the assignable tokens from an account and transfer to its address the respective payment. * @param account Address of the account. * @param tokenAmount Amount of tokens. * @param exerciseAccount Address of the account that is exercising. * @return Remaining amount of tokens. */ function _exerciseAccount(address account, uint256 tokenAmount, address exerciseAccount) internal returns(uint256) { uint256 available = _getAssignableAmount(account); if (available > 0) { TokenCollateralized storage data = tokenData[account]; uint256 valueToTransfer; if (available < tokenAmount) { valueToTransfer = available; tokenAmount = tokenAmount.sub(available); } else { valueToTransfer = tokenAmount; tokenAmount = 0; } (address exerciseAsset, uint256 amount) = getExerciseData(valueToTransfer); data.amount = data.amount.sub(valueToTransfer); _removeCollateralDataIfNecessary(account); if (_isEther(exerciseAsset)) { payable(account).transfer(amount); } else { require(IERC20(exerciseAsset).transfer(account, amount), "ACOToken::_exerciseAccount: Invalid transfer"); } emit Assigned(account, exerciseAccount, amount, valueToTransfer); } return tokenAmount; } /** * @dev Internal function to validate the exercise operation and burn the respective tokens. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _validateAndBurn(address account, uint256 tokenAmount) notExpired internal { require(tokenAmount > 0, "ACOToken::_validateAndBurn: Invalid token amount"); // Whether an account has deposited collateral it only can exercise the extra amount of unassignable tokens. if (_accountHasCollateral(account)) { require(balanceOf(account) > tokenData[account].amount, "ACOToken::_validateAndBurn: Tokens compromised"); require(tokenAmount <= balanceOf(account).sub(tokenData[account].amount), "ACOToken::_validateAndBurn: Token amount not available"); } _callBurn(account, tokenAmount); (address exerciseAsset, uint256 expectedAmount) = getExerciseData(tokenAmount); if (_isEther(exerciseAsset)) { require(msg.value == expectedAmount, "ACOToken::_validateAndBurn: Invalid ether amount"); } else { require(msg.value == 0, "ACOToken::_validateAndBurn: No ether expected"); require(IERC20(exerciseAsset).transferFrom(msg.sender, address(this), expectedAmount), "ACOToken::_validateAndBurn: Fail to receive asset"); } } /** * @dev Internal function to calculate the token strike price relation. * @param tokenAmount Amount of tokens. * @return Calculated value with strike asset precision. */ function _getTokenStrikePriceRelation(uint256 tokenAmount) internal view returns(uint256) { return tokenAmount.mul(strikePrice).div(underlyingPrecision); } /** * @dev Internal function to get the collateral sent back from an account. * Function to be called when the token IS expired. * @param account Address of the account. */ function _redeem(address account) nonReentrant internal { require(!_notExpired(), "ACOToken::_redeem: Token not expired yet"); _redeemCollateral(account, tokenData[account].amount); super._burnAction(account, balanceOf(account)); } /** * @dev Internal function to burn tokens from an account and get the collateral, not assigned, back. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function _burn(address account, uint256 tokenAmount) nonReentrant notExpired internal { _redeemCollateral(account, tokenAmount); _callBurn(account, tokenAmount); } /** * @dev Internal function to burn tokens. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function _callBurn(address account, uint256 tokenAmount) internal { if (account == msg.sender) { super._burnAction(account, tokenAmount); } else { super._burnFrom(account, tokenAmount); } } /** * @dev Internal function to get the amount of assignable token from an account. * @param account Address of the account. * @return The assignable amount of tokens. */ function _getAssignableAmount(address account) internal view returns(uint256) { if (tokenData[account].amount > balanceOf(account)) { return tokenData[account].amount.sub(balanceOf(account)); } else { return 0; } } /** * @dev Internal function to remove the token data with collateral if its total amount was assigned. * @param account Address of account. */ function _removeCollateralDataIfNecessary(address account) internal { TokenCollateralized storage data = tokenData[account]; if (!_hasCollateral(data)) { uint256 lastIndex = _collateralOwners.length - 1; if (lastIndex != data.index) { address last = _collateralOwners[lastIndex]; tokenData[last].index = data.index; _collateralOwners[data.index] = last; } _collateralOwners.pop(); delete tokenData[account]; } } /** * @dev Internal function to get if the token is not expired. * @return Whether the token is NOT expired. */ function _notExpired() internal view returns(bool) { return now <= expiryTime; } /** * @dev Internal function to get if an account has collateral deposited. * @param account Address of the account. * @return Whether the account has collateral deposited. */ function _accountHasCollateral(address account) internal view returns(bool) { return _hasCollateral(tokenData[account]); } /** * @dev Internal function to get if an account has collateral deposited. * @param data Token data from an account. * @return Whether the account has collateral deposited. */ function _hasCollateral(TokenCollateralized storage data) internal view returns(bool) { return data.amount > 0; } /** * @dev Internal function to get if the address is for Ethereum (0x0). * @param _address Address to be checked. * @return Whether the address is for Ethereum. */ function _isEther(address _address) internal pure returns(bool) { return _address == address(0); } /** * @dev Internal function to get the token name. * The token name is assembled with the token data: * ACO UNDERLYING_SYMBOL-EXPIRYTIME-STRIKE_PRICE_STRIKE_ASSET_SYMBOL-TYPE * @return The token name. */ function _name() internal view returns(string memory) { return string(abi.encodePacked( "ACO ", underlyingSymbol, "-", _getFormattedStrikePrice(), strikeAssetSymbol, "-", _getType(), "-", _getFormattedExpiryTime() )); } /** * @dev Internal function to get the token type description. * @return The token type description. */ function _getType() internal view returns(string memory) { if (isCall) { return "C"; } else { return "P"; } } /** * @dev Internal function to get the expiry time formatted. * @return The expiry time formatted. */ function _getFormattedExpiryTime() internal view returns(string memory) { (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute,) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(expiryTime); return string(abi.encodePacked( _getNumberWithTwoCaracters(day), _getMonthFormatted(month), _getYearFormatted(year), "-", _getNumberWithTwoCaracters(hour), _getNumberWithTwoCaracters(minute), "UTC" )); } /** * @dev Internal function to get the year formatted with 2 characters. * @return The year formatted. */ function _getYearFormatted(uint256 year) internal pure returns(string memory) { bytes memory yearBytes = bytes(Strings.toString(year)); bytes memory result = new bytes(2); uint256 startIndex = yearBytes.length - 2; for (uint256 i = startIndex; i < yearBytes.length; i++) { result[i - startIndex] = yearBytes[i]; } return string(result); } /** * @dev Internal function to get the month abbreviation. * @return The month abbreviation. */ function _getMonthFormatted(uint256 month) internal pure returns(string memory) { if (month == 1) { return "JAN"; } else if (month == 2) { return "FEB"; } else if (month == 3) { return "MAR"; } else if (month == 4) { return "APR"; } else if (month == 5) { return "MAY"; } else if (month == 6) { return "JUN"; } else if (month == 7) { return "JUL"; } else if (month == 8) { return "AUG"; } else if (month == 9) { return "SEP"; } else if (month == 10) { return "OCT"; } else if (month == 11) { return "NOV"; } else if (month == 12) { return "DEC"; } else { return "INVALID"; } } /** * @dev Internal function to get the number with 2 characters. * @return The 2 characters for the number. */ function _getNumberWithTwoCaracters(uint256 number) internal pure returns(string memory) { string memory _string = Strings.toString(number); if (number < 10) { return string(abi.encodePacked("0", _string)); } else { return _string; } } /** * @dev Internal function to get the strike price formatted. * @return The strike price formatted. */ function _getFormattedStrikePrice() internal view returns(string memory) { uint256 digits; uint256 count; int256 representativeAt = -1; uint256 addPointAt = 0; uint256 temp = strikePrice; uint256 number = strikePrice; while (temp != 0) { if (representativeAt == -1 && (temp % 10 != 0 || count == uint256(strikeAssetDecimals))) { representativeAt = int256(digits); number = temp; } if (representativeAt >= 0) { if (count == uint256(strikeAssetDecimals)) { addPointAt = digits; } digits++; } temp /= 10; count++; } if (count <= uint256(strikeAssetDecimals)) { digits = digits + 2 + uint256(strikeAssetDecimals) - count; addPointAt = digits - 2; } else if (addPointAt > 0) { digits++; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = number; for (uint256 i = 0; i < digits; ++i) { if (i > 0 && i == addPointAt) { buffer[index--] = byte("."); } else if (number == 0) { buffer[index--] = byte("0"); } else { if (representativeAt <= int256(i)) { buffer[index--] = byte(uint8(48 + number % 10)); } number /= 10; } } return string(buffer); } /** * @dev Internal function to the asset decimals. * @param asset Address of the asset. * @return The asset decimals. */ function _getAssetDecimals(address asset) internal view returns(uint8) { if (_isEther(asset)) { return uint8(18); } else { (bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("decimals()")); require(success, "ACOToken::_getAssetDecimals: Invalid asset decimals"); return abi.decode(returndata, (uint8)); } } /** * @dev Internal function to the asset symbol. * @param asset Address of the asset. * @return The asset symbol. */ function _getAssetSymbol(address asset) internal view returns(string memory) { if (_isEther(asset)) { return "ETH"; } else { (bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("symbol()")); require(success, "ACOToken::_getAssetSymbol: Invalid asset symbol"); return abi.decode(returndata, (string)); } } }
Function to get the data for exercise of an amount of token. tokenAmount Amount of tokens. return The asset and the respective amount that should be sent to get the collateral./
function getExerciseData(uint256 tokenAmount) public view returns(address, uint256) { if (isCall) { return (strikeAsset, _getTokenStrikePriceRelation(tokenAmount)); return (underlying, tokenAmount); } }
568,823
// File: contracts/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.0 (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: contracts/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: contracts/ITraits.sol pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/IArena.sol pragma solidity ^0.8.0; interface IArena { function addManyToArenaAndPack(address account, uint16[] calldata tokenIds) external; function randomGuardOwner(uint256 seed) external view returns (address); } // File: contracts/ISquuid.sol pragma solidity ^0.8.0; interface ISquuid { // struct to store each token's traits struct PlayerGuard { bool isPlayer; uint8 colors; uint8 head; uint8 numbers; uint8 shapes; uint8 nose; uint8 accessories; uint8 guns; uint8 feet; uint8 alphaIndex; } function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (PlayerGuard memory); } // File: contracts/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: contracts/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/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: contracts/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: contracts/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: contracts/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: contracts/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: contracts/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: contracts/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/SQUID.sol pragma solidity ^0.8.0; contract SQUID is ERC20, Ownable { // a mapping from an address to whether or not it can mint / burn mapping(address => bool) controllers; constructor() ERC20("SQUID", "SQUID") { } /** * mints $SQUID to a recipient * @param to the recipient of the $SQUID * @param amount the amount of $SQUID to mint */ function mint(address to, uint256 amount) external { require(controllers[msg.sender], "Only controllers can mint"); _mint(to, amount); } /** * burns $SQUID from a holder * @param from the holder of the $SQUID * @param amount the amount of $SQUID to burn */ function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); } /** * enables an address to mint / burn * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } } // File: contracts/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/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: contracts/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/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/Squuid.sol pragma solidity ^0.8.0; contract Squuid is ISquuid, ERC721Enumerable, Ownable, Pausable { // mint price uint256 public constant WL_MINT_PRICE = .0456 ether; uint256 public constant MINT_PRICE = .06942 ether; // max number of tokens that can be minted - 50000 in production uint256 public immutable MAX_TOKENS; // number of tokens that can be claimed for free - 20% of MAX_TOKENS uint256 public PAID_TOKENS; // number of tokens have been minted so far uint16 public minted; //For Whitelist mapping(address => uint256) public whiteList; //Keep track of data mapping(uint256 => PlayerGuard) public _idData; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => PlayerGuard) public tokenTraits; // mapping from hashed(tokenTrait) to the tokenId it's associated with // used to ensure there are no duplicates mapping(uint256 => uint256) public existingCombinations; // list of probabilities for each trait type // 0 - 9 are associated with Player, 10 - 18 are associated with Wolves uint8[][18] public rarities; // list of aliases for Walker's Alias algorithm // 0 - 9 are associated with Player, 10 - 18 are associated with Wolves uint8[][18] public aliases; // reference to the Arena for choosing random Guard thieves IArena public arena; // reference to $SQUID for burning on mint SQUID public squid; // reference to Traits ITraits public traits; /** * instantiates contract and rarity tables */ constructor(address _squid, address _traits, uint256 _maxTokens) ERC721("Squid Game", 'SGAME') { squid = SQUID(_squid); traits = ITraits(_traits); MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; // I know this looks weird but it saves users gas by making lookup O(1) // A.J. Walker's Alias Algorithm // player // colors rarities[0] = [15, 50, 200, 250, 255]; aliases[0] = [4, 4, 4, 4, 4]; // head rarities[1] = [190, 215, 240, 100, 110, 135, 160, 185, 80, 210, 235, 240, 80, 80, 100, 100, 100, 245, 250, 255]; aliases[1] = [1, 2, 4, 0, 5, 6, 7, 9, 0, 10, 11, 17, 0, 0, 0, 0, 4, 18, 19, 19]; // numbers rarities[2] = [255, 30, 60, 60, 150, 156]; aliases[2] = [0, 0, 0, 0, 0, 0]; // shapes rarities[3] = [221, 100, 181, 140, 224, 147, 84, 228, 140, 224, 250, 160, 241, 207, 173, 84, 254, 220, 196, 140, 168, 252, 140, 183, 236, 252, 224, 255]; aliases[3] = [1, 2, 5, 0, 1, 7, 1, 10, 5, 10, 11, 12, 13, 14, 16, 11, 17, 23, 13, 14, 17, 23, 23, 24, 27, 27, 27, 27]; // nose rarities[4] = [175, 100, 40, 250, 115, 100, 185, 175, 180, 255]; aliases[4] = [3, 0, 4, 6, 6, 7, 8, 8, 9, 9]; // accessories rarities[5] = [80, 225, 227, 228, 112, 240, 64, 160, 167, 217, 171, 64, 240, 126, 80, 255]; aliases[5] = [1, 2, 3, 8, 2, 8, 8, 9, 9, 10, 13, 10, 13, 15, 13, 15]; // guns rarities[6] = [255]; aliases[6] = [0]; // feet rarities[7] = [243, 189, 133, 133, 57, 95, 152, 135, 133, 57, 222, 168, 57, 57, 38, 114, 114, 114, 255]; aliases[7] = [1, 7, 0, 0, 0, 0, 0, 10, 0, 0, 11, 18, 0, 0, 0, 1, 7, 11, 18]; // alphaIndex rarities[8] = [255]; aliases[8] = [0]; // wolves // colors rarities[9] = [210, 90, 9, 9, 9, 150, 9, 255, 9]; aliases[9] = [5, 0, 0, 5, 5, 7, 5, 7, 5]; // head rarities[10] = [255]; aliases[10] = [0]; // numbers rarities[11] = [255]; aliases[11] = [0]; // shapes rarities[12] = [135, 177, 219, 141, 183, 225, 147, 189, 231, 135, 135, 135, 135, 246, 150, 150, 156, 165, 171, 180, 186, 195, 201, 210, 243, 252, 255]; aliases[12] = [1, 2, 3, 4, 5, 6, 7, 8, 13, 3, 6, 14, 15, 16, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 26, 26]; // nose rarities[13] = [255]; aliases[13] = [0]; // accessories rarities[14] = [239, 244, 249, 234, 234, 234, 234, 234, 234, 234, 130, 255, 247]; aliases[14] = [1, 2, 11, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11]; // guns rarities[15] = [75, 180, 165, 120, 60, 150, 105, 195, 45, 225, 75, 45, 195, 120, 255]; aliases[15] = [1, 9, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 14, 12, 14]; // feet rarities[16] = [255]; aliases[16] = [0]; // alphaIndex rarities[17] = [8, 160, 73, 255]; aliases[17] = [2, 3, 3, 3]; } /** EXTERNAL */ /** * mint a token - 90% Player, 10% Wolves * The first 20% are free to claim, the remaining cost $SQUID */ function mint(uint256 amount, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); } else { require(msg.value == 0); } uint256 totalSquidCost = 0; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); generate(minted, seed); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); } else { _safeMint(address(arena), minted); tokenIds[i] = minted; } totalSquidCost += mintCost(minted); } if (totalSquidCost > 0) squid.burn(_msgSender(), totalSquidCost); if (stake) arena.addManyToArenaAndPack(_msgSender(), tokenIds); } function mintWhitelist(uint256 amount, address _wallet, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 5, "Invalid mint amount"); require(whiteList[_msgSender()] >= amount, "Invalid Whitelist Amount"); require(amount * WL_MINT_PRICE == msg.value, "Invalid payment amount"); whiteList[_msgSender()] = whiteList[_msgSender()] - amount; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); _idData[minted] = generate(minted, seed); if (!stake) { _mint(_wallet, minted); } else { _mint(address(arena), minted); tokenIds[i] = minted; } } if (stake) arena.addManyToArenaAndPack(_msgSender(), tokenIds); } /** * the first 20% are paid in ETH * the next 20% are 20000 $SQUID * the next 40% are 40000 $SQUID * the final 20% are 80000 $SQUID * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId) public view returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; if (tokenId <= MAX_TOKENS * 2 / 5) return 25000 ether; // XXX if (tokenId <= MAX_TOKENS * 3 / 5) return 75000 ether; // XXX if (tokenId <= MAX_TOKENS * 4 / 5) return 125000 ether; // XXX if (tokenId <= MAX_TOKENS * 9 / 10) return 250000 ether; // XXX return 500000 ether; // XXX } function totalMint() public view returns (uint16) { return minted; } // XXX function transferFrom( address from, address to, uint256 tokenId ) public virtual override { // Hardcode the Arena's approval so that users don't have to waste gas approving if (_msgSender() != address(arena)) require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** INTERNAL */ /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed) internal returns (PlayerGuard memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; return t; } return generate(tokenId, random(seed)); } /** * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup * ensuring O(1) instead of O(n) reduces mint cost by more than 50% * probability & alias tables are generated off-chain beforehand * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[traitType].length); if (seed >> 8 < rarities[traitType][trait]) return trait; return aliases[traitType][trait]; } /** * the first 20% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked guard * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Guard thief's owner) */ function selectRecipient(uint256 seed) internal view returns (address) { if (minted <= PAID_TOKENS || ((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used address thief = arena.randomGuardOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); return thief; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of randomly selected traits */ function selectTraits(uint256 seed) internal view returns (PlayerGuard memory t) { t.isPlayer = (seed & 0xFFFF) % 10 != 0; uint8 shift = t.isPlayer ? 0 : 9; seed >>= 16; t.colors = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.head = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; t.numbers = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; t.shapes = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; t.nose = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; t.accessories = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; t.guns = selectTrait(uint16(seed & 0xFFFF), 6 + shift); seed >>= 16; t.feet = selectTrait(uint16(seed & 0xFFFF), 7 + shift); seed >>= 16; t.alphaIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift); } /** * converts a struct to a 256 bit hash to check for uniqueness * @param s the struct to pack into a hash * @return the 256 bit hash of the struct */ function structToHash(PlayerGuard memory s) internal pure returns (uint256) { return uint256(bytes32( abi.encodePacked( s.isPlayer, s.colors, s.head, s.shapes, s.accessories, s.guns, s.numbers, s.feet, s.alphaIndex ) )); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } /** READ */ function getTokenTraits(uint256 tokenId) external view override returns (PlayerGuard memory) { return tokenTraits[tokenId]; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } /** ADMIN */ function addToWhitelist(address[] memory toWhitelist) external onlyOwner { for(uint256 i = 0; i < toWhitelist.length; i++){ address idToWhitelist = toWhitelist[i]; whiteList[idToWhitelist] = 3; } } /** * called after deployment so that the contract can get random guard thieves * @param _arena the address of the Arena */ function setArena(address _arena) external onlyOwner { arena = IArena(_arena); } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * updates the number of tokens for sale */ function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } /** RENDER */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return traits.tokenURI(tokenId); } } // File: contracts/Arena.sol pragma solidity ^0.8.0; contract Arena is Ownable, IERC721Receiver, Pausable { // maximum alpha score for a Guard uint8 public constant MAX_ALPHA = 8; // struct to store a stake's token, owner, and earning values struct Stake { uint16 tokenId; uint80 value; address owner; } event TokenStaked(address owner, uint256 tokenId, uint256 value); event PlayerClaimed(uint256 tokenId, uint256 earned, bool unstaked); event GuardClaimed(uint256 tokenId, uint256 earned, bool unstaked); // reference to the Squuid NFT contract Squuid squuid; // reference to the $SQUID contract for minting $SQUID earnings SQUID squid; // maps tokenId to stake mapping(uint256 => Stake) public arena; // maps alpha to all Guard stakes with that alpha mapping(uint256 => Stake[]) public pack; // tracks location of each Guard in Pack mapping(uint256 => uint256) public packIndices; // total alpha scores staked uint256 public totalAlphaStaked = 0; // any rewards distributed when no wolves are staked uint256 public unaccountedRewards = 0; // amount of $SQUID due for each alpha point staked uint256 public squidPerAlpha = 0; // player earn 10000 $SQUID per day uint256 public constant DAILY_SQUID_RATE = 5000 ether; // player must have 2 days worth of $SQUID to unstake or else it's too cold uint256 public constant MINIMUM_TO_EXIT = 2 days; // wolves take a 20% tax on all $SQUID claimed uint256 public constant SQUID_CLAIM_TAX_PERCENTAGE = 20; // there will only ever be (roughly) 2.4 billion $SQUID earned through staking uint256 public constant MAXIMUM_GLOBAL_SQUID = 6000000000 ether; // amount of $SQUID earned so far uint256 public totalSquidEarned; // number of Player staked in the Arena uint256 public totalPlayerStaked; // the last time $SQUID was claimed uint256 public lastClaimTimestamp; // emergency rescue to allow unstaking without any checks but without $SQUID bool public rescueEnabled = false; /** * @param _squuid reference to the Squuid NFT contract * @param _squid reference to the $SQUID token */ constructor(address _squuid, address _squid) { squuid = Squuid(_squuid); squid = SQUID(_squid); } /** STAKING */ /** * adds Player and Wolves to the Arena and Pack * @param account the address of the staker * @param tokenIds the IDs of the Player and Wolves to stake */ function addManyToArenaAndPack(address account, uint16[] calldata tokenIds) external { require(account == _msgSender() || _msgSender() == address(squuid), "DONT GIVE YOUR TOKENS AWAY"); for (uint i = 0; i < tokenIds.length; i++) { if (_msgSender() != address(squuid)) { // dont do this step if its a mint + stake require(squuid.ownerOf(tokenIds[i]) == _msgSender(), "AINT YO TOKEN"); squuid.transferFrom(_msgSender(), address(this), tokenIds[i]); } else if (tokenIds[i] == 0) { continue; // there may be gaps in the array for stolen tokens } if (isPlayer(tokenIds[i])) _addPlayerToArena(account, tokenIds[i]); else _addGuardToPack(account, tokenIds[i]); } } /** * adds a single Player to the Arena * @param account the address of the staker * @param tokenId the ID of the Player to add to the Arena */ function _addPlayerToArena(address account, uint256 tokenId) internal whenNotPaused _updateEarnings { arena[tokenId] = Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(block.timestamp) }); totalPlayerStaked += 1; emit TokenStaked(account, tokenId, block.timestamp); } /** * adds a single Guard to the Pack * @param account the address of the staker * @param tokenId the ID of the Guard to add to the Pack */ function _addGuardToPack(address account, uint256 tokenId) internal { uint256 alpha = _alphaForGuard(tokenId); totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5 packIndices[tokenId] = pack[alpha].length; // Store the location of the guard in the Pack pack[alpha].push(Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(squidPerAlpha) })); // Add the guard to the Pack emit TokenStaked(account, tokenId, squidPerAlpha); } /** CLAIMING / UNSTAKING */ /** * realize $SQUID earnings and optionally unstake tokens from the Arena / Pack * to unstake a Player it will require it has 2 days worth of $SQUID unclaimed * @param tokenIds the IDs of the tokens to claim earnings from * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds */ function claimManyFromArenaAndPack(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings { uint256 owed = 0; for (uint i = 0; i < tokenIds.length; i++) { if (isPlayer(tokenIds[i])) owed += _claimPlayerFromArena(tokenIds[i], unstake); else owed += _claimGuardFromPack(tokenIds[i], unstake); } if (owed == 0) return; squid.mint(_msgSender(), owed); } /** * realize $SQUID earnings for a single Player and optionally unstake it * if not unstaking, pay a 20% tax to the staked Wolves * if unstaking, there is a 50% chance all $SQUID is stolen * @param tokenId the ID of the Player to claim earnings from * @param unstake whether or not to unstake the Player * @return owed - the amount of $SQUID earned */ function _claimPlayerFromArena(uint256 tokenId, bool unstake) internal returns (uint256 owed) { Stake memory stake = arena[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S SQUID"); if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) { owed = (block.timestamp - stake.value) * DAILY_SQUID_RATE / 1 days; } else if (stake.value > lastClaimTimestamp) { owed = 0; // $SQUID production stopped already } else { owed = (lastClaimTimestamp - stake.value) * DAILY_SQUID_RATE / 1 days; // stop earning additional $SQUID if it's all been earned } if (unstake) { if (random(tokenId) & 1 == 1) { // 50% chance of all $SQUID stolen _payGuardTax(owed); owed = 0; } delete arena[tokenId]; squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Player totalPlayerStaked -= 1; } else { _payGuardTax(owed * SQUID_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked wolves owed = owed * (100 - SQUID_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Player owner arena[tokenId] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(block.timestamp) }); // reset stake } emit PlayerClaimed(tokenId, owed, unstake); } /** * realize $SQUID earnings for a single Guard and optionally unstake it * Wolves earn $SQUID proportional to their Alpha rank * @param tokenId the ID of the Guard to claim earnings from * @param unstake whether or not to unstake the Guard * @return owed - the amount of $SQUID earned */ function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) { require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK"); uint256 alpha = _alphaForGuard(tokenId); Stake memory stake = pack[alpha][packIndices[tokenId]]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); owed = (alpha) * (squidPerAlpha - stake.value); // Calculate portion of tokens based on Alpha if (unstake) { totalAlphaStaked -= alpha; // Remove Alpha from total staked Stake memory lastStake = pack[alpha][pack[alpha].length - 1]; pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Guard to current position packIndices[lastStake.tokenId] = packIndices[tokenId]; pack[alpha].pop(); // Remove duplicate delete packIndices[tokenId]; // Delete old mapping squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Guard } else { pack[alpha][packIndices[tokenId]] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(squidPerAlpha) }); // reset stake } emit GuardClaimed(tokenId, owed, unstake); } /** * emergency unstake tokens * @param tokenIds the IDs of the tokens to claim earnings from */ function rescue(uint256[] calldata tokenIds) external { require(rescueEnabled, "RESCUE DISABLED"); uint256 tokenId; Stake memory stake; Stake memory lastStake; uint256 alpha; for (uint i = 0; i < tokenIds.length; i++) { tokenId = tokenIds[i]; if (isPlayer(tokenId)) { stake = arena[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); delete arena[tokenId]; squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Player totalPlayerStaked -= 1; emit PlayerClaimed(tokenId, 0, true); } else { alpha = _alphaForGuard(tokenId); stake = pack[alpha][packIndices[tokenId]]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); totalAlphaStaked -= alpha; // Remove Alpha from total staked lastStake = pack[alpha][pack[alpha].length - 1]; pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Guard to current position packIndices[lastStake.tokenId] = packIndices[tokenId]; pack[alpha].pop(); // Remove duplicate delete packIndices[tokenId]; // Delete old mapping squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Guard emit GuardClaimed(tokenId, 0, true); } } } /** ACCOUNTING */ /** * add $SQUID to claimable pot for the Pack * @param amount $SQUID to add to the pot */ function _payGuardTax(uint256 amount) internal { if (totalAlphaStaked == 0) { // if there's no staked wolves unaccountedRewards += amount; // keep track of $SQUID due to wolves return; } // makes sure to include any unaccounted $SQUID squidPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked; unaccountedRewards = 0; } /** * tracks $SQUID earnings to ensure it stops once 2.4 billion is eclipsed */ modifier _updateEarnings() { if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) { totalSquidEarned += (block.timestamp - lastClaimTimestamp) * totalPlayerStaked * DAILY_SQUID_RATE / 1 days; lastClaimTimestamp = block.timestamp; } _; } /** ADMIN */ /** * allows owner to enable "rescue mode" * simplifies accounting, prioritizes tokens out in emergency */ function setRescueEnabled(bool _enabled) external onlyOwner { rescueEnabled = _enabled; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } /** READ ONLY */ /** * checks if a token is a Player * @param tokenId the ID of the token to check * @return player - whether or not a token is a Player */ function isPlayer(uint256 tokenId) public view returns (bool player) { (player, , , , , , , , , ) = squuid.tokenTraits(tokenId); } /** * gets the alpha score for a Guard * @param tokenId the ID of the Guard to get the alpha score for * @return the alpha score of the Guard (5-8) */ function _alphaForGuard(uint256 tokenId) internal view returns (uint8) { ( , , , , , , , , , uint8 alphaIndex) = squuid.tokenTraits(tokenId); return MAX_ALPHA - alphaIndex; // alpha index is 0-3 } /** * chooses a random Guard thief when a newly minted token is stolen * @param seed a random value to choose a Guard from * @return the owner of the randomly selected Guard thief */ function randomGuardOwner(uint256 seed) external view returns (address) { if (totalAlphaStaked == 0) return address(0x0); uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; // choose a value from 0 to total alpha staked uint256 cumulative; seed >>= 32; // loop through each bucket of Wolves with the same alpha score for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { cumulative += pack[i].length * i; // if the value is not inside of that bucket, keep going if (bucket >= cumulative) continue; // get the address of a random Guard with that alpha score return pack[i][seed % pack[i].length].owner; } return address(0x0); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Arena directly"); return IERC721Receiver.onERC721Received.selector; } }
Converts a `uint256` to its ASCII `string` decimal representation./ Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (PlayerGuard memory); } pragma solidity ^0.8.0; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); }
98,417
// SPDX-License-Identifier: MIT pragma solidity 0.5.3; import '@openzeppelin/upgrades/contracts/Initializable.sol'; import './AuctionFactory.sol'; import './Escrow.sol'; /// @title Gloom - contracts to auction off ERC-20 tokens to the highest bidder (in ETH) /// @title Auction contract, to be used in conjunction with AuctionFactory and Escrow contracts /// @author Michael S. Mueller /// @notice This MVP is designed to handle one auction or one auction invite per address /// @notice This is a demo, do not use on mainnet /// @dev Auction inherits Initializable to ensure Auction is only initialized once /* ===== OVERVIEW ===== PHASES - Phase begins in Setup, later Seller triggers move to Commit, Reveal, Deliver, Withdraw SETUP - Seller configures (but does not transfer) ERC-20 token amount and address - Auction Factory deploys new clone of Auction (logic) contract with this configuration - Seller makes seller deposit (in ETH) into Auction - Seller specifies bidder deposit requirement (in ETH) and invites bidders to Auction COMMIT - Bidders deposit into Auction (in ETH) and commit a hash (with salt) of their bid (denominated in ETH) REVEAL - Bidders reveal their bids, Auction contract assigns winner and deploys new Escrow contract DELIVER - Seller transfers (using approve / transferFrom pattern) their ERC-20 tokens into Escrow - Winning bidder transfers winning bid (in ETH) to Escrow WITHDRAW - Seller withdraws their seller deposit (in ETH) from Auction and the winning bid proceeds (in ETH) from Escrow - Bidder withdraws their bidder deposit (in ETH) from Auction and ERC-20 tokens from Escrow */ contract Auction is Initializable { address private factory; address payable private seller; address private winner; uint256 private sellerDeposit; uint256 private bidderDeposit; // number of tokens, 18 decimal precision uint256 private tokenAmount; address private tokenContractAddress; mapping(address => uint256) private balances; Escrow private escrow; // seller controls movement from one phase to the next enum Phase { Setup, Commit, Reveal, Deliver, Withdraw } Phase private phase; // bidCommit is hashed and salted bid (hidden from other bidders) // bidHex is bid once it has been revealed struct Bidder { bool isInvited; bytes32 bidCommit; uint64 bidCommitBlock; bool isBidRevealed; bytes32 bidHex; } mapping(address => Bidder) private bidders; address[] private bidderAddresses; event LogSellerDepositReceived(address indexed seller, uint256 sellerDeposit); event LogSellerDepositWithdrawn(address indexed seller, uint256 amount); event LogBidderDepositReceived(address indexed bidder, uint256 bidderDeposit); event LogBidderDepositWithdrawn(address indexed bidder, uint256 amount); event LogBidderInvited(address indexed bidder); event LogBidCommitted(address indexed bidder, bytes32 bidHash, uint256 bidCommitBlock); event LogBidRevealed(address indexed bidder, bytes32 bidHex, bytes32 salt); event LogSetWinner(address indexed bidder, uint256 bid); event LogPhaseChangeTo(string phase); modifier onlySeller { require(msg.sender == seller, 'Sender not authorized'); _; } modifier onlyBidder { require(isInvitedBidder(msg.sender), 'Sender not authorized'); _; } modifier onlySellerOrBidder { require(msg.sender == seller || isInvitedBidder(msg.sender), 'Sender not authorized'); _; } modifier onlySellerOrWinner { require(msg.sender == seller || msg.sender == winner, 'Sender not authorized'); _; } modifier inSetup { require(phase == Phase.Setup, 'Action not authorized now'); _; } modifier inCommit { require(phase == Phase.Commit, 'Action not authorized now'); _; } modifier inReveal { require(phase == Phase.Reveal, 'Action not authorized now'); _; } modifier inDeliver { require(phase == Phase.Deliver, 'Action not authorized now'); _; } modifier inWithdraw { require(phase == Phase.Withdraw, 'Action not authorized now'); _; } /// @notice Initialize Auction in Setup phase with seller address and ERC-20 token amount and address /// @dev Initializable contracts have initialize function instead of constructor /// @dev initializer modifier prevents function from being called twice /// @param _seller address of seller triggering Auction deploy /// @param _tokenAmount uint number of tokens being auctioned, assumed 18 decimal precision /// @param _tokenContractAddress contract address of token being auction, assumed ERC-20 function initialize( address payable _seller, uint256 _tokenAmount, address _tokenContractAddress ) public initializer { factory = msg.sender; seller = _seller; tokenAmount = _tokenAmount; tokenContractAddress = _tokenContractAddress; phase = Phase.Setup; } // PHASE CONTROL ONLY SELLER /// @notice Start commit /// @dev Frontend listens for phase change logs to update UI function startCommit() external onlySeller inSetup { phase = Phase.Commit; emit LogPhaseChangeTo('Commit'); } /// @notice Start commit function startReveal() external onlySeller inCommit { phase = Phase.Reveal; emit LogPhaseChangeTo('Reveal'); } /// @notice Start delivery, determine winner, deploy new escrow contract function startDeliver() external onlySeller inReveal { phase = Phase.Deliver; setWinner(); deployEscrow(); emit LogPhaseChangeTo('Deliver'); } /// @notice Check that seller has transferred tokens and buyer has paid, then start withdraw /// @dev Could update to use minimal proxy pattern to deploy escrow with less gas function startWithdraw() external onlySeller inDeliver { require(escrow.bothOk(), 'Escrow incomplete'); require(escrow.startWithdraw(), 'Error starting escrow withdraw'); phase = Phase.Withdraw; emit LogPhaseChangeTo('Withdraw'); } // ALL PHASES PUBLIC /// @notice Get salt and hash of bid /// @dev Used in frontend in Commit phase and internally in Reveal phase /// @return bytes32 keccak hash of salted bid /// @param data 32-byte hex encoding of bid amount (left zero-padded on front end) /// @param salt 32-byte hex encoding of bidder password (from front end) function getSaltedHash(bytes32 data, bytes32 salt) public view returns (bytes32) { return keccak256(abi.encodePacked(address(this), data, salt)); } // ALL PHASES PRIVATE /// @notice Check if a bidder is invited to Auction /// @dev Used in onlySellerOrBidder modifier and in require statements as check /// @return true if invited, false if not /// @param bidderAddress bidder address to check function isInvitedBidder(address bidderAddress) private view returns (bool) { return bidders[bidderAddress].isInvited; } // ALL PHASES ONLY SELLER /// @notice Get bidders to Auction /// @dev Used in frontend to show bidders to seller /// @return array of bidder addresses function getBidders() external view onlySeller returns (address[] memory) { return bidderAddresses; } // ALL PHASES ONLY SELLER OR BIDDER /// @notice Get current Auction phase /// @dev Used in frontend to show phase to both seller and bidders /// @return string representation of current phase function getPhase() external view onlySellerOrBidder returns (string memory) { if (phase == Phase.Setup) return 'Setup'; if (phase == Phase.Commit) return 'Commit'; if (phase == Phase.Reveal) return 'Reveal'; if (phase == Phase.Deliver) return 'Deliver'; if (phase == Phase.Withdraw) return 'Withdraw'; } /// @notice Get details of token being auctioned at any time /// @dev Used in frontend to show asset details to both seller and bidders /// @return number and contract address of tokens being auctioned function getAsset() external view onlySellerOrBidder returns (uint256, address) { return (tokenAmount, tokenContractAddress); } /// @notice Get seller deposit amount at any time /// @dev Used in frontend to show seller deposit amount to both seller and bidders /// @return amount of ETH seller has deposited function getSellerDeposit() external view onlySellerOrBidder returns (uint256) { return sellerDeposit; } /// @notice Get bidder deposit requirement amount at any time /// @dev Used in frontend to show bidder deposit requirement to both seller and bidders /// @return amount of ETH bidders are required to deposit in order to commit bid function getBidderDeposit() external view onlySellerOrBidder returns (uint256) { return bidderDeposit; } /// @notice Get winning bidder address and bid at any time, will have results from Deliver phase /// @dev Used in frontend to show winning bidder and bid to both seller and bidders /// @return winner address and bid (in ETH) function getWinner() external view onlySellerOrBidder returns (address, uint256) { uint256 winningBid = uint256(bidders[winner].bidHex); return (winner, winningBid); } // ALL PHASES ONLY SELLER OR WINNER /// @notice Get address of deployed Escrow contract at any time /// @dev Used in frontend to obtain escrow contract address for seller and winner /// @return address of deployed Escrow contract function getEscrow() external view onlySellerOrWinner returns (Escrow) { return escrow; } // SETUP PHASE ONLY SELLER /// @notice Receives seller deposit (in ETH) in Setup phase /// @dev Frontend handles seller transfer /// @dev Seller can submit (and change) sellerDeposit multiple times, which should be controlled for (e.g. multiple deposits) function receiveSellerDeposit() external payable onlySeller inSetup { sellerDeposit = msg.value; balances[msg.sender] += msg.value; emit LogSellerDepositReceived(msg.sender, msg.value); } /// @notice Registers bidder at Auction Factory in Setup phase /// @dev We need Auction Factory to know who the bidders are to identify them in front end /// @param bidderAddress bidder address to register at Auction Factory function registerBidderAtFactory(address bidderAddress) private { AuctionFactory auctionFactory = AuctionFactory(factory); auctionFactory.registerBidder(bidderAddress); } /// @notice Invites individual bidder in Setup phase /// @param bidderAddress bidder address to invite function inviteBidder(address bidderAddress) private { require(!isInvitedBidder(bidderAddress), 'Bidder already invited'); bidders[bidderAddress].isInvited = true; bidderAddresses.push(bidderAddress); registerBidderAtFactory(bidderAddress); emit LogBidderInvited(bidderAddress); } /// @notice Seller establishes bidder deposit requirement and invite bidders in Setup phase /// @dev Seller can call this multiple times, should establish logic to prevent or to handle editing bidder setup /// @param _bidderDeposit bidder deposit requirement amount (seller configures on front end when inviting bidders) /// @param _bidderAddresses array of bidders to invite (seller configures on front end) function setupBidders(uint256 _bidderDeposit, address[] calldata _bidderAddresses) external onlySeller inSetup { bidderDeposit = _bidderDeposit; for (uint256 i = 0; i < _bidderAddresses.length; i++) { inviteBidder(_bidderAddresses[i]); } } // COMMIT PHASE ONLY BIDDER /// @notice Receives bidder deposit (in ETH) in Commit phase /// @dev Frontend handles bidder transfer function receiveBidderDeposit() private { require(msg.value == bidderDeposit, 'Deposit is not required amount'); balances[msg.sender] += msg.value; emit LogBidderDepositReceived(msg.sender, msg.value); } /// @notice Commit obfuscated bid in Commit phase /// @dev Block.number is not currently used but could compare to block.number at reveal to ensure minimal block difference /// @param dataHash 32-byte keccak256 hash of bid commit amount and salt (return value of getSaltedHash above called from front end) function commitBid(bytes32 dataHash) private { bidders[msg.sender].bidCommit = dataHash; bidders[msg.sender].bidCommitBlock = uint64(block.number); bidders[msg.sender].isBidRevealed = false; emit LogBidCommitted(msg.sender, bidders[msg.sender].bidCommit, bidders[msg.sender].bidCommitBlock); } /// @notice Triggers bidder deposit (in ETH) and commits obfuscated bid in Commit phase /// @dev Bidder can submit (and change) bid multiple times, which should be controlled for (e.g. multiple deposits) /// @param dataHash 32-byte keccak256 hash of bid commit amount and salt (return value of getSaltedHash above called from front end) function submitBid(bytes32 dataHash) external payable onlyBidder inCommit { receiveBidderDeposit(); commitBid(dataHash); } // REVEAL PHASE ONLY BIDDER /// @notice Checks revealed bid in Reveal phase to ensure it matches commit, if so stores revealed bid /// @param bidHex 32-byte hex encoding of bid amount (left zero-padded on front end) /// @param salt 32-byte hex encoding of bidder password (from front end) function revealBid(bytes32 bidHex, bytes32 salt) external onlyBidder inReveal { require(bidders[msg.sender].isBidRevealed == false, 'Bid already revealed'); require(getSaltedHash(bidHex, salt) == bidders[msg.sender].bidCommit, 'Revealed hash does not match'); bidders[msg.sender].isBidRevealed = true; bidders[msg.sender].bidHex = bidHex; emit LogBidRevealed(msg.sender, bidHex, salt); } // DELIVER PHASE INTERNAL TRIGGERED BY PHASE CONTROL ONLY SELLER /// @notice Cycles through bids and determines winner at start of Deliver phase /// @dev Solidity casts bid from bytes32 to uint256 here, consider using OpenZeppelin SafeCast.sol function setWinner() internal { address _winner = bidderAddresses[0]; for (uint256 i = 1; i < bidderAddresses.length; i++) { address current = bidderAddresses[i]; if (bidders[current].bidHex > bidders[_winner].bidHex) { _winner = current; } } winner = _winner; uint256 winningBid = uint256(bidders[winner].bidHex); emit LogSetWinner(winner, winningBid); } /// @notice Deploys new escrow contract at start of Deliver phase /// @dev Could update to use minimal proxy pattern to deploy Escrow with less gas function deployEscrow() internal { escrow = new Escrow(); bytes32 winningBid = bidders[winner].bidHex; escrow.initialize(seller, winner, tokenAmount, tokenContractAddress, winningBid); } // WITHDRAW PHASE ONLY SELLER OR BIDDER /// @notice Seller withdraws deposit (in ETH) in withdraw phase /// @dev Performs state updates before external call to prevent reentrancy attack /// @dev To test / control for: effects of multiple and changing seller deposits function withdrawSellerDeposit() external payable onlySeller inWithdraw { require(balances[msg.sender] >= sellerDeposit, 'Insufficient balance'); balances[msg.sender] -= sellerDeposit; (bool success, ) = msg.sender.call.value(sellerDeposit)(''); require(success, 'Transfer failed'); emit LogSellerDepositWithdrawn(msg.sender, sellerDeposit); } /// @notice Bidder withdraws deposit (in ETH) in withdraw phase /// @dev Performs state updates before external call to prevent reentrancy attack /// @dev To test / control for: effects of multiple and changing deposits by same bidder function withdrawBidderDeposit() external payable onlyBidder inWithdraw { require(balances[msg.sender] >= bidderDeposit, 'Insufficient balance'); balances[msg.sender] -= bidderDeposit; (bool success, ) = msg.sender.call.value(bidderDeposit)(''); require(success, 'Transfer failed'); emit LogBidderDepositWithdrawn(msg.sender, bidderDeposit); } }
Get bidders to Auction Used in frontend to show bidders to seller return array of bidder addresses
function getBidders() external view onlySeller returns (address[] memory) { return bidderAddresses; }
1,775,606
// SPDX-License-Identifier: WTFPL pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./tokens/IFAVault.sol"; import "./calculators/ICalculator.sol"; import "./components/IFAPool.sol"; import "./components/IFABank.sol"; import "./strategies/CreateIFA.sol"; // Query data related to ifa. // This contract is owned by Timelock. contract CalculatorDataBoard is Ownable { IFAMaster public ifaMaster; constructor(IFAMaster _ifaMaster) public { ifaMaster = _ifaMaster; } function getCalculatorStat(uint256 _poolId) public view returns (uint256, uint256, uint256) { ICalculator calculator; (,, calculator) = IFABank(ifaMaster.bank()).poolMap(_poolId); uint256 rate = calculator.rate(); uint256 minimumLTV = calculator.minimumLTV(); uint256 maximumLTV = calculator.maximumLTV(); return (rate, minimumLTV, maximumLTV); } function getPendingReward(uint256 _poolId, uint256 _index) public view returns (uint256) { IFAVault vault; (, vault,) = IFAPool(ifaMaster.pool()).poolMap(_poolId); return vault.getPendingReward(msg.sender, _index); } // return user loan record size. function getUserLoanLength(address _who) public view returns (uint256) { return IFABank(ifaMaster.bank()).getLoanListLength(_who); } // return loan info (loanId,principal, interest, lockedAmount, time, rate, maximumLTV) function getUserLoan(address _who, uint256 _index) public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { uint256 poolId; uint256 loanId; (poolId, loanId) = IFABank(ifaMaster.bank()).loanList(_who, _index); ICalculator calculator; (,, calculator) = IFABank(ifaMaster.bank()).poolMap(poolId); uint256 lockedAmount = calculator.getLoanLockedAmount(loanId); uint256 principal = calculator.getLoanPrincipal(loanId); uint256 interest = calculator.getLoanInterest(loanId); uint256 time = calculator.getLoanTime(loanId); uint256 rate = calculator.getLoanRate(loanId); uint256 maximumLTV = calculator.getLoanMaximumLTV(loanId); return (loanId, principal, interest, lockedAmount, time, rate, maximumLTV); } }
return loan info (loanId,principal, interest, lockedAmount, time, rate, maximumLTV)
function getUserLoan(address _who, uint256 _index) public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { uint256 poolId; uint256 loanId; (poolId, loanId) = IFABank(ifaMaster.bank()).loanList(_who, _index); ICalculator calculator; (,, calculator) = IFABank(ifaMaster.bank()).poolMap(poolId); uint256 lockedAmount = calculator.getLoanLockedAmount(loanId); uint256 principal = calculator.getLoanPrincipal(loanId); uint256 interest = calculator.getLoanInterest(loanId); uint256 time = calculator.getLoanTime(loanId); uint256 rate = calculator.getLoanRate(loanId); uint256 maximumLTV = calculator.getLoanMaximumLTV(loanId); return (loanId, principal, interest, lockedAmount, time, rate, maximumLTV); }
6,400,247
./full_match/1/0x2Bbbdf97295F73175b12CC087cF446765931e1C3/sources/@layerzerolabs/solidity-examples/contracts/token/oft/v2/OFTCoreV2.sol
public functions/ send call
function callOnOFTReceived( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes32 _from, address _to, uint _amount, bytes calldata _payload, uint _gasForCall ) public virtual { require(_msgSender() == address(this), "OFTCore: caller must be OFTCore"); _amount = _transferFrom(address(this), _to, _amount); emit ReceiveFromChain(_srcChainId, _to, _amount); }
8,317,421
./full_match/43113/0x538dA80010c6B27E3079575035d8F9BE41A47597/sources/contracts/tREASURY.sol
/require( isReserveToken[ _token ], "Not accepted" ); Only reserves can be used for redemptionsrequire( isReserveSpender[ msg.sender ] == true, "Not approved" );
function withdraw( uint _amount, address _token ) public virtual onlyManager { uint value = valueOf( _token, _amount ); IOHMERC20( OHM ).burnFrom( msg.sender, value ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20( _token ).safeTransfer( msg.sender, _amount ); emit Withdrawal( _token, _amount, value ); } @param _amount uint @param _token address
13,165,060
./full_match/43114/0xE487a3780D56F2ECD142201907dF16350bb09946/sources/DssProxyActions.sol
Moves the amount from the CDP urn to proxy's address Exits WETH amount to proxy address as a token Converts WETH to ETH Sends ETH back to the user's wallet
function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { flux(manager, cdp, address(this), wad); GemJoin(ethJoin).exit(address(this), wad); WETH9_(payable(address(GemJoin(ethJoin).gem()))).withdraw(wad); msg.sender.transfer(wad); }
4,579,851
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import './interface/ComptrollerInterface.sol'; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; error MarketNotList(); error InsufficientLiquidity(); error PriceError(); error NotLiquidatePosition(); error AdminOnly(); error ProtocolPaused(); contract Comptroller is ComptrollerInterface { event NewAurumController(AurumControllerInterface oldAurumController, AurumControllerInterface newAurumController); event NewComptrollerCalculation(ComptrollerCalculation oldComptrollerCalculation, ComptrollerCalculation newComptrollerCalculation); event NewTreasuryGuardian(address oldTreasuryGuardian, address newTreasuryGuardian); event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress); event NewTreasuryPercent(uint oldTreasuryPercent, uint newTreasuryPercent); event ARMGranted(address recipient, uint amount); event NewPendingAdmin (address oldPendingAdmin,address newPendingAdmin); event NewAdminConfirm (address oldAdmin, address newAdmin); event DistributedGOLDVault(uint amount); // Variables declaration // address public admin; address public pendingAdmin; ComptrollerStorage public compStorage; ComptrollerCalculation public compCalculate; AurumControllerInterface public aurumController; address public treasuryGuardian; //Guardian of the treasury address public treasuryAddress; //Wallet Address uint256 public treasuryPercent; //Fee in percent of accrued interest with decimal 18 , This value is used in liquidate function of each LendToken bool internal locked; // reentrancy Guardian constructor(ComptrollerStorage compStorage_) { admin = msg.sender; compStorage = compStorage_; //Bind storage to the comptroller contract. locked = false; // reentrancyGuard Variable } // // Get parameters function // function isComptroller() external pure returns(bool){ // double check the contract return true; } function isProtocolPaused() external view returns(bool) { return compStorage.protocolPaused(); } function getMintedGOLDs(address minter) external view returns(uint) { // The ledger of user's AURUM minted is stored in ComptrollerStorage contract. return compStorage.getMintedGOLDs(minter); } function getComptrollerOracleAddress() external view returns(address) { return address(compStorage.oracle()); } function getAssetsIn(address account) external view returns (LendTokenInterface[] memory) { return compStorage.getAssetsIn(account); } function getGoldMintRate() external view returns (uint) { return compStorage.goldMintRate(); } function addToMarket(LendTokenInterface lendToken) external{ compStorage.addToMarket(lendToken, msg.sender); } function exitMarket(address lendTokenAddress) external{ LendTokenInterface lendToken = LendTokenInterface(lendTokenAddress); /* Get sender tokensHeld and borrowBalance from the lendToken */ (uint tokensHeld, uint borrowBalance, ) = lendToken.getAccountSnapshot(msg.sender); /* Fail if the sender has a borrow balance */ if (borrowBalance != 0) { revert(); } // if All of user's tokensHeld allowed to redeem, then it's allowed to UNCOLLATERALIZED. this.redeemAllowed(lendTokenAddress, msg.sender, tokensHeld); // Execute change of state variable in ComptrollerStorage. compStorage.exitMarket(lendTokenAddress, msg.sender); } /*** Policy Hooks ***/ // Check if the account be allowed to mint tokens // This check only // 1. Protocol not pause // 2. The lendToken is listed // Then update the reward SupplyIndex function mintAllowed(address lendToken, address minter) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.getMintGuardianPaused(lendToken), "mint is paused"); if (!compStorage.isMarketListed(lendToken)) { revert MarketNotList(); } // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, minter); } // // Redeem allowed will check // 1. is the asset is list in market ? // 2. had the redeemer entered the market ? // 3. predict the value after redeem and check. if the loan is over (shortfall) then user can't redeem. // 4. if all pass then redeem is allowed. // function redeemAllowed(address lendToken, address redeemer, uint redeemTokens) external{ // bool protocolPaused = compStorage.protocolPaused(); // if(protocolPaused){ revert ProtocolPaused(); } if (!compStorage.isMarketListed(lendToken)) { //Can't redeem the asset which not list in market. revert MarketNotList(); } /* If the redeemer is not 'in' the market (this token not in collateral calculation), then we can bypass the liquidity check */ if (!compStorage.checkMembership(redeemer, LendTokenInterface(lendToken)) ) { return ; } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (, uint shortfall) = compCalculate.getHypotheticalAccountLiquidity(redeemer, lendToken, redeemTokens, 0); if (shortfall != 0) { revert InsufficientLiquidity(); } compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, redeemer); } // // Borrow allowed will check // 1. is the asset listed in market ? // 2. if borrower not yet listed in market.accountMembership --> add the borrower in // 3. Check the price of oracle (is it still in normal status ?) // 4.1 Check borrow cap (if borrowing amount more than cap it's not allowed) // 4.2 Predict the loan after borrow. if the loan is over (shortfall) then user can't borrow. // 5. if all pass, return no ERROR. // function borrowAllowed(address lendToken, address borrower, uint borrowAmount) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.getBorrowGuardianPaused(lendToken)); if (!compStorage.isMarketListed(lendToken)) { revert MarketNotList(); } if (!compStorage.checkMembership(borrower, LendTokenInterface(lendToken)) ) { // previously we check that 'lendToken' is one of the verify LendToken, so make sure that this function is called by the verified lendToken not ATTACKER wallet. require(msg.sender == lendToken, "sender must be lendToken"); // the borrow token automatically addToMarket. compStorage.addToMarket(LendTokenInterface(lendToken), borrower); } if (compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendToken)) == 0) { revert PriceError(); } uint borrowCap = compStorage.getBorrowCaps(lendToken); // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = LendTokenInterface(lendToken).totalBorrows(); uint nextTotalBorrows = totalBorrows + borrowAmount; require(nextTotalBorrows < borrowCap, "borrow cap reached"); // if total borrow + pending borrow reach borrow cap --> error } uint shortfall; (, shortfall) = compCalculate.getHypotheticalAccountLiquidity(borrower, lendToken, 0, borrowAmount); if (shortfall != 0) { revert InsufficientLiquidity(); } // Keep the flywheel moving uint borrowIndex = LendTokenInterface(lendToken).borrowIndex(); compStorage.updateARMBorrowIndex(lendToken, borrowIndex); compStorage.distributeBorrowerARM(lendToken, borrower, borrowIndex); } // // repay is mostly allowed. except the market is closed. // function repayBorrowAllowed(address lendToken, address borrower) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } if (!compStorage.isMarketListed(lendToken) ) { revert MarketNotList(); } // Keep the flywheel moving uint borrowIndex = LendTokenInterface(lendToken).borrowIndex(); compStorage.updateARMBorrowIndex(lendToken, borrowIndex); compStorage.distributeBorrowerARM(lendToken, borrower, borrowIndex); } // // Liquidate allowed will check // 1. is market listed ? // 2. is the borrower currently shortfall ? (run predict function without borrowing or redeeming) // 3. calculate the max repayAmount by formula borrowBalance * closeFactorMantissa (%) // 4. check if repayAmount > maximumClose then revert. // 5. if all pass => allowed // function liquidateBorrowAllowed(address lendTokenBorrowed, address lendTokenCollateral, address borrower, uint repayAmount) external view{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } if (!(compStorage.isMarketListed(lendTokenBorrowed) || address(lendTokenBorrowed) == address(aurumController)) || !compStorage.isMarketListed(lendTokenCollateral) ) { revert MarketNotList(); } /* The borrower must have shortfall in order to be liquidatable */ (, uint shortfall) = compCalculate.getHypotheticalAccountLiquidity(borrower, address(0), 0, 0); if (shortfall == 0) { revert NotLiquidatePosition(); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance; if (address(lendTokenBorrowed) != address(aurumController)) { //aurumController is GOLD aurum minting control borrowBalance = LendTokenInterface(lendTokenBorrowed).borrowBalanceStored(borrower); } else { borrowBalance = compStorage.getMintedGOLDs(borrower); } uint maxClose = compStorage.closeFactorMantissa() * borrowBalance / 1e18; if (repayAmount > maxClose) { revert InsufficientLiquidity(); } } // // SeizeAllowed will check // 1. check the lendToken Borrow and Collateral both are listed in market (aurumController also can be lendTokenBorrowed address) // // 2. lendToken Borrow and Collateral are in the same market (Comptroller) // 3. if all pass => (allowed). // // lendTokenBorrowed is the called LendToken or aurumController. function seizeAllowed(address lendTokenCollateral, address lendTokenBorrowed, address liquidator, address borrower) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.seizeGuardianPaused()); // We've added aurumController as a borrowed token list check for seize if (!compStorage.isMarketListed(lendTokenCollateral) || !(compStorage.isMarketListed(lendTokenBorrowed) || address(lendTokenBorrowed) == address(aurumController))) { revert MarketNotList(); } // Check Borrow and Collateral in the same market (comptroller). if (LendTokenInterface(lendTokenCollateral).comptroller() != LendTokenInterface(lendTokenBorrowed).comptroller()) { revert(); } // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendTokenCollateral); compStorage.distributeSupplierARM(lendTokenCollateral, borrower); compStorage.distributeSupplierARM(lendTokenCollateral, liquidator); } // // TransferAllowed is simply automatic allowed when redeeming is allowed (redeeming then transfer) // So just check if this token is redeemable ? // function transferAllowed(address lendToken, address src, address dst, uint transferTokens) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.transferGuardianPaused()); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens this.redeemAllowed(lendToken, src, transferTokens); // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, src); compStorage.distributeSupplierARM(lendToken, dst); } /*** Liquidity/Liquidation Calculations ***/ // Calculating function in ComptrollerCalculation contract function liquidateCalculateSeizeTokens(address lendTokenBorrowed, address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { return compCalculate.liquidateCalculateSeizeTokens(lendTokenBorrowed, lendTokenCollateral, actualRepayAmount); } function liquidateGOLDCalculateSeizeTokens(address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { return compCalculate.liquidateGOLDCalculateSeizeTokens(lendTokenCollateral, actualRepayAmount); } // /*** Admin Functions ***/ // function _setPendingAdmin(address newPendingAdmin) external { if(msg.sender != admin) { revert AdminOnly();} address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin (oldPendingAdmin, newPendingAdmin); } function _confirmNewAdmin() external { if(msg.sender != admin) { revert AdminOnly();} address oldAdmin = admin; address newAdmin = pendingAdmin; require(newAdmin != address(0), "Set pending admin first"); admin = pendingAdmin; pendingAdmin = address(0); //Also set ComptrollerStorage's new admin to the same as comptroller. compStorage._setNewStorageAdmin(newAdmin); emit NewAdminConfirm (oldAdmin, newAdmin); } function _setAurumController(AurumControllerInterface aurumController_) external{ if(msg.sender != admin) { revert AdminOnly();} AurumControllerInterface oldRate = aurumController; aurumController = aurumController_; emit NewAurumController(oldRate, aurumController_); } function _setTreasuryData(address newTreasuryGuardian, address newTreasuryAddress, uint newTreasuryPercent) external{ if (!(msg.sender == admin || msg.sender == treasuryGuardian)) { revert AdminOnly(); } require(newTreasuryPercent < 1e18, "treasury percent cap overflow"); address oldTreasuryGuardian = treasuryGuardian; address oldTreasuryAddress = treasuryAddress; uint oldTreasuryPercent = treasuryPercent; treasuryGuardian = newTreasuryGuardian; treasuryAddress = newTreasuryAddress; treasuryPercent = newTreasuryPercent; emit NewTreasuryGuardian(oldTreasuryGuardian, newTreasuryGuardian); emit NewTreasuryAddress(oldTreasuryAddress, newTreasuryAddress); emit NewTreasuryPercent(oldTreasuryPercent, newTreasuryPercent); } function _setComptrollerCalculation (ComptrollerCalculation newCompCalculate) external { if(msg.sender != admin) { revert AdminOnly();} ComptrollerCalculation oldCompCalculate = compCalculate; compCalculate = newCompCalculate; emit NewComptrollerCalculation (oldCompCalculate, newCompCalculate); } // Claim ARM function function claimARMAllMarket(address holder) external { return claimARM(holder, compStorage.getAllMarkets()); } function claimARM(address holder, LendTokenInterface[] memory lendTokens) public { this.claimARM(holder, lendTokens, true, true); } function claimARM(address holder, LendTokenInterface[] memory lendTokens, bool borrowers, bool suppliers) external { require (locked == false,"No reentrance"); //Reentrancy guard locked = true; for (uint i = 0; i < lendTokens.length; i++) { LendTokenInterface lendToken = lendTokens[i]; require(compStorage.isMarketListed(address(lendToken))); uint armAccrued; if (borrowers) { // Update the borrow index of each lendToken in the storage of comptroller // Borrow index is the multiplier which gradually increase by the amount of interest (borrowRate) uint borrowIndex = lendToken.borrowIndex(); compStorage.updateARMBorrowIndex(address(lendToken), borrowIndex); compStorage.distributeBorrowerARM(address(lendToken), holder, borrowIndex); armAccrued = compStorage.getArmAccrued(holder); compStorage.grantARM(holder, armAccrued); //reward the user then set user's armAccrued to 0; } if (suppliers) { compStorage.updateARMSupplyIndex(address(lendToken)); compStorage.distributeSupplierARM(address(lendToken), holder); armAccrued = compStorage.getArmAccrued(holder); compStorage.grantARM(holder, armAccrued); } } locked = false; } /*** Aurum Distribution Admin ***/ function _setAurumSpeed(LendTokenInterface lendToken, uint aurumSpeed) external { if(msg.sender != admin) { revert AdminOnly();} uint borrowIndex = lendToken.borrowIndex(); compStorage.updateARMSupplyIndex(address(lendToken)); compStorage.updateARMBorrowIndex(address(lendToken), borrowIndex); uint currentAurumSpeed = compStorage.getAurumSpeeds(address(lendToken)); if (currentAurumSpeed == 0 && aurumSpeed != 0) { // Initialize compStorage.addARMdistributionMarket(lendToken); } if (currentAurumSpeed != aurumSpeed) { compStorage.setAurumSpeed(lendToken, aurumSpeed); } } //Set the amount of GOLD had minted, this should be called by aurumController contract function setMintedGOLDOf(address owner, uint amount) external { require(msg.sender == address(aurumController)); bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } bool mintGOLDGuardianPaused = compStorage.mintGOLDGuardianPaused(); require(!mintGOLDGuardianPaused, "Mint GOLD is paused"); compStorage.setMintedGOLD(owner,amount); } } contract ComptrollerCalculation { // no admin setting in this contract, ComptrollerStorage compStorage; constructor(ComptrollerStorage _compStorage) { compStorage = _compStorage; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `lendTokenBalance` is the number of lendTokens 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 lendTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; uint goldOraclePriceMantissa; uint tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return 1. account liquidity in excess of collateral requirements, * 2. account shortfall below collateral requirements) */ function getAccountLiquidity(address account) external view returns (uint, uint) { (uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(address(0)), 0, 0); return (liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param lendTokenModify 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) */ // // This function will simulate the user's account after interact with a specify LendToken when increasing loan (Borrowing and Redeeming) // How much liquidity left OR How much shortage will return. // 1. get each aset that the account participate in the market // 2. Sum up Collateral value (+), Borrow (-), Effect[BorrowMore, RedeemMore, Gold Minted] (-) // 3. Return liquidity if positive, Return shortage if negative. // function getHypotheticalAccountLiquidity(address account, address lendTokenModify, uint redeemTokens, uint borrowAmount) external view returns (uint, uint) { (uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(lendTokenModify), redeemTokens, borrowAmount); return (liquidity, shortfall); } function isShortage(address account) external view returns(bool){ // This function will be called by the front-end Liquidator query. the LendTokenInterface(msg.sender) is the dummy parameter, it's not use for calculation. (,uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(msg.sender), 0, 0); if(shortfall > 0){ return true; } else { return false; } } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param lendTokenModify 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 lendToken using stored data, * without calculating accumulated interest. * @return (hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, LendTokenInterface lendTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results vars.goldOraclePriceMantissa = compStorage.oracle().getGoldPrice(); if (vars.goldOraclePriceMantissa == 0) { revert ("Gold price error"); } // For each asset the account is in LendTokenInterface[] memory assets = compStorage.getAssetsIn(account); for (uint i = 0; i < assets.length; i++) { LendTokenInterface asset = assets[i]; // Read the balances and exchange rate from the lendToken // As noted above, if no one interact with the LendToken, the 'accrueInterest' function not called for long time. // May lead to outdated exchangeRate. (vars.lendTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); uint collateralFactorMantissa = compStorage.getMarketCollateralFactorMantissa(address(asset)); // Get the normalized price of the asset vars.oraclePriceMantissa = compStorage.oracle().getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { revert("Oracle error"); } // Pre-compute a conversion factor // Unit compensate = 1e18 :: (e18*e18 / e18) *e18 / e18 vars.tokensToDenom = (collateralFactorMantissa * vars.exchangeRateMantissa / 1e18) * vars.oraclePriceMantissa / 1e18; // sumCollateral += tokensToDenom * lendTokenBalance // Unit compensate = 1e18 :: (e18*e18 / e18) vars.sumCollateral += (vars.tokensToDenom * vars.lendTokenBalance / 1e18); // sumBorrowPlusEffects += oraclePrice * borrowBalance // Unit compensate = 1e18 :: (e18*e18 /e18) vars.sumBorrowPlusEffects += (vars.oraclePriceMantissa * vars.borrowBalance / 1e18); // Calculate effects of interacting with lendTokenModify if (asset == lendTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens // Unit compensate = 1e18 vars.sumBorrowPlusEffects += (vars.tokensToDenom * redeemTokens / 1e18); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount // Unit compensate = 1e18 vars.sumBorrowPlusEffects += (vars.oraclePriceMantissa * borrowAmount / 1e18); } } //---------------------- This formula modified from VAI minted of venus contract to => GoldMinted * GoldOraclePrice------------------ // sumBorrowPlusEffects += GoldMinted * GoldOraclePrice vars.sumBorrowPlusEffects += (vars.goldOraclePriceMantissa * compStorage.getMintedGOLDs(account) / 1e18); // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { //Return remaining liquidity. return (vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { //Return shortfall amount. return (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 lendToken.liquidateBorrowFresh) * @param lendTokenBorrowed The address of the borrowed lendToken * @param lendTokenCollateral The address of the collateral lendToken * @param actualRepayAmount The amount of underlying token that liquidator had paid. * @return number of lendTokenCollateral tokens to be seized in a liquidation */ function liquidateCalculateSeizeTokens(address lendTokenBorrowed, address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenBorrowed)); uint priceCollateralMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { revert ("Oracle price error"); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = LendTokenInterface(lendTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; // Numerator is 1e54 // *1e18 for calculating ratio into 1e18 uint numerator = compStorage.liquidationIncentiveMantissa() * priceBorrowedMantissa * 1e18; // Denominator is 1e36 uint denominator = priceCollateralMantissa * exchangeRateMantissa; // Ratio is 1e18 uint ratioMantissa = numerator / denominator; seizeTokens = ratioMantissa * actualRepayAmount / 1e18; return seizeTokens; } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation. Called by AurumController contract * @param lendTokenCollateral The address of the collateral lendToken * @param actualRepayAmount The amount of AURUM that liquidator had paid. * @return number of lendTokenCollateral tokens to be seized in a liquidation */ function liquidateGOLDCalculateSeizeTokens(address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { /* Read oracle prices for borrowed and collateral markets */ //The different to the previous function is only Borrow price oracle is GOLD price uint priceBorrowedMantissa = compStorage.oracle().getGoldPrice(); // get the current gold price feeding from oracle uint priceCollateralMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenCollateral)); if (priceCollateralMantissa == 0 || priceBorrowedMantissa == 0) { revert ("Oracle price error"); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = LendTokenInterface(lendTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; // Numerator is 1e54 // *1e18 for calculating ratio into 1e18 uint numerator = compStorage.liquidationIncentiveMantissa() * priceBorrowedMantissa * 1e18; // Denominator is 1e36 uint denominator = priceCollateralMantissa * exchangeRateMantissa; // Ratio is 1e18 uint ratioMantissa = numerator / denominator; seizeTokens = ratioMantissa * actualRepayAmount / 1e18; return seizeTokens; } struct ARMAccrued { uint supplierIndex; uint borrowerIndex; uint supplyStateIndex; uint borrowStateIndex; uint supplierTokens; uint borrowerAmount; uint aurumSpeed; } // // Front-end function // core function is getUpdateARMAccrued // input of timestamp in Javascript should be divided by 1000 // function getUpdateARMSupplyIndex(address lendToken, uint currentTime) internal view returns(uint) { (uint supplyStateIndex, uint supplyStateTimestamp) = compStorage.armSupplyState(lendToken); uint supplySpeed = compStorage.aurumSpeeds(lendToken); uint deltaTime = currentTime - supplyStateTimestamp; if (deltaTime > 0 && supplySpeed > 0) { uint supplyTokens = LendTokenInterface(lendToken).totalSupply(); uint armAcc = deltaTime * supplySpeed; uint addingValue; if (supplyTokens > 0){ addingValue = armAcc * 1e36 / supplyTokens; // calculate index and stored in Double } else { addingValue = 0; } return supplyStateIndex + addingValue; } else { return supplyStateIndex; } } function getUpdateARMBorrowIndex(address lendToken, uint currentTime) internal view returns(uint) { (uint borrowStateIndex, uint borrowStateTimestamp) = compStorage.armBorrowState(lendToken); uint borrowSpeed = compStorage.aurumSpeeds(lendToken); uint deltaTime = currentTime - borrowStateTimestamp; uint marketBorrowIndex = LendTokenInterface(lendToken).borrowIndex(); if (deltaTime > 0 && borrowSpeed > 0) { uint borrowTokens = LendTokenInterface(lendToken).totalBorrows() * 1e18 / marketBorrowIndex; uint armAcc = deltaTime * borrowSpeed; // addingValue is e36 uint addingValue; if (borrowTokens > 0){ addingValue = armAcc * 1e36 / borrowTokens; // calculate index and stored in Double } else { addingValue = 0; } return borrowStateIndex + addingValue; } else { return borrowStateIndex; } } // This function called by front-end dApp to get real-time reward function getUpdateARMAccrued(address user, uint currentTime) external view returns(uint) { LendTokenInterface[] memory lendToken = compStorage.getAllMarkets(); ARMAccrued memory vars; uint priorARMAccrued = compStorage.getArmAccrued(user); uint i; uint deltaIndex; uint marketBorrowIndex; for(i=0;i<lendToken.length; i++){ vars.supplierIndex = compStorage.aurumSupplierIndex(address(lendToken[i]) , user); vars.borrowerIndex = compStorage.aurumBorrowerIndex(address(lendToken[i]) , user); vars.supplyStateIndex = getUpdateARMSupplyIndex(address(lendToken[i]), currentTime); vars.borrowStateIndex = getUpdateARMBorrowIndex(address(lendToken[i]), currentTime); marketBorrowIndex = lendToken[i].borrowIndex(); vars.aurumSpeed = compStorage.aurumSpeeds(address(lendToken[i])); //Supply Accrued if (vars.supplierIndex == 0 && vars.supplyStateIndex > 0) { vars.supplierIndex = 1e36; } deltaIndex = vars.supplyStateIndex - vars.supplierIndex; vars.supplierTokens = lendToken[i].balanceOf(user); priorARMAccrued += vars.supplierTokens * deltaIndex / 1e36; //Borrow Accrued if (vars.borrowerIndex > 0) { deltaIndex = vars.borrowStateIndex - vars.borrowerIndex; vars.borrowerAmount = lendToken[i].borrowBalanceStored(user) * 1e18 / marketBorrowIndex; priorARMAccrued += vars.borrowerAmount * deltaIndex / 1e36; } } return priorARMAccrued; } } contract ComptrollerStorage { event MarketListed(LendTokenInterface lendToken); event MarketEntered(LendTokenInterface lendToken, address account); event MarketExited(LendTokenInterface lendToken, address account); event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); event NewCollateralFactor(LendTokenInterface lendToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); event AurumSpeedUpdated(LendTokenInterface indexed lendToken, uint newSpeed); event DistributedSupplierARM(LendTokenInterface indexed lendToken, address indexed supplier, uint aurumDelta, uint aurumSupplyIndex); event DistributedBorrowerARM(LendTokenInterface indexed lendToken, address indexed borrower, uint aurumDelta, uint aurumBorrowIndex); event NewGOLDMintRate(uint oldGOLDMintRate, uint newGOLDMintRate); event ActionProtocolPaused(bool state); event ActionTransferPaused(bool state); event ActionSeizePaused(bool state); event ActionMintPaused(address lendToken, bool state); event ActionBorrowPaused(address lendToken, bool state); event NewGuardianAddress(address oldGuardian, address newGuardian); event NewBorrowCap(LendTokenInterface indexed lendToken, uint newBorrowCap); event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); event MintGOLDPause(bool state); address public armAddress; address public comptrollerAddress; address public admin; address public guardian; //Guardian address, can only stop protocol PriceOracle public oracle; //stored contract of current PriceOracle (can be changed by _setPriceOracle function) function getARMAddress() external view returns(address) {return armAddress;} // // Liquidation variables // //Close factor is the % (in 1e18 value) of borrowing asset can be liquidate //e.g. if set 50% --> borrow 1000 USD, position can be liquidate maximum of 500 USD uint public closeFactorMantissa; //calculate the maximum repayAmount when liquidating a borrow --> can be set by _setCloseFactor(uint) uint public liquidationIncentiveMantissa; //multiplier that liquidator will receive after successful liquidate ; venus comptroller set up = 1100000000000000000 (1.1e18) // // Pause variables // /** * @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 can only be paused globally, not by market. */ bool public protocolPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; function getMintGuardianPaused(address lendTokenAddress) external view returns(bool){ return mintGuardianPaused[lendTokenAddress];} mapping(address => bool) public borrowGuardianPaused; function getBorrowGuardianPaused(address lendTokenAddress) external view returns(bool){ return borrowGuardianPaused[lendTokenAddress];} bool public mintGOLDGuardianPaused; mapping(address => uint) public armAccrued; //ARM accrued but not yet transferred to each user function getArmAccrued(address user) external view returns (uint) {return armAccrued[user];} // // Aurum Gold controller 'AURUM token' // mapping(address => uint) public mintedGOLDs; //minted Aurum GOLD amount to each user function getMintedGOLDs(address user) external view returns(uint) {return mintedGOLDs[user];} uint16 public goldMintRate; //GOLD Mint Rate (percentage) value with two decimals 0-10000, 100 = 1%, 1000 = 10%, // // ARM distribution variables // mapping(address => uint) public aurumSpeeds; //The portion of aurumRate that each market currently receives function getAurumSpeeds(address lendToken) external view returns(uint) { return aurumSpeeds[lendToken];} // // Borrow cap // mapping(address => uint) public borrowCaps; //borrowAllowed for each lendToken address. Defaults to zero which corresponds to unlimited borrowing. function getBorrowCaps(address lendTokenAddress) external view returns (uint) { return borrowCaps[lendTokenAddress];} // // Market variables // mapping(address => LendTokenInterface[]) public accountAssets; //stored each account's assets. function getAssetsIn(address account) external view returns (LendTokenInterface[] memory) {return accountAssets[account];} struct Market { bool isListed; //Listed = true, Not listed = false /** * @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; mapping(address => bool) accountMembership; //Each market mapping of "accounts in this asset" similar to 'accountAssets' variable but the market side. } /** * @notice Official mapping of lendTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; //Can be set by _supportMarket admin function. function checkMembership(address account, LendTokenInterface lendToken) external view returns (bool) {return markets[address(lendToken)].accountMembership[account];} function isMarketListed(address lendTokenAddress) external view returns (bool) {return markets[lendTokenAddress].isListed;} function getMarketCollateralFactorMantissa(address lendTokenAddress) external view returns (uint) {return markets[lendTokenAddress].collateralFactorMantissa;} struct TheMarketState { /// @notice The market's last updated aurumBorrowIndex or aurumSupplyIndex // index variable is in Double (1e36) stored the last update index uint index; /// @notice The block number the index was last updated at uint lastTimestamp; } LendTokenInterface[] public allMarkets; //A list of all markets function getAllMarkets() external view returns(LendTokenInterface[] memory) {return allMarkets;} mapping(address => TheMarketState) public armSupplyState; //market supply state for each market mapping(address => TheMarketState) public armBorrowState; //market borrow state for each market //Individual index variables will update once individual check allowed function (will lastly call distributeSupplier / distributeBorrower function) to the current market's index. mapping(address => mapping(address => uint)) public aurumSupplierIndex; //supply index of each market for each supplier as of the last time they accrued ARM mapping(address => mapping(address => uint)) public aurumBorrowerIndex; //borrow index of each market for each borrower as of the last time they accrued ARM /// @notice The portion of ARM that each contributor receives per block mapping(address => uint) public aurumContributorSpeeds; /// @notice Last block at which a contributor's ARM rewards have been allocated mapping(address => uint) public lastContributorBlock; /// @notice The initial Aurum index for a market uint224 constant armInitialIndex = 1e36; // // CloseFactorMantissa guide // uint public constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must be strictly greater than this value ** MIN 5% uint public constant closeFactorMaxMantissa = 0.9e18; // 0.9 // closeFactorMantissa must not exceed this value ** MAX 90% uint public constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value constructor(address _armAddress) { admin = msg.sender; armAddress = _armAddress; closeFactorMantissa = 0.5e18; liquidationIncentiveMantissa = 1.1e18; } // // Comptroller parameter change function // Require comptroller is msg.sender // modifier onlyComptroller { require (msg.sender == comptrollerAddress, "Only comptroller"); _; } function _setNewStorageAdmin(address newAdmin) external onlyComptroller { admin = newAdmin; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param lendToken The market to enter * @param borrower The address of the account to modify */ function addToMarket(LendTokenInterface lendToken, address borrower) external onlyComptroller { Market storage marketToJoin = markets[address(lendToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join revert ("MARKET_NOT_LISTED"); } if (marketToJoin.accountMembership[borrower]) { // already joined return ; } // 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(lendToken); emit MarketEntered(lendToken, borrower); } // To exitMarket.. Checking condition // --user must not borrowing this asset, // --user is allowed to redeem all the tokens (no excess loan when hypotheticalLiquidityCheck) // Action // 1.trigger boolean of user address of market's accountMembership to false // 2.delete userAssetList to this market. // function exitMarket(address lendTokenAddress, address user) external onlyComptroller{ LendTokenInterface lendToken = LendTokenInterface(lendTokenAddress); Market storage marketToExit = markets[address(lendToken)]; /* Return out if the sender is not ‘in’ the market */ if (!marketToExit.accountMembership[user]) { return ; //the state variable had changed in redeemAllowed function (updateARMSupplyIndex, distributeSupplierARM) } /* Set lendToken account membership to false */ delete marketToExit.accountMembership[user]; /* Delete lendToken from the account’s list of assets */ // In order to delete lendToken, copy last item in list to location of item to be removed, reduce length by 1 LendTokenInterface[] storage userAssetList = accountAssets[user]; uint len = userAssetList.length; uint i; for (i=0 ; i < len ; i++) { if (userAssetList[i] == lendToken) { // found the deleting array userAssetList[i] = userAssetList[len - 1]; // move the last parameter in array to the deleting array userAssetList.pop(); //this function remove the last parameter and also reduce array length by 1 break; //break before i++ so if there is the asset list, 'i' must always lesser than 'len' } } // We *must* have found the asset in the list or our redundant data structure is broken assert(i < len); emit MarketExited(lendToken, user); } function setAurumSpeed(LendTokenInterface lendToken, uint aurumSpeed) external onlyComptroller { // This function called by comptroller's _setAurumSpeed //Update the aurumSpeeds state variable. aurumSpeeds[address(lendToken)] = aurumSpeed; emit AurumSpeedUpdated(lendToken, aurumSpeed); } // This function is called by _setAurumSpeed admin function when FIRST TIME starting distribute ARM reward (from aurumSpeed 0) // it will check the MarketState of this lendToken and set to InitialIndex function addARMdistributionMarket(LendTokenInterface lendToken) external onlyComptroller { // Add the ARM market Market storage market = markets[address(lendToken)]; require(market.isListed == true, "aurum market is not listed"); // // These Lines of code is modified from Venus // If someone had mint lendToken or Allowed function is called, the timestamp would be change and not equal to zero // /* if (armSupplyState[address(lendToken)].index == 0 && armSupplyState[address(lendToken)].lastTimestamp == 0) { armSupplyState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } if (armBorrowState[address(lendToken)].index == 0 && armBorrowState[address(lendToken)].lastTimestamp == 0) { armBorrowState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } */ // // We remove the timeStamp == 0 , once distribution is initiated the index will not back to zero again. // This prevent over-reward of ARM if someone is pre-supply before the reward is initiating distribution. // if (armSupplyState[address(lendToken)].index == 0) { armSupplyState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } if (armBorrowState[address(lendToken)].index == 0) { armBorrowState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } } //Update the ARM distribute to Supplier //This function update the armSupplyState function updateARMSupplyIndex(address lendToken) external onlyComptroller { TheMarketState storage supplyState = armSupplyState[lendToken]; uint supplySpeed = aurumSpeeds[lendToken]; uint currentTime = block.timestamp; uint deltaTime = currentTime - supplyState.lastTimestamp; if (deltaTime > 0 && supplySpeed > 0) { uint supplyTokens = LendTokenInterface(lendToken).totalSupply(); uint armAcc = deltaTime * supplySpeed; // addingValue is e36 uint addingValue; if (supplyTokens > 0){ addingValue = armAcc * 1e36 / supplyTokens; // calculate index and stored in Double } else { addingValue = 0; } uint newindex = supplyState.index + addingValue; armSupplyState[lendToken] = TheMarketState({ index: newindex, // setting new updated index lastTimestamp: currentTime //and also timestamp }); } else if (deltaTime > 0) { supplyState.lastTimestamp = currentTime; } } //Update the ARM distribute to Borrower //same as above function but interact with Borrower variables function updateARMBorrowIndex(address lendToken, uint marketBorrowIndex) external onlyComptroller { TheMarketState storage borrowState = armBorrowState[lendToken]; uint borrowSpeed = aurumSpeeds[lendToken]; uint currentTime = block.timestamp; uint deltaTime = currentTime - borrowState.lastTimestamp; if (deltaTime > 0 && borrowSpeed > 0) { //borrowAmount is 1e18 :: e18 * 1e18 / e18 uint borrowAmount = LendTokenInterface(lendToken).totalBorrows() * 1e18 / marketBorrowIndex; uint armAcc = deltaTime * borrowSpeed; uint addingValue; if (borrowAmount > 0){ addingValue = armAcc * 1e36 / borrowAmount; // calculate index and stored in Double } else { addingValue = 0; } uint newindex = borrowState.index + addingValue; armBorrowState[lendToken] = TheMarketState({ index: newindex, // setting new updated index lastTimestamp: currentTime //and also timestamp }); } else if (deltaTime > 0) { borrowState.lastTimestamp = currentTime; } } //Distribute function will update armAccrued depends on the State.index which update by updateARM function //armAccrued will later claim by claimARM function function distributeSupplierARM(address lendToken, address supplier) external onlyComptroller { TheMarketState storage supplyState = armSupplyState[lendToken]; uint supplyIndex = supplyState.index; // stored in 1e36 uint supplierIndex = aurumSupplierIndex[lendToken][supplier]; // stored in 1e36 aurumSupplierIndex[lendToken][supplier] = supplyIndex; // update the user's index to the current state if (supplierIndex == 0 && supplyIndex > 0) { //This happen when first time using Allowed function after initialized reward distribution (Mint/Redeem/Seize) //or receiving a lendToken but currently don't have this token (transferAllowed function) supplierIndex = armInitialIndex; // 1e36 } //Calculate the new accrued arm since last update uint deltaIndex = supplyIndex - supplierIndex; uint supplierTokens = LendTokenInterface(lendToken).balanceOf(supplier); //e18 //If first time Mint/receive transfer LendToken, the balanceOf should be 0 uint supplierDelta = supplierTokens * deltaIndex / 1e36; //e18 :: e18*e36/ 1e36 uint supplierAccrued = armAccrued[supplier] + supplierDelta; armAccrued[supplier] = supplierAccrued; emit DistributedSupplierARM(LendTokenInterface(lendToken), supplier, supplierDelta, supplyIndex); } function distributeBorrowerARM(address lendToken, address borrower, uint marketBorrowIndex) external onlyComptroller { TheMarketState storage borrowState = armBorrowState[lendToken]; uint borrowIndex = borrowState.index; // stored in 1e36 uint borrowerIndex = aurumBorrowerIndex[lendToken][borrower]; // stored in 1e36 aurumBorrowerIndex[lendToken][borrower] = borrowIndex; // update the user's index to the current state if (borrowerIndex > 0) { uint deltaIndex = borrowIndex - borrowerIndex; // e36 // Let explain in diagram // [p] = principal // [i] = interest // [/i] = interest not yet record in accountBorrows[user] // [p][p][p][p][i] principal with interest (accountBorrows[user] stored 1. principal and 2.interestIndex multiplier) // [p][p][p][p] principal / interestIndex // [p][p][p][p][/i][/i] principal / interestIndex * marketBorrowIndex (this is what borrowBalanceStored function returns); // We need only principal amount to be calculated. uint borrowerAmount = LendTokenInterface(lendToken).borrowBalanceStored(borrower) * 1e18 / marketBorrowIndex; // e18 //This result uint borrowerDelta = borrowerAmount * deltaIndex / 1e36; // e18 :: e18 * e36 / 1e36 uint borrowerAccrued = armAccrued[borrower] + borrowerDelta; armAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerARM(LendTokenInterface(lendToken), borrower, borrowerDelta, borrowIndex); } } //called by claimARM function //This function execute change of state variable 'armAccrued' and transfer ARM token to user. //returns the pending reward after claim. by the way it's not necessory. function grantARM(address user, uint amount) external onlyComptroller returns (uint) { IERC20 arm = IERC20(armAddress); uint armRemaining = arm.balanceOf(address(this)); // when the ARM reward pool is nearly empty, admin should manually turn aurum speed to 0 //Treasury reserves will be used when there is human error in reward process. if (amount > 0 && amount <= armRemaining) { armAccrued[user] = 0; arm.transfer(user, amount); return 0; } return amount; } function setMintedGOLD(address owner, uint amount) external onlyComptroller{ mintedGOLDs[owner] = amount; } // // Admin function // function _setComptrollerAddress (address newComptroller) external { require(msg.sender == admin, "Only admin"); comptrollerAddress = newComptroller; } // Maximum % of borrowing position can be liquidated (stored in 1e18) function _setCloseFactor(uint newCloseFactorMantissa) external { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, newCloseFactorMantissa); } function _setCollateralFactor(LendTokenInterface lendToken, uint newCollateralFactorMantissa) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); // Verify market is listed Market storage market = markets[address(lendToken)]; if (!market.isListed) { revert ("Market not listed"); } // Check collateral factor <= 0.9 uint highLimit = collateralFactorMaxMantissa; require (highLimit > newCollateralFactorMantissa); // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(lendToken) == 0) { revert ("Fail price oracle"); } // 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(lendToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); } // LiquidativeIncentive is > 1.00 // if set 1.1e18 means liquidator get 10% of liquidated position function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); require(newLiquidationIncentiveMantissa >= 1e18,"value must greater than 1e18"); // 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); } // Add the market to the markets mapping and set it as listed function _supportMarket(LendTokenInterface lendToken) external{ require(msg.sender == admin, "Only admin"); if (markets[address(lendToken)].isListed) { revert ("Already list"); } require (lendToken.isLendToken(),"Not lendToken"); // Sanity check to make sure its really a LendTokenInterface markets[address(lendToken)].isListed = true; markets[address(lendToken)].collateralFactorMantissa = 0; for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != lendToken, "Already added"); } allMarkets.push(lendToken); emit MarketListed(lendToken); } //Set borrowCaps function _setMarketBorrowCaps(LendTokenInterface[] calldata lendTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin, "Only admin"); uint numMarkets = lendTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(lendTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(lendTokens[i], newBorrowCaps[i]); } } /** * Set whole protocol pause/unpause state */ function _setGuardianAddress(address newGuardian) external { require(msg.sender == admin, "No Auth"); address oldGuardian = guardian; guardian = newGuardian; emit NewGuardianAddress(oldGuardian, newGuardian); } //Guardians can pause protocol but can't unpause function _setProtocolPaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); protocolPaused = state; emit ActionProtocolPaused(state); } function _setTransferPaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); transferGuardianPaused = state; emit ActionTransferPaused(state); } function _setSeizePaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); seizeGuardianPaused = state; emit ActionSeizePaused(state); } function _setMintPaused(address lendToken, bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); mintGuardianPaused[lendToken] = state; emit ActionMintPaused(lendToken, state); } function _setBorrowPaused(address lendToken, bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); borrowGuardianPaused[lendToken] = state; emit ActionBorrowPaused(lendToken, state); } function _setMintGoldPause(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); mintGOLDGuardianPaused = state; emit MintGOLDPause(state); } function _setGOLDMintRate(uint16 newGOLDMintRate) external{ require(msg.sender == admin, "Only admin"); // Input: 0-10000, percentage with 2 decimals // 1 = 0.01% // 100 = 1% // 10000 = 100% // Check caller is admin require (newGOLDMintRate > 0 && newGOLDMintRate <= 10000,"Mintable GOLD rate must value 0-10000"); uint oldGOLDMintRate = goldMintRate; goldMintRate = newGOLDMintRate; emit NewGOLDMintRate(oldGOLDMintRate, newGOLDMintRate); } /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle */ function _setPriceOracle(PriceOracle newOracle) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); // 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); } }
The ledger of user's AURUM minted is stored in ComptrollerStorage contract.
function getMintedGOLDs(address minter) external view returns(uint) {
15,849,431
./partial_match/3/0x9a01e8Fbf0d024867178B22eBD0b4De4662d6Dfc/sources/GHTVerificationService.sol
Set the user's address to lock or unlock./
function _setWhiteListAddress(address account, bool flag) internal { _whiteListAddress[account] = flag; }
5,252,756
pragma solidity ^0.6.2; // SPDX-License-Identifier: MIT import "./Ownable.sol"; import "./IERC20.sol"; import "./ITraderJoeRouter.sol"; contract WhiteRabbitBuybackFund is Ownable { address constant DEAD_ADDRESS = address(57005); ITraderJoeRouter router; IERC20 token; uint256 public totalAvaxDeposited; uint256 public totalAvaxBought; uint256 public totalTokensBought; event Deposit(uint256 amount); event BuybackIssued(uint256 amountIn, uint256 amountOut); constructor(address routerAddress, address tokenAddress) public { router = ITraderJoeRouter(routerAddress); token = IERC20(tokenAddress); } function buyback(uint256 amountIn) external onlyOwner returns (uint256) { require(amountIn > 0, "Insufficient value sent"); require(address(this).balance >= amountIn, "Insufficient balance"); // create swap path address[] memory path = new address[](2); path[0] = router.WAVAX(); path[1] = address(token); // buy tokens uint256 previousBalance = token.balanceOf(DEAD_ADDRESS); router.swapExactAVAXForTokensSupportingFeeOnTransferTokens{value: amountIn}(0, path, DEAD_ADDRESS, block.timestamp); uint256 amountBoughtBack = token.balanceOf(DEAD_ADDRESS) - previousBalance; // track for statistics totalAvaxBought += amountIn; totalTokensBought += amountBoughtBack; emit BuybackIssued(amountIn, amountBoughtBack); } function deposit() external payable onlyOwner { totalAvaxDeposited += msg.value; emit Deposit(msg.value); } }
create swap path buy tokens track for statistics
function buyback(uint256 amountIn) external onlyOwner returns (uint256) { require(amountIn > 0, "Insufficient value sent"); require(address(this).balance >= amountIn, "Insufficient balance"); address[] memory path = new address[](2); path[0] = router.WAVAX(); path[1] = address(token); uint256 previousBalance = token.balanceOf(DEAD_ADDRESS); uint256 amountBoughtBack = token.balanceOf(DEAD_ADDRESS) - previousBalance; totalAvaxBought += amountIn; totalTokensBought += amountBoughtBack; emit BuybackIssued(amountIn, amountBoughtBack); }
7,269,582
pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title 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(); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } /** * The Ether Based Source Chain token (EBSC - EBSCToken) has a fixed supply * * The owner can associate the token with a token sale contract. In that * case, the token balance is moved to the token sale contract, which * in turn can transfer its tokens to contributors to the sale. */ contract EBSCToken is StandardToken, BurnableToken, Ownable { // Constants string public constant name = "Ether Based Source Chain"; string public constant symbol = "EBSC"; uint8 public constant decimals = 18; string public constant website = "www.ebsc.io"; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); uint256 public constant CROWDSALE_ALLOWANCE = 800000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = 200000000 * (10 ** uint256(decimals)); // Properties uint256 public crowdSaleAllowance; // the number of tokens available for crowdsales uint256 public adminAllowance; // the number of tokens available for the administrator address public crowdSaleAddr; // the address of a crowdsale currently selling this token address public adminAddr; // the address of a crowdsale currently selling this token //bool public transferEnabled = false; // indicates if transferring tokens is enabled or not bool public transferEnabled = true; // Enables everyone to transfer tokens // Modifiers /** * The listed addresses are not valid recipients of tokens. * * 0x0 - the zero address is not valid * this - the contract itself should not receive tokens * owner - the owner has all the initial tokens, but cannot receive any back * adminAddr - the admin has an allowance of tokens to transfer, but does not receive any * crowdSaleAddr - the crowdsale has an allowance of tokens to transfer, but does not receive any */ modifier validDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); require(_to != owner); require(_to != address(adminAddr)); require(_to != address(crowdSaleAddr)); _; } /** * Constructor - instantiates token supply and allocates balanace of * to the owner (msg.sender). */ function EBSCToken(address _admin) public { // the owner is a custodian of tokens that can // give an allowance of tokens for crowdsales // or to the admin, but cannot itself transfer // tokens; hence, this requirement require(msg.sender != _admin); totalSupply = INITIAL_SUPPLY; crowdSaleAllowance = CROWDSALE_ALLOWANCE; adminAllowance = ADMIN_ALLOWANCE; // mint all tokens balances[msg.sender] = totalSupply.sub(adminAllowance); Transfer(address(0x0), msg.sender, totalSupply.sub(adminAllowance)); balances[_admin] = adminAllowance; Transfer(address(0x0), _admin, adminAllowance); adminAddr = _admin; approve(adminAddr, adminAllowance); } /** * Associates this token with a current crowdsale, giving the crowdsale * an allowance of tokens from the crowdsale supply. This gives the * crowdsale the ability to call transferFrom to transfer tokens to * whomever has purchased them. * * Note that if _amountForSale is 0, then it is assumed that the full * remaining crowdsale supply is made available to the crowdsale. * * @param _crowdSaleAddr The address of a crowdsale contract that will sell this token * @param _amountForSale The supply of tokens provided to the crowdsale */ function setCrowdsale(address _crowdSaleAddr, uint256 _amountForSale) external onlyOwner { require(_amountForSale <= crowdSaleAllowance); // if 0, then full available crowdsale supply is assumed uint amount = (_amountForSale == 0) ? crowdSaleAllowance : _amountForSale; // Clear allowance of old, and set allowance of new approve(crowdSaleAddr, 0); approve(_crowdSaleAddr, amount); crowdSaleAddr = _crowdSaleAddr; } /** * Overrides ERC20 transfer function with modifier that prevents the * ability to transfer tokens until after transfers have been enabled. */ function transfer(address _to, uint256 _value) public validDestination(_to) returns (bool) { return super.transfer(_to, _value); } /** * Overrides ERC20 transferFrom function with modifier that prevents the * ability to transfer tokens until after transfers have been enabled. */ function transferFrom(address _from, address _to, uint256 _value) public validDestination(_to) returns (bool) { bool result = super.transferFrom(_from, _to, _value); if (result) { if (msg.sender == crowdSaleAddr) crowdSaleAllowance = crowdSaleAllowance.sub(_value); if (msg.sender == adminAddr) adminAllowance = adminAllowance.sub(_value); } return result; } /** * Overrides the burn function so that it cannot be called until after * transfers have been enabled. * * @param _value The amount of tokens to burn in wei-EBSC */ function burn(uint256 _value) public { require(transferEnabled || msg.sender == owner); super.burn(_value); Transfer(msg.sender, address(0x0), _value); } } /** * The EBSCSale smart contract is used for selling EBSC tokens (EBSC). * It does so by converting ETH received into a quantity of * tokens that are transferred to the contributor via the ERC20-compatible * transferFrom() function. */ contract EBSCSale is Pausable { using SafeMath for uint256; // The beneficiary is the future recipient of the funds address public beneficiary; // The crowdsale has a funding goal, cap, deadline, and minimum contribution uint public fundingGoal; uint public fundingCap; uint public minContribution; bool public fundingGoalReached = false; bool public fundingCapReached = false; bool public saleClosed = false; // Time period of sale (UNIX timestamps) uint public startTime; uint public endTime; // Keeps track of the amount of wei raised uint public amountRaised; // Refund amount, should it be required uint public refundAmount; // The ratio of EBSC to Ether uint public rate = 6000; uint public constant LOW_RANGE_RATE = 500; uint public constant HIGH_RANGE_RATE = 20000; // prevent certain functions from being recursively called bool private rentrancy_lock = false; // The token being sold EBSCToken public tokenReward; // A map that tracks the amount of wei contributed by address mapping(address => uint256) public balanceOf; // Events event GoalReached(address _beneficiary, uint _amountRaised); event CapReached(address _beneficiary, uint _amountRaised); event FundTransfer(address _backer, uint _amount, bool _isContribution); // Modifiers modifier beforeDeadline() { require (currentTime() < endTime); _; } modifier afterDeadline() { require (currentTime() >= endTime); _; } modifier afterStartTime() { require (currentTime() >= startTime); _; } modifier saleNotClosed() { require (!saleClosed); _; } modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } /** * Constructor for a crowdsale of QuantstampToken tokens. * * @param ifSuccessfulSendTo the beneficiary of the fund * @param fundingGoalInEthers the minimum goal to be reached * @param fundingCapInEthers the cap (maximum) size of the fund * @param minimumContributionInWei minimum contribution (in wei) * @param start the start time (UNIX timestamp) * @param end the end time (UNIX timestamp) * @param rateEBSCToEther the conversion rate from EBSC to Ether * @param addressOfTokenUsedAsReward address of the token being sold */ function EBSCSale( address ifSuccessfulSendTo, uint fundingGoalInEthers, uint fundingCapInEthers, uint minimumContributionInWei, uint start, uint end, uint rateEBSCToEther, address addressOfTokenUsedAsReward ) public { require(ifSuccessfulSendTo != address(0) && ifSuccessfulSendTo != address(this)); require(addressOfTokenUsedAsReward != address(0) && addressOfTokenUsedAsReward != address(this)); require(fundingGoalInEthers <= fundingCapInEthers); require(end > 0); beneficiary = ifSuccessfulSendTo; fundingGoal = fundingGoalInEthers * 1 ether; fundingCap = fundingCapInEthers * 1 ether; minContribution = minimumContributionInWei; startTime = start; endTime = end; // TODO double check setRate(rateEBSCToEther); tokenReward = EBSCToken(addressOfTokenUsedAsReward); } /** * This fallback function is called whenever Ether is sent to the * smart contract. It can only be executed when the crowdsale is * not paused, not closed, and before the deadline has been reached. * * This function will update state variables for whether or not the * funding goal or cap have been reached. It also ensures that the * tokens are transferred to the sender, and that the correct * number of tokens are sent according to the current rate. */ function () public payable whenNotPaused beforeDeadline afterStartTime saleNotClosed nonReentrant { require(msg.value >= minContribution); // Update the sender's balance of wei contributed and the amount raised uint amount = msg.value; uint currentBalance = balanceOf[msg.sender]; balanceOf[msg.sender] = currentBalance.add(amount); amountRaised = amountRaised.add(amount); // Compute the number of tokens to be rewarded to the sender // Note: it's important for this calculation that both wei // and EBSC have the same number of decimal places (18) uint numTokens = amount.mul(rate); // Transfer the tokens from the crowdsale supply to the sender if (tokenReward.transferFrom(tokenReward.owner(), msg.sender, numTokens)) { FundTransfer(msg.sender, amount, true); // Check if the funding goal or cap have been reached // TODO check impact on gas cost checkFundingGoal(); checkFundingCap(); } else { revert(); } } /** * The owner can terminate the crowdsale at any time. */ function terminate() external onlyOwner { saleClosed = true; } /** * The owner can update the rate (EBSC to ETH). * * @param _rate the new rate for converting EBSC to ETH */ function setRate(uint _rate) public onlyOwner { require(_rate >= LOW_RANGE_RATE && _rate <= HIGH_RANGE_RATE); rate = _rate; } /** * The owner can allocate the specified amount of tokens from the * crowdsale allowance to the recipient (_to). * * NOTE: be extremely careful to get the amounts correct, which * are in units of wei and mini-EBSC. Every digit counts. * * @param _to the recipient of the tokens * @param amountWei the amount contributed in wei * @param amountMiniEbsc the amount of tokens transferred in mini-EBSC (18 decimals) */ function ownerAllocateTokens(address _to, uint amountWei, uint amountMiniEbsc) external onlyOwner nonReentrant { if (!tokenReward.transferFrom(tokenReward.owner(), _to, amountMiniEbsc)) { revert(); } balanceOf[_to] = balanceOf[_to].add(amountWei); amountRaised = amountRaised.add(amountWei); FundTransfer(_to, amountWei, true); checkFundingGoal(); checkFundingCap(); } /** * The owner can call this function to withdraw the funds that * have been sent to this contract for the crowdsale subject to * the funding goal having been reached. The funds will be sent * to the beneficiary specified when the crowdsale was created. */ function ownerSafeWithdrawal() external onlyOwner nonReentrant { require(fundingGoalReached); uint balanceToSend = this.balance; beneficiary.transfer(balanceToSend); FundTransfer(beneficiary, balanceToSend, false); } /** * The owner can unlock the fund with this function. The use- * case for this is when the owner decides after the deadline * to allow contributors to be refunded their contributions. * Note that the fund would be automatically unlocked if the * minimum funding goal were not reached. */ function ownerUnlockFund() external afterDeadline onlyOwner { fundingGoalReached = false; } /** * This function permits anybody to withdraw the funds they have * contributed if and only if the deadline has passed and the * funding goal was not reached. */ function safeWithdrawal() external afterDeadline nonReentrant { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); FundTransfer(msg.sender, amount, false); refundAmount = refundAmount.add(amount); } } } /** * Checks if the funding goal has been reached. If it has, then * the GoalReached event is triggered. */ function checkFundingGoal() internal { if (!fundingGoalReached) { if (amountRaised >= fundingGoal) { fundingGoalReached = true; GoalReached(beneficiary, amountRaised); } } } /** * Checks if the funding cap has been reached. If it has, then * the CapReached event is triggered. */ function checkFundingCap() internal { if (!fundingCapReached) { if (amountRaised >= fundingCap) { fundingCapReached = true; saleClosed = true; CapReached(beneficiary, amountRaised); } } } /** * Returns the current time. * Useful to abstract calls to "now" for tests. */ function currentTime() public constant returns (uint _currentTime) { return now; } /** * Given an amount in EBSC, this method returns the equivalent amount * in mini-EBSC. * * @param amount an amount expressed in units of EBSC */ function convertToMiniEbsc(uint amount) internal constant returns (uint) { return amount * (10 ** uint(tokenReward.decimals())); } /** * These helper functions are exposed for changing the start and end time dynamically */ function changeStartTime(uint256 _startTime) external onlyOwner {startTime = _startTime;} function changeEndTime(uint256 _endTime) external onlyOwner {endTime = _endTime;} }
Given an amount in EBSC, this method returns the equivalent amount in mini-EBSC. amount an amount expressed in units of EBSC/
function convertToMiniEbsc(uint amount) internal constant returns (uint) { return amount * (10 ** uint(tokenReward.decimals())); }
14,115,699
/** *Submitted for verification at Etherscan.io on 2021-03-10 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.7.4; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.7.4; /** * @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 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; /* Added by WorkQuest Team */ address private _owner; bool private _locked = false; bool private _lockFixed = false; address private _saleContract = address(0); /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; _owner = msg.sender; //added by WorkQuest Team } /** * @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) { require(!_locked || msg.sender == _saleContract, "Transfers locked"); //added by WorkQuest Team _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { require(!_locked, "Transfers locked"); //added by WorkQuest Team _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Set the address of the sale contract. * `saleContract` can make token transfers * even when the token contract state is locked. * Transfer lock serves the purpose of preventing * the creation of fake Uniswap pools. * * Added by WorkQuest Team. * */ function setSaleContract(address saleContract) public { require(msg.sender == _owner && _saleContract == address(0), "Caller must be owner and _saleContract yet unset"); _saleContract = saleContract; } /** * @dev Lock token transfers. * * Added by WorkQuest Team. * */ function lockTransfers() public { require(msg.sender == _owner && !_lockFixed, "Caller must be owner and _lockFixed false"); _locked = true; } /** * @dev Unlock token transfers. * * Added by WorkQuest Team. * */ function unlockTransfers() public { require(msg.sender == _owner && !_lockFixed, "Caller must be owner and _lockFixed false"); _locked = false; } /** * @dev Permanently unlock token transfers. * After this, further locking is impossible. * * Added by WorkQuest Team. * */ function unlockTransfersPermanent() public { require(msg.sender == _owner && !_lockFixed, "Caller must be owner and _lockFixed false"); _locked = false; _lockFixed = true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/CustomToken.sol pragma solidity ^0.7.4; contract CustomToken is ERC20 { constructor( address initialAccount, uint256 initialBalance ) ERC20("Work Quest Token", "WQT") { _mint(initialAccount, initialBalance); } }
Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
7,733,496
./full_match/3/0xf6d0B298e8B442AE851002Ed8a58f994A18A1edc/sources/Project3.sol
require(preseedfunding >= values[i]); teamSupply = SafeMath.sub(teamSupply,values[i]);
function transferPreseedfundingTokens(address[] calldata recipients, uint256[] calldata values) onlyOwner external { for (uint256 i = 0; i < recipients.length; i++) { _mint(recipients[i], values[i]); } }
14,174,558
// SPDX-License-Identifier: BSD-4-Clause pragma solidity 0.8.3; import "./IOddzLiquidityPoolManager.sol"; import "../Libs/DateTimeLibrary.sol"; import "../Swap/IDexManager.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; contract OddzLiquidityPoolManager is AccessControl, IOddzLiquidityPoolManager, ERC20("Oddz USD LP token", "oUSD") { using Math for uint256; using Address for address; using SafeERC20 for IERC20; /** * @dev reqBalance represents minimum required balance out of 10 * Range between 6 and 10 * e.g. 8 represents 80% of the balance */ uint8 public reqBalance = 8; /** * @dev Liquidity specific data definitions */ LockedLiquidity[] public lockedLiquidity; IERC20 public token; /** * @dev Liquidity lock and distribution data definitions */ mapping(uint256 => bool) public allowedMaxExpiration; mapping(uint256 => uint256) public periodMapper; mapping(bytes32 => IOddzLiquidityPool[]) public poolMapper; mapping(bytes32 => bool) public uniquePoolMapper; /** * @dev Active pool count */ mapping(IOddzLiquidityPool => uint256) public override poolExposure; /** * @dev Disabled pools */ mapping(IOddzLiquidityPool => bool) public disabledPools; // user address -> date of transfer mapping(address => uint256) public lastPoolTransfer; /** * @dev Premium specific data definitions */ uint256 public premiumLockupDuration = 14 days; uint256 public moveLockupDuration = 7 days; /** * @dev DEX manager */ IDexManager public dexManager; address public strategyManager; /** * @dev Access control specific data definitions */ bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 public constant TIMELOCKER_ROLE = keccak256("TIMELOCKER_ROLE"); modifier onlyOwner(address _address) { require(hasRole(DEFAULT_ADMIN_ROLE, _address), "LP Error: caller has no access to the method"); _; } modifier onlyManager(address _address) { require(hasRole(MANAGER_ROLE, _address), "LP Error: caller has no access to the method"); _; } modifier onlyTimeLocker(address _address) { require(hasRole(TIMELOCKER_ROLE, _address), "LP Error: caller has no access to the method"); _; } modifier validLiquidty(uint256 _id) { LockedLiquidity storage ll = lockedLiquidity[_id]; require(ll._locked, "LP Error: liquidity has already been unlocked"); _; } modifier reqBalanceValidRange(uint8 _reqBalance) { require(_reqBalance >= 6 && _reqBalance <= 10, "LP Error: required balance valid range [6 - 10]"); _; } modifier validMaxExpiration(uint256 _maxExpiration) { require(allowedMaxExpiration[_maxExpiration] == true, "LP Error: invalid maximum expiration"); _; } modifier validCaller(address _provider) { require(msg.sender == _provider || msg.sender == strategyManager, "LP Error: invalid caller"); _; } constructor(IERC20 _token, IDexManager _dexManager) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(TIMELOCKER_ROLE, msg.sender); _setRoleAdmin(TIMELOCKER_ROLE, TIMELOCKER_ROLE); token = _token; dexManager = _dexManager; addAllowedMaxExpiration(1); addAllowedMaxExpiration(2); addAllowedMaxExpiration(7); addAllowedMaxExpiration(14); addAllowedMaxExpiration(30); mapPeriod(1, 1); mapPeriod(2, 2); mapPeriod(3, 7); mapPeriod(4, 7); mapPeriod(5, 7); mapPeriod(6, 7); mapPeriod(7, 7); mapPeriod(8, 14); mapPeriod(9, 14); mapPeriod(10, 14); mapPeriod(11, 14); mapPeriod(12, 14); mapPeriod(13, 14); mapPeriod(14, 14); mapPeriod(15, 30); mapPeriod(16, 30); mapPeriod(17, 30); mapPeriod(18, 30); mapPeriod(19, 30); mapPeriod(20, 30); mapPeriod(21, 30); mapPeriod(22, 30); mapPeriod(23, 30); mapPeriod(24, 30); mapPeriod(25, 30); mapPeriod(26, 30); mapPeriod(27, 30); mapPeriod(28, 30); mapPeriod(29, 30); mapPeriod(30, 30); } function addLiquidity( address _provider, IOddzLiquidityPool _pool, uint256 _amount ) external override validCaller(_provider) returns (uint256 mint) { require(poolExposure[_pool] > 0, "LP Error: Invalid pool"); mint = _amount; require(mint > 0, "LP Error: Amount is too small"); uint256 eligiblePremium = _pool.collectPremium(_provider, premiumLockupDuration); if (eligiblePremium > 0) token.safeTransfer(_provider, eligiblePremium); _pool.addLiquidity(_amount, _provider); _mint(_provider, mint); token.safeTransferFrom(_provider, address(this), _amount); } function removeLiquidity( address _provider, IOddzLiquidityPool _pool, uint256 _amount ) external override validCaller(_provider) { require(poolExposure[_pool] > 0, "LP Error: Invalid pool"); require(_amount <= balanceOf(_provider), "LP Error: Amount exceeds oUSD balance"); uint256 eligiblePremium = _pool.collectPremium(_provider, premiumLockupDuration); token.safeTransfer( _provider, _removeLiquidity(_provider, _pool, _amount, premiumLockupDuration) + eligiblePremium ); _burn(_provider, _amount); } function _removeLiquidity( address _provider, IOddzLiquidityPool _pool, uint256 _amount, uint256 premiumLockPeriod ) private returns (uint256 transferAmount) { uint256 validateBalance; if (disabledPools[_pool]) validateBalance = _pool.availableBalance() * 10; else validateBalance = _pool.availableBalance() * reqBalance; require(_amount * 10 <= validateBalance, "LP Error: Not enough funds in the pool. Please lower the amount."); require(_amount > 0, "LP Error: Amount is too small"); transferAmount = _pool.removeLiquidity(_amount, _provider, premiumLockPeriod); } function lockLiquidity( uint256 _id, LiquidityParams memory _liquidityParams, uint256 _premium ) external override onlyManager(msg.sender) { require(_id == lockedLiquidity.length, "LP Error: Invalid id"); (address[] memory pools, uint256[] memory poolBalances) = getSortedEligiblePools(_liquidityParams); require(pools.length > 0, "LP Error: No pool balance"); uint8 count = 0; uint256 totalAmount = _liquidityParams._amount; uint256 base = totalAmount / pools.length; uint256[] memory share = new uint256[](pools.length); while (count < pools.length) { if (base > poolBalances[count]) share[count] = poolBalances[count]; else share[count] = base; IOddzLiquidityPool(pools[count]).lockLiquidity(share[count]); totalAmount -= share[count]; if (totalAmount > 0) base = totalAmount / (pools.length - (count + 1)); count++; } lockedLiquidity.push(LockedLiquidity(_liquidityParams._amount, _premium, true, pools, share)); } function unlockLiquidity(uint256 _id) external override onlyManager(msg.sender) validLiquidty(_id) { LockedLiquidity storage ll = lockedLiquidity[_id]; for (uint8 i = 0; i < ll._pools.length; i++) { IOddzLiquidityPool(ll._pools[i]).unlockLiquidity(ll._share[i]); IOddzLiquidityPool(ll._pools[i]).unlockPremium(_id, (ll._premium * ll._share[i]) / ll._amount); } ll._locked = false; } function send( uint256 _id, address _account, uint256 _amount ) external override onlyManager(msg.sender) validLiquidty(_id) { (, uint256 transferAmount) = _updateAndFetchLockedLiquidity(_id, _account, _amount); // Transfer Funds token.safeTransfer(_account, transferAmount); } function sendUA( uint256 _id, address _account, uint256 _amount, bytes32 _underlying, bytes32 _strike, uint32 _deadline, uint16 _minAmountsOut ) public override onlyManager(msg.sender) validLiquidty(_id) { (, uint256 transferAmount) = _updateAndFetchLockedLiquidity(_id, _account, _amount); address exchange = dexManager.getExchange(_underlying, _strike); // Transfer Funds token.safeTransfer(exchange, transferAmount); // block.timestamp + deadline --> deadline from the current block dexManager.swap( _strike, _underlying, exchange, _account, transferAmount, block.timestamp + _deadline, _minAmountsOut ); } /** * @notice Move liquidity between pools * @param _poolTransfer source and destination pools with amount of transfer */ function move(address _provider, PoolTransfer memory _poolTransfer) external override validCaller(_provider) { require( lastPoolTransfer[_provider] == 0 || (lastPoolTransfer[_provider] + moveLockupDuration) < block.timestamp, "LP Error: Pool transfer not allowed" ); lastPoolTransfer[_provider] = block.timestamp; int256 totalTransfer = 0; for (uint256 i = 0; i < _poolTransfer._source.length; i++) { require( (poolExposure[_poolTransfer._source[i]] > 0) || disabledPools[_poolTransfer._source[i]], "LP Error: Invalid pool" ); _removeLiquidity(_provider, _poolTransfer._source[i], _poolTransfer._sAmount[i], moveLockupDuration); totalTransfer += int256(_poolTransfer._sAmount[i]); } for (uint256 i = 0; i < _poolTransfer._destination.length; i++) { require(poolExposure[_poolTransfer._destination[i]] > 0, "LP Error: Invalid pool"); _poolTransfer._destination[i].addLiquidity(_poolTransfer._dAmount[i], _provider); totalTransfer -= int256(_poolTransfer._dAmount[i]); } require(totalTransfer == 0, "LP Error: invalid transfer amount"); } /** * @notice withdraw porfits from the pool * @param _pool liquidity pool address */ function withdrawProfits(IOddzLiquidityPool _pool) external { require(poolExposure[_pool] > 0, "LP Error: Invalid pool"); uint256 premium = _pool.collectPremium(msg.sender, premiumLockupDuration); require(premium > 0, "LP Error: No premium allocated"); token.safeTransfer(msg.sender, premium); } /** * @notice update and returns locked liquidity * @param _lid Id of LockedLiquidity that should be unlocked * @param _account Provider account address * @param _amount Funds that should be sent */ function _updateAndFetchLockedLiquidity( uint256 _lid, address _account, uint256 _amount ) private returns (uint256 lockedPremium, uint256 transferAmount) { LockedLiquidity storage ll = lockedLiquidity[_lid]; require(_account != address(0), "LP Error: Invalid address"); ll._locked = false; lockedPremium = ll._premium; transferAmount = _amount; if (transferAmount > ll._amount) transferAmount = ll._amount; for (uint8 i = 0; i < ll._pools.length; i++) { IOddzLiquidityPool(ll._pools[i]).unlockLiquidity(ll._share[i]); IOddzLiquidityPool(ll._pools[i]).exercisePremium( _lid, (lockedPremium * ll._share[i]) / ll._amount, (transferAmount * ll._share[i]) / ll._amount ); } } /** * @notice return sorted eligible pools * @param _liquidityParams Lock liquidity params * @return pools sorted pools based on ascending order of available liquidity * @return poolBalance sorted in ascending order of available liquidity */ function getSortedEligiblePools(LiquidityParams memory _liquidityParams) public view returns (address[] memory pools, uint256[] memory poolBalance) { // if _expiration is 86401 i.e. 1 day 1 second, then max 1 day expiration pool will not be eligible IOddzLiquidityPool[] memory allPools = poolMapper[ keccak256( abi.encode( _liquidityParams._pair, _liquidityParams._type, _liquidityParams._model, periodMapper[getActiveDayTimestamp(_liquidityParams._expiration) / 1 days] ) ) ]; uint256 count = 0; for (uint8 i = 0; i < allPools.length; i++) { if (allPools[i].availableBalance() > 0) { count++; } } poolBalance = new uint256[](count); pools = new address[](count); uint256 j = 0; uint256 balance = 0; for (uint256 i = 0; i < allPools.length; i++) { if (allPools[i].availableBalance() > 0) { pools[j] = address(allPools[i]); poolBalance[j] = allPools[i].availableBalance(); balance += poolBalance[j]; j++; } } (poolBalance, pools) = _sort(poolBalance, pools); require(balance > _liquidityParams._amount, "LP Error: Amount is too large"); } /** * @notice Insertion sort based on pool balance since atmost 6 eligible pools * @param balance list of liquidity * @param pools list of pools with reference to balance * @return sorted balance list in ascending order * @return sorted pool list in ascending order of balance list */ function _sort(uint256[] memory balance, address[] memory pools) private pure returns (uint256[] memory, address[] memory) { // Higher deployment cost but betters execution cost int256 j; uint256 unsignedJ; uint256 unsignedJplus1; uint256 key; address val; for (uint256 i = 1; i < balance.length; i++) { key = balance[i]; val = pools[i]; j = int256(i - 1); unsignedJ = uint256(j); while ((j >= 0) && (balance[unsignedJ] > key)) { unsignedJplus1 = unsignedJ + 1; balance[unsignedJplus1] = balance[unsignedJ]; pools[unsignedJplus1] = pools[unsignedJ]; j--; unsignedJ = uint256(j); } unsignedJplus1 = uint256(j + 1); balance[unsignedJplus1] = key; pools[unsignedJplus1] = val; } return (balance, pools); } /** * @notice Add/update allowed max expiration * @param _maxExpiration maximum expiration time of option */ function addAllowedMaxExpiration(uint256 _maxExpiration) public onlyOwner(msg.sender) { allowedMaxExpiration[_maxExpiration] = true; } /** * @notice sets the manager for the liqudity pool contract * @param _address manager contract address * Note: This can be called only by the owner */ function setManager(address _address) external { require(_address != address(0) && _address.isContract(), "LP Error: Invalid manager address"); grantRole(MANAGER_ROLE, _address); } /** * @notice removes the manager for the liqudity pool contract for valid managers * @param _address manager contract address * Note: This can be called only by the owner */ function removeManager(address _address) external { revokeRole(MANAGER_ROLE, _address); } /** * @notice sets the timelocker for the liqudity pool contract * @param _address timelocker address * Note: This can be called only by the owner */ function setTimeLocker(address _address) external { require(_address != address(0), "LP Error: Invalid timelocker address"); grantRole(TIMELOCKER_ROLE, _address); } /** * @notice removes the timelocker for the liqudity pool contract * @param _address timelocker contract address * Note: This can be called only by the owner */ function removeTimeLocker(address _address) external { revokeRole(TIMELOCKER_ROLE, _address); } /** * @notice sets required balance * @param _reqBalance required balance between 6 and 9 * Note: This can be called only by the owner */ function setReqBalance(uint8 _reqBalance) external onlyTimeLocker(msg.sender) reqBalanceValidRange(_reqBalance) { reqBalance = _reqBalance; } /** * @notice map period * @param _source source period * @param _dest destimation period * Note: This can be called only by the owner */ function mapPeriod(uint256 _source, uint256 _dest) public validMaxExpiration(_dest) onlyTimeLocker(msg.sender) { periodMapper[_source] = _dest; } /** * @notice Map pools for an option parameters * @param _pair Asset pair address * @param _type Option type * @param _model Option premium model * @param _period option period exposure * @param _pools eligible pools based on above params * Note: This can be called only by the owner */ function mapPool( address _pair, IOddzOption.OptionType _type, bytes32 _model, uint256 _period, IOddzLiquidityPool[] memory _pools ) public onlyTimeLocker(msg.sender) { require(_pools.length <= 10, "LP Error: pools length should be <= 10"); // delete all the existing pool mapping IOddzLiquidityPool[] storage aPools = poolMapper[keccak256(abi.encode(_pair, _type, _model, _period))]; for (uint256 i = 0; i < aPools.length; i++) { delete uniquePoolMapper[keccak256(abi.encode(_pair, _type, _model, _period, aPools[i]))]; poolExposure[aPools[i]] -= 1; if (poolExposure[aPools[i]] == 0) disabledPools[aPools[i]] = true; } delete poolMapper[keccak256(abi.encode(_pair, _type, _model, _period))]; // add unique pool mapping bytes32 uPool; for (uint256 i = 0; i < _pools.length; i++) { uPool = keccak256(abi.encode(_pair, _type, _model, _period, _pools[i])); if (!uniquePoolMapper[uPool]) { poolMapper[keccak256(abi.encode(_pair, _type, _model, _period))].push(_pools[i]); uniquePoolMapper[uPool] = true; poolExposure[_pools[i]] += 1; disabledPools[_pools[i]] = false; } } } /** * @notice get active day based on user input timestamp * @param _timestamp epoch time */ function getActiveDayTimestamp(uint256 _timestamp) internal pure returns (uint256 activationDate) { // activation date should be next day 00 hours if _timestamp % 86400 is greater than 0 if ((_timestamp % 1 days) > 0) _timestamp = _timestamp + 1 days; (uint256 year, uint256 month, uint256 day) = DateTimeLibrary.timestampToDate(_timestamp); activationDate = DateTimeLibrary.timestampFromDate(year, month, day); } /** * @notice updates premium lockup duration * @param _premiumLockupDuration premium lockup duration */ function updatePremiumLockupDuration(uint256 _premiumLockupDuration) public onlyTimeLocker(msg.sender) { require( _premiumLockupDuration >= 1 days && _premiumLockupDuration <= 30 days, "LP Error: invalid premium lockup duration" ); premiumLockupDuration = _premiumLockupDuration; } /** * @notice updates move lockup duration * @param _moveLockupDuration move lockup duration */ function updateMoveLockupDuration(uint256 _moveLockupDuration) public onlyTimeLocker(msg.sender) { require( _moveLockupDuration >= 3 days && _moveLockupDuration <= 30 days, "LP Error: invalid move lockup duration" ); moveLockupDuration = _moveLockupDuration; } function setStrategyManager(address _strategyManager) public onlyOwner(msg.sender) { require(_strategyManager.isContract(), "LP Error: invalid strategy manager"); strategyManager = _strategyManager; } }
updates premium lockup duration _premiumLockupDuration premium lockup duration/
function updatePremiumLockupDuration(uint256 _premiumLockupDuration) public onlyTimeLocker(msg.sender) { require( _premiumLockupDuration >= 1 days && _premiumLockupDuration <= 30 days, "LP Error: invalid premium lockup duration" ); premiumLockupDuration = _premiumLockupDuration; }
1,042,721
./partial_match/3/0xc8C2880FA38400DDFf59519C184F151eC7eF9d27/sources/FourConnect.sol
Transfer all the accumulated fees to the owners account Prevent owner from withdrawing active bets! transfer all funds to owner
function withdraw() public { require( bet == 0, "Can only withdraw funds when there is no active game." ); require( address(this).balance > 0, "The balance is currently 0 ETH. Nothing to withdraw." ); require( msg.sender == owner, "Only the owner can withdraw funds." ); owner.transfer(address(this).balance); }
5,316,962
// SPDX-License-Identifier: MIT /// @author Nazariy Vavryk [[email protected]] - reNFT Labs [https://twitter.com/renftlabs] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; /** Holiday season NFT game. Players buy tickets to win the NFTs * in the prize pool. Every ticket buyer will win an NFT. * ------------------------------------------------------------- * RULES OF THE GAME * ------------------------------------------------------------- * 1. Players buy tickets before Jan 3rd 2021 23:59:59 GMT. * 2. Only 255 players will participate in the game. * 1. Players take turns to unwrap or steal. * 2. Each player can only steal once and be stolen from once. * 3. Each player has 3 hours to take the turn. * 4. If the player fails to take action, they lose their ability * to steal and an NFT is randomly assigned to them. */ contract Game is Ownable, ERC721Holder, VRFConsumerBase, ReentrancyGuard { event Received(address, uint256); event PrizeTransfer(address to, address nftishka, uint256 id, uint256 nftIx); struct Nft { address adr; uint256 id; } // ! there is no player at index 0 here. Starts from index 1 struct Players { address[256] addresses; mapping(address => bool) contains; uint8 numPlayers; } struct Entropies { uint256[8] vals; uint8 numEntropies; } /// @dev Chainlink related address private chainlinkVrfCoordinator = 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952; address private chainlinkLinkToken = 0x514910771AF9Ca656af840dff83E8264EcF986CA; bytes32 private chainlinkKeyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; uint256 public ticketPrice = 0.5 ether; /// @dev before this date, you can be buying tickets. After this date, unwrapping begins /// @dev 2021 January 3rd 23:59:59 GMT uint32 public timeBeforeGameStart = 1609718399; /// @dev order in which the players take turns. This gets set after gameStart once everyone has randomness associated to them /// an example of this is 231, 1, 21, 3, ...; the numbers signify the addresses at /// indices 231, 1, 3 and so on from the players array. We avoid having a map /// of indices like 1, 2, 3 and so on to addresses which are then duplicated /// as well in the players array. Note that this is 1-indexed! First player is not index 0, but 1. /// This is done such that the maps of steals "swaps" and "spaws" would not signify a player at index /// 0 (default value of uninitialised uint8). /// Interpretation of this is that if at index 0 in playersOrder we have index 3 /// then that means that player players.addresses[3] is the one to go first uint8[255] private playersOrder; /// @dev Chainlink entropies Entropies private entropies; /// this array tracks the addresses of all the players that will participate in the game /// these guys bought the ticket before `gameStart` Players public players; /// to keep track of all the deposited NFTs Nft[255] public nfts; /// address on the left stole from address on the right /// think of it as a swap of NFTs /// once again the address is the index in players array mapping(uint8 => uint8) public swaps; /// efficient reverse lookup at the expense of extra storage, forgive me mapping(uint8 => uint8) public spaws; /// for onlyOwner use only, this lets the contract know who is allowed to /// deposit the NFTs into the prize pool mapping(address => bool) public depositors; /// @dev flag that indicates if the game is ready to start /// after people bought the tickets, owners initialize the /// contract with chainlink entropy. Before this is done /// the game cannot begin bool private initComplete = false; /// @dev tracks the last time a valid steal or unwrap call was made /// this serves to signal if any of the players missed their turn /// when a player misses their turn, they forego the ability to /// steal from someone who unwrapped before them /// Initially this gets set in the initEnd by owner, when they complete /// the initialization of the game uint32 private lastAction; /// this is how much time in seconds each player has to unwrap /// or steal. If they do not act, they forego their ability /// to steal. 3 hours each player times 256 players max is 768 hours /// which equates to 32 days. uint16 public thinkTime = 10800; /// index from playersOrder of current unwrapper / stealer uint8 public currPlayer = 0; /// @dev at this point we have a way to track all of the players - players /// @dev we have the NFT that each player will win (unless stolen from) - playersOrder /// @dev we have a way to determine which NFT the player will get if stolen from - swaps /// @dev at the expense of storage, O(1) check if player was stolen from - spaws modifier beforeGameStart() { require(now < timeBeforeGameStart, "game has now begun"); _; } modifier afterGameStart() { /// @dev I have read miners can manipulate block time for up to 900 seconds /// @dev I am creating two times here to ensure that there is no overlap /// @dev To avoid a situation where both are true /// @dev 2 * 900 = 1800 gives extra cushion require(now > timeBeforeGameStart + 1800, "game has not started yet"); require(initComplete, "game has not initialized yet"); _; } modifier onlyWhitelisted() { require(depositors[msg.sender], "you are not allowed to deposit"); _; } modifier youShallNotPatheth(uint8 missed) { uint256 currTime = now; require(currTime > lastAction, "timestamps are incorrect"); uint256 elapsed = currTime - lastAction; uint256 playersSkipped = elapsed / thinkTime; // someone has skipped their turn. We track this on the front-end if (missed != 0) { require(playersSkipped > 0, "zero players skipped"); require(playersSkipped < 255, "too many players skipped"); require(playersSkipped == missed, "playersSkipped not eq missed"); require(currPlayer < 256, "currPlayer exceeds 255"); } else { require(playersSkipped == 0, "playersSkipped not zero"); } require(players.addresses[playersOrder[currPlayer + missed]] == msg.sender, "not your turn"); _; } /// Add who is allowed to deposit NFTs with this function /// All addresses that are not whitelisted will not be /// allowed to deposit. function addDepositors(address[] calldata ds) external onlyOwner { for (uint256 i = 0; i < ds.length; i++) { depositors[ds[i]] = true; } } constructor() public VRFConsumerBase(chainlinkVrfCoordinator, chainlinkLinkToken) { depositors[0x465DCa9995D6c2a81A9Be80fBCeD5a770dEE3daE] = true; depositors[0x426923E98e347158D5C471a9391edaEa95516473] = true; } function deposit(ERC721[] calldata _nfts, uint256[] calldata tokenIds) public onlyWhitelisted { require(_nfts.length == tokenIds.length, "variable lengths"); for (uint256 i = 0; i < _nfts.length; i++) { _nfts[i].transferFrom(msg.sender, address(this), tokenIds[i]); } } function buyTicket() public payable beforeGameStart nonReentrant { require(msg.value >= ticketPrice, "sent ether too low"); require(players.numPlayers < 256, "total number of players reached"); require(players.contains[msg.sender] == false, "cant buy more"); players.contains[msg.sender] = true; // !!! at 0-index we have address(0) players.addresses[players.numPlayers + 1] = msg.sender; players.numPlayers++; } /// @param missed - how many players missed their turn since lastAction function unwrap(uint8 missed) external afterGameStart nonReentrant youShallNotPatheth(missed) { currPlayer += missed + 1; lastAction = uint32(now); } /// @param _sender - index from playersOrder arr that you are stealing from /// @param _from - index from playersOrder who to steal from /// @param missed - how many players missed their turn since lastAction function steal( uint8 _sender, uint8 _from, uint8 missed ) external afterGameStart nonReentrant youShallNotPatheth(missed) { require(_sender > _from, "cant steal from someone who unwrapped after"); uint8 sender = playersOrder[_sender]; uint8 from = playersOrder[_from]; require(sender > 0, "strictly greater than zero sender"); require(from > 0, "strictly greater than zero from"); require(currPlayer + missed < 256, "its a pickle, no doubt about it"); require(players.addresses[playersOrder[currPlayer + missed]] == players.addresses[sender], "not your order"); require(players.addresses[sender] == msg.sender, "sender is not valid"); require(spaws[from] == 0, "cant steal from them again"); require(swaps[sender] == 0, "you cant steal again. You can in Verkhovna Rada."); // sender stole from swaps[sender] = from; // from was stolen by sender spaws[from] = sender; currPlayer += missed + 1; lastAction = uint32(now); } /// @param startIx - index from which to start looping the prizes /// @param endIx - index on which to end looping the prizes (exclusive) /// @dev start and end indices would be useful in case we hit /// the block gas limit, or we want to better control our transaction /// costs function finito( uint8[256] calldata op, uint8 startIx, uint8 endIx ) external onlyOwner { require(startIx > 0, "there is no player at 0"); for (uint8 i = startIx; i < endIx; i++) { uint8 playerIx = playersOrder[i - 1]; uint8 prizeIx; uint8 stoleIx = swaps[playerIx]; uint8 stealerIx = spaws[playerIx]; if (stoleIx == 0 && stealerIx == 0) { prizeIx = playersOrder[i - 1] - 1; } else if (stealerIx != 0) { prizeIx = op[stealerIx - 1]; } else { bool end = false; while (!end) { prizeIx = stoleIx; stoleIx = swaps[stoleIx]; if (stoleIx == 0) { end = true; } } prizeIx = op[prizeIx - 1]; } ERC721(nfts[prizeIx].adr).transferFrom(address(this), players.addresses[playerIx], nfts[prizeIx].id); emit PrizeTransfer(players.addresses[playerIx], nfts[prizeIx].adr, nfts[prizeIx].id, prizeIx); } } /// Will revert the safeTransfer /// on transfer nothing happens, the NFT is not added to the prize pool function onERC721Received( address, address, uint256, bytes memory ) public override returns (bytes4) { revert("we are saving you your NFT, you are welcome"); } /// we slice up Chainlink's uint256 into 32 chunks to obtain 32 uint8 vals /// each one now represents the order of the ticket buyers, which also /// represents the NFT that they will unwrap (unless swapped with) function initStart(uint8 numCalls, uint256[] calldata ourEntropy) external onlyOwner { require(initComplete == false, "cannot init start again"); require(now > timeBeforeGameStart + 1800, "game has not started yet"); require(numCalls == ourEntropy.length, "incorrect entropy size"); for (uint256 i = 0; i < numCalls; i++) { getRandomness(ourEntropy[i]); } } /// After slicing the Chainlink entropy off-chain, give back the randomness /// result here. The technique which will be used must be voiced prior to the /// game, obviously function initEnd(uint8[255] calldata _playersOrder, uint32 _lastAction) external onlyOwner { require(now > timeBeforeGameStart + 1800, "game has not started yet"); require(_playersOrder.length == players.numPlayers, "incorrect len"); playersOrder = _playersOrder; lastAction = _lastAction; initComplete = true; } /// Randomness is queried afterGameStart but before initComplete (flag) function getRandomness(uint256 ourEntropy) internal returns (bytes32 requestId) { uint256 chainlinkCallFee = 2000000000000000000; require(LINK.balanceOf(address(this)) >= chainlinkCallFee, "not enough LINK"); requestId = requestRandomness(chainlinkKeyHash, chainlinkCallFee, ourEntropy); } receive() external payable { // thanks a bunch emit Received(msg.sender, msg.value); } /// Gets called by Chainlink function fulfillRandomness(bytes32, uint256 randomness) internal override { entropies.vals[entropies.numEntropies] = randomness; entropies.numEntropies++; } function setTicketPrice(uint256 v) external onlyOwner { ticketPrice = v; } function player(uint8 i) external view returns (address, uint8) { return (players.addresses[i], players.numPlayers); } /// to avoid having the players rig the game by having this information /// to buy multiple tickts from different accounts and computing what /// NFT they will get themselves function entropy(uint8 i) external view onlyOwner returns (uint256, uint8) { return (entropies.vals[i], entropies.numEntropies); } function withdrawERC721(ERC721 nft, uint256 tokenId) external onlyOwner { nft.transferFrom(address(this), msg.sender, tokenId); } function withdrawERC20(ERC20 token) external onlyOwner { token.transfer(msg.sender, token.balanceOf(address(this))); } function withdrawEth() external onlyOwner { msg.sender.transfer(address(this).balance); } }
Will revert the safeTransfer on transfer nothing happens, the NFT is not added to the prize pool
function onERC721Received( address, address, uint256, bytes memory ) public override returns (bytes4) { revert("we are saving you your NFT, you are welcome"); }
5,470,144
// @dev - Solidity Task: Build a vanity name registering system resistant against frontrunning pragma solidity ^0.8.7; /** DEPENDENCIES */ import "Ownable.sol"; contract NameRegistrationSystem is Ownable{ /** @dev - FRONT-RUNNING SECURITY */ uint256 txCounter; /** @dev - CONSTANTS */ uint8 constant public NAME_MIN_LENGTH = 1; bytes1 constant public BYTES_DEFAULT_VALUE = bytes1(0x00); /** @dev - MAPPINGS */ // @dev - stores nameHash (bytes32) mapping (bytes32 => UserProperties) public UserList; /** @dev - STRUCTS */ // @dev - name structure struct UserProperties { bytes name; address userAddress; string nationality; } /** @dev - EVENTS */ // @dev - Logs the name registrations event LogNameRegistration( uint indexed timestamp, bytes name ); // @dev - Logs name renewals event LogNameRenew( uint indexed timestamp, bytes name, address indexed owner ); // @dev - Logs name transfers event LogNameTransfer( uint indexed timestamp, bytes name, address indexed owner, address newOwner ); /** @dev - MODIFIERS */ // @dev - Secure way to ensure the length of the name being purchased is // within the allowed parameters (NAME_MIN_LENGTH) modifier nameLengthCheck(bytes memory name) { // @dev - CHECK if the length of the name provided is allowed require( name.length >= NAME_MIN_LENGTH, "Name is too short" ); _; } // @dev - Secure way to check if the address sending the transaction // (msg.sender) owns the name modifier isNameOwner(bytes memory name) { // @dev - GET a hash of the name bytes32 nameHash = getNameHash(name); // @dev - CHECK if the msg.sender owns the name require( UserList[nameHash].userAddress == msg.sender, "You do not own this name" ); _; } // @dev - Secure way to implement the requirement of the transaction counter modifier transactionCounter(uint256 _txCounter) { // @dev - REQUIRE _txCounter to be equal to the current global txCounter _txCounter = getTxCounter(); require( _txCounter == txCounter, "Error, possible transaction order issue" ); _; } // @dev - Contract constructor constructor() { txCounter = 0; } /* * @dev - GET name hash to be used as a unique identifier * @param name * @return nameHash */ function getNameHash(bytes memory name) public pure returns(bytes32) { // @dev - RETURN keccak256 hash for name return keccak256(name); } /* * @dev - FUNCTION to return transaction counter */ function getTxCounter() public view returns (uint256) { return txCounter; } /* * @dev - FUNCTION to register name * @param name - name being registered */ function register(bytes memory name, uint256 _txCounter, string memory nationality) public nameLengthCheck(name) transactionCounter(_txCounter) { txCounter += 1; // @dev - CALCULATE name hash bytes32 nameHash = getNameHash(name); // @dev - RECORD name to storage UserList[nameHash] = UserProperties(name, msg.sender, nationality); // @dev - LogNameRegistration event emit LogNameRegistration( block.timestamp, name ); } /* * @dev - FUNCTION to renew registration on name * @param name - name being renewed */ function renewName(bytes memory name) public isNameOwner(name) { // LogNameRenew event emit LogNameRenew( block.timestamp, name, msg.sender ); } /* * @dev - Transfers name ownership * @param name - name being transferred * @param newOwner - address of the new owner */ function transferName(bytes memory name, address newOwner) public isNameOwner(name) { // @dev - Standard guard to prevent ownership being transferred to the 0x0 address require(newOwner != address(0)); // @dev - CALCULATE the hash of the current name bytes32 nameHash = getNameHash(name); // @dev - ASSIGN the names new owner UserList[nameHash].userAddress = newOwner; // @dev - LogNameTransfer event emit LogNameTransfer( block.timestamp, name, msg.sender, newOwner ); } }
- FUNCTION to register name name - name being registered/ - CALCULATE name hash - RECORD name to storage - LogNameRegistration event
function register(bytes memory name, uint256 _txCounter, string memory nationality) public nameLengthCheck(name) transactionCounter(_txCounter) { txCounter += 1; bytes32 nameHash = getNameHash(name); UserList[nameHash] = UserProperties(name, msg.sender, nationality); emit LogNameRegistration( block.timestamp, name ); }
15,827,728
./partial_match/1/0x4B44e4305B42405382b7BeC717F64D0552a9D9Fe/sources/InboxValidatorManager.sol
Unenrolls a validator from the validator set. Reverts if `_validator` is not in the validator set. _validator The validator to remove from the validator set./
function unenrollValidator(address _validator) external onlyOwner { _unenrollValidator(_validator); }
15,460,325
pragma solidity ^0.8.0; import "./freeportParts/MetaTxContext.sol"; import "./Freeport.sol"; /** The contract NFTAttachment allows users to attach objects to NFTs. * Some application can listen for the events and interpret the objects in some way. * * There are three roles who can attach objects to an NFT: * the minter, any current owner, or any anonymous account. * A different event is emitted for each role. * * The attachment data is meant to identify an object hosted externally, * such as a CID, a.k.a. Content Identifier, or a DDC URL. * The content may be retrieved from Cere DDC or some other store. */ contract NFTAttachment is /* AccessControl, */ MetaTxContext { /** This attachment contract refers to the NFT contract in this variable. */ Freeport public freeport; /** The token ID that represents the internal currency for all payments in Freeport. */ uint256 constant CURRENCY = 0; /** Set which NFT contract to refer to. * * The event `MinterAttachToNFT` is only supported for Freeport-compatible NFTs. * * The event `OwnerAttachToNFT` is supported for ERC-1155 NFTs, including Freeport. */ function initialize(Freeport _freeport) public initializer { __MetaTxContext_init(); require(address(_freeport) != address(0)); freeport = _freeport; } /** The account `minter` wished to attach data `attachment` to the NFT type `nftId`. * * The `minter` is the minter who created this NFT type, or may create it in the future if it does not exist. */ event MinterAttachToNFT( address indexed minter, uint256 indexed nftId, bytes attachment); /** The account `owner` wished to attach data `attachment` to the NFT type `nftId`. * * The `owner` owned at least one NFT of this type at the time of the event. */ event OwnerAttachToNFT( address indexed owner, uint256 indexed nftId, bytes attachment); /** The account `anonym` wished to attach data `attachment` to the NFT type `nftId`. * * There is absolutely no validation. It is the responsibility of the reader of this event to decide * who the sender is and what the attachment means. */ event AnonymAttachToNFT( address indexed anonym, uint256 indexed nftId, bytes attachment); /** Attach data `attachment` to the NFT type `nftId`, as the minter of this NFT type. * * This only works for NFT IDs in the Freeport format. */ function minterAttachToNFT(uint256 nftId, bytes calldata attachment) public { require(nftId != CURRENCY, "0 is not a valid NFT ID"); address minter = _msgSender(); address actualMinter = _minterFromNftId(nftId); require(minter == actualMinter, "Only minter"); emit MinterAttachToNFT(minter, nftId, attachment); } /** Attach data `attachment` to the NFT type `nftId`, as a current owner of an NFT of this type. * * This works for NFTs in the ERC-1155 or Freeport standards. */ function ownerAttachToNFT(uint256 nftId, bytes calldata attachment) public { require(nftId != CURRENCY, "0 is not a valid NFT ID"); address owner = _msgSender(); uint256 balance = freeport.balanceOf(owner, nftId); require(balance > 0, "Only current owner"); emit OwnerAttachToNFT(owner, nftId, attachment); } /** Attach data `attachment` to the NFT type `nftId`, as any account. */ function anonymAttachToNFT(uint256 nftId, bytes calldata attachment) public { require(nftId != CURRENCY, "0 is not a valid NFT ID"); address anonym = _msgSender(); emit AnonymAttachToNFT(anonym, nftId, attachment); } /** Parse an NFT ID into its issuer, its supply, and an arbitrary nonce. * * This does not imply that the NFTs exist. * * This is specific to Freeport NFTs. See `freeportParts/Issuance.sol` */ function _minterFromNftId(uint256 id) public pure returns (address minter) { minter = address(uint160((id & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) >> (32 + 64))); return minter; } }
Attach data `attachment` to the NFT type `nftId`, as the minter of this NFT type. This only works for NFT IDs in the Freeport format./
function minterAttachToNFT(uint256 nftId, bytes calldata attachment) public { require(nftId != CURRENCY, "0 is not a valid NFT ID"); address minter = _msgSender(); address actualMinter = _minterFromNftId(nftId); require(minter == actualMinter, "Only minter"); emit MinterAttachToNFT(minter, nftId, attachment); }
928,370
./partial_match/4/0x3c3d4e051D347f1dfDebe1F235754b6e12E01ecf/sources/InstantSwap.sol
Shows latest USDC price for given asset/ Asset Price USDC Price Converting to gram
function toToken(address assetAdd, uint256 asset) public view returns(uint256 value) { uint256 backed = getPrice(assetAdd); uint256 USDCValue = getPrice(USDC); backed = (backed / 28.35e8) * 10E8; backed = (asset * backed) / 10E10; value = (USDCValue * backed) / 10E17; }
8,620,916
pragma solidity >=0.6; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; // SPDX-License-Identifier: MIT interface IConsensus { /** * @dev delegate to a validator * @param _validator the address of the validator msg.sender is delegating to */ function delegate(address _validator) external payable; /** * @dev Function to be called when a delegator whishes to withdraw some of his staked funds for a validator * @param _validator the address of the validator msg.sender has delegating to * @param _amount the amount msg.sender wishes to withdraw from the contract */ function withdraw(address _validator, uint256 _amount) external; function delegatedAmount(address _address, address _validator) external view returns (uint256); function stakeAmount(address _address) external view returns (uint256); } contract FuseStakingV2 is Initializable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; mapping(address => uint256) public stakers; address[] public validators; IConsensus public consensus; /** * @dev initialize */ function initialize() public initializer { __Ownable_init_unchained(); consensus = IConsensus( address(0x3014ca10b91cb3D0AD85fEf7A3Cb95BCAc9c0f79) ); validators.push(address(0xcb876A393F05a6677a8a029f1C6D7603B416C0A6)); } function stake() public payable { require(msg.value > 0, "stake must be > 0"); stakeNextValidator(); stakers[msg.sender] = stakers[msg.sender].add(msg.value); } function balanceOf(address _owner) public view returns (uint256) { return stakers[_owner]; } function withdraw(uint256 _value) public returns (uint256) { uint256 toWithdraw = _value == 0 ? stakers[msg.sender] : _value; uint256 toCollect = toWithdraw; require( toWithdraw > 0 && toWithdraw <= stakers[msg.sender], "invalid withdraw amount" ); for (uint256 i = 0; i < validators.length; i++) { uint256 cur = consensus.delegatedAmount(address(this), validators[i]); if (cur == 0) continue; if (cur <= toCollect) { consensus.withdraw(validators[i], cur); toCollect = toCollect.sub(cur); } else { undelegateWithCatch(validators[i], toCollect); toCollect = 0; } if (toCollect == 0) break; } // in case some funds where not withdrawn if (toWithdraw > balance()) { toWithdraw = balance(); } stakers[msg.sender] = stakers[msg.sender].sub(toWithdraw); if (toWithdraw > 0) payable(msg.sender).transfer(toWithdraw); return toWithdraw; } function stakeNextValidator() public { require(validators.length > 0, "no approved validators"); uint256 min = consensus.delegatedAmount(address(this), validators[0]); uint256 minIdx = 0; for (uint256 i = 1; i < validators.length; i++) { uint256 cur = consensus.delegatedAmount(address(this), validators[i]); if (cur < min) minIdx = i; } uint256 balance = payable(address(this)).balance; consensus.delegate{ value: balance }(validators[minIdx]); } function addValidator(address _v) public onlyOwner { validators.push(_v); } function totalDelegated() public view returns (uint256) { uint256 total = 0; for (uint256 i = 0; i < validators.length; i++) { uint256 cur = consensus.delegatedAmount(address(this), validators[i]); total = total.add(cur); } return total; } function removeValidator(address _validator) public onlyOwner { uint256 delegated = consensus.delegatedAmount(address(this), _validator); if (delegated > 0) { uint256 prevBalance = balance(); undelegateWithCatch(_validator, delegated); // wasnt withdrawn because validator needs to be taken of active validators if (balance() == prevBalance) { // pendingValidators.push(_validator); return; } } for (uint256 i = 0; i < validators.length; i++) { if (validators[i] == _validator) { if (i < validators.length - 1) validators[i] = validators[validators.length - 1]; validators.pop(); break; } } } function undelegateWithCatch(address _validator, uint256 _amount) internal returns (bool) { try consensus.withdraw(_validator, _amount) { return true; } catch Error( string memory /*reason*/ ) { // This is executed in case // revert was called inside getData // and a reason string was provided. return false; } catch ( bytes memory /*lowLevelData*/ ) { // This is executed in case revert() was used // or there was a failing assertion, division // by zero, etc. inside getData. return false; } } function balance() internal view returns (uint256) { return payable(address(this)).balance; } receive() external payable {} }
wasnt withdrawn because validator needs to be taken of active validators pendingValidators.push(_validator);
function removeValidator(address _validator) public onlyOwner { uint256 delegated = consensus.delegatedAmount(address(this), _validator); if (delegated > 0) { uint256 prevBalance = balance(); undelegateWithCatch(_validator, delegated); if (balance() == prevBalance) { return; } } for (uint256 i = 0; i < validators.length; i++) { if (validators[i] == _validator) { if (i < validators.length - 1) validators[i] = validators[validators.length - 1]; validators.pop(); break; } } }
12,874,668
./full_match/1/0xC53a66E45D3aA5558Ff322D18c4227fD63E2C8e2/sources/contracts/vault/modules/adminModule/main.sol
Auth can update the revenue and withdrawal fee percentage. revenueFeePercent_ New revenue fee percentage, scaled to factor 4. i.e 1e6 = 100%, 1e4 = 1% withdrawalFeePercent_ New withdrawal fee percentage, scaled to factor 4. i.e 1e6 = 100%, 1e4 = 1% withdrawFeeAbsoluteMin_ New withdraw fee absolute. 1 ETH = 1e18, 0.01 = 1e16
function updateFees( uint256 revenueFeePercent_, uint256 withdrawalFeePercent_, uint256 withdrawFeeAbsoluteMin_ ) public onlyAuth { if (revenueFeePercentage > 1e6 || withdrawalFeePercentage > 1e6) { revert AdminModule__NotValidRevenueFee(); } revenueFeePercentage = revenueFeePercent_; withdrawalFeePercentage = withdrawalFeePercent_; withdrawFeeAbsoluteMin = withdrawFeeAbsoluteMin_; emit LogUpdateFees( revenueFeePercent_, withdrawalFeePercent_, withdrawFeeAbsoluteMin_ ); }
9,612,435
./partial_match/3/0xE333bacb250b1aDC74074d4DBf13662c6Bd96172/sources/GoldenGoose.sol
Transfer tokens to a specified address (For Only Owner) to The address to transfer to. value The amount to be transferred. return Transfer status in true or false/
function transferByOwner(address to, uint256 value, uint256 lockingTime) public AllTransfersLockStatus onlyOwner returns (bool) { addLockingTime(to,lockingTime,value); _transfer(msg.sender, to, value); return true; }
5,077,833
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./dexes/nft20/Nft20Router.sol"; import "./dexes/uniswap/UniswapRouter.sol"; contract NFT20Swapper is IERC721Receiver, IERC1155Receiver, Ownable, UniswapRouter, Nft20Router { struct ERC20Details { address[] tokenAddrs; uint256[] amounts; } struct ERC721Details { address[] tokenAddrs; uint256[] ids; } struct ERC1155Details { address tokenAddr; uint256[] ids; uint256[] amounts; } function _swapExactERC20ForETH( address _from, address _recipient, uint256 _amountIn ) internal virtual returns (uint256[] memory amount) { return _swapExactERC20ForETHViaUniswap(_from, _recipient, _amountIn); } function _swapETHForExactERC20( address _to, address _recipient, uint256 _amountOut ) internal virtual/* returns (uint256[] memory amount) */ { _swapETHForExactERC20ViaUniswap(_to, _recipient, _amountOut); } function _swapExactETHForERC20( address _to, address _recipient, uint256 _amountOutMin ) internal virtual /* returns (uint256[] memory amount) */ { _swapExactETHForERC20ViaUniswap(_to, _recipient, _amountOutMin); } function _swapExactERC20ForERC20(address _from, address _to, address _recipient) internal virtual returns (uint256[] memory amount) { return _swapExactERC20ForERC20ViaUniswap(_from, _to, _recipient); } function _swapERC20ForExactERC20(address _from, address _to, address _recipient, uint256 _amountOut) internal virtual returns (uint256[] memory amount) { return _swapERC20ForExactERC20ViaUniswap(_from, _to, _recipient, _amountOut); } // swaps any combination of ERC-20/721/1155 // User needs to approve assets before invoking swap function swap( ERC20Details calldata inputERC20s, ERC721Details calldata inputERC721s, ERC1155Details calldata inputERC1155s, ERC20Details calldata outputERC20s, ERC721Details calldata outputERC721s, ERC1155Details calldata outputERC1155s, address changeIn ) external { // transfer ERC20 tokens from the sender to this contract for (uint256 i = 0; i < inputERC20s.tokenAddrs.length; i++) { // Transfer ERC20 to the contract IERC20(inputERC20s.tokenAddrs[i]).transferFrom( msg.sender, address(this), inputERC20s.amounts[i] ); // Swap ERC20 for ETH _swapExactERC20ForETH(inputERC20s.tokenAddrs[i], address(this), inputERC20s.amounts[i]); } // transfer ERC721 tokens from the sender to this contract // WARNING: It is assumed that the ERC721 token addresses are NOT malicious uint256[] memory _id = new uint256[](1); for (uint256 i = 0; i < inputERC721s.tokenAddrs.length; i++) { // Transfer ERC721 to the contract IERC721(inputERC721s.tokenAddrs[i]).transferFrom( msg.sender, address(this), inputERC721s.ids[i] ); _id[0] = inputERC721s.ids[i]; // Swap ERC721(s) for eq. ERC20(s) (address _erc20Addr, ) = _swapERC721ForERC20EquivalentViaNft20(inputERC721s.tokenAddrs[i], _id); // Swap eq. ERC20 for ETH _swapExactERC20ForETH(_erc20Addr, address(this), 95*10**18); } // transfer ERC1155 tokens from the sender to this contract // WARNING: It is assumed that the ERC1155 token addresses are NOT malicious IERC1155(inputERC1155s.tokenAddr).safeBatchTransferFrom( msg.sender, address(this), inputERC1155s.ids, inputERC1155s.amounts, "" ); // Swap ERC1155(s) for eq. ERC20(s) _swapERC1155BatchForERC20EquivalentViaNft20(inputERC1155s.tokenAddr, inputERC1155s.ids, inputERC1155s.amounts); uint256 totalAmount = 0; for (uint256 i = 0; i < inputERC1155s.amounts.length; i++) { totalAmount = totalAmount.add(inputERC1155s.amounts[i]); } // Swap eq. ERC20 for ETH _swapExactERC20ForETH(nftToErc20[inputERC1155s.tokenAddr], address(this), totalAmount.mul(10).mul(10**18)); // Swap ETH to ERC721(s) for(uint256 i = 0; i < outputERC721s.tokenAddrs.length; i++) { _id[0] = outputERC721s.ids[i]; _swapETHForERC721(outputERC721s.tokenAddrs[i], _id, address(0), msg.sender); } // Swap ETH to ERC1155(s) _swapETHForERC1155(outputERC1155s.tokenAddr, outputERC1155s.ids, outputERC1155s.amounts, address(0), msg.sender); // Swap ETH to ERC20(s) for(uint256 i = 0; i < outputERC20s.tokenAddrs.length; i++) { _swapETHForExactERC20(outputERC20s.tokenAddrs[i], msg.sender, outputERC20s.amounts[i]); } // check if the user wants the change in ETH if(changeIn == ETH) { // Return the change ETH back (bool success, ) = msg.sender.call{value:address(this).balance}(""); require(success, "swap: ETH dust transfer failed."); } else { // Return the change in desired ERC20 back _swapExactETHForERC20(changeIn, msg.sender, 0); } } // converts ETH to ERC721(s) and returns change in changeIn ERC20 function swapEthForERC721( address toNft, uint256[] calldata toIds, address changeIn ) virtual external payable { _swapETHForERC721(toNft, toIds, changeIn, msg.sender); } function _swapETHForERC721( address _toNft, uint256[] memory _toIds, address _changeIn, address _recipient ) virtual internal { // ETH -> eq. ERC20 -> ERC721(s) // Convert ETH to eq. ERC20 _swapETHForExactERC20( nftToErc20[_toNft], address(this), _toIds.length*NFT20_NFT_VALUE ); uint256[] memory amounts; // Convert eq. ERC20 to ERC721(s) _swapERC20EquivalentForNFTViaNft20(nftToErc20[_toNft], _toIds, amounts, _recipient); // check if the user wants the change in ETH if(_changeIn == ETH) { // Return the change ETH back (bool success, ) = _recipient.call{value:address(this).balance}(""); require(success, "swapEthForERC721: ETH dust transfer failed."); } else if (_changeIn == address(0)) {} else { // Return the change in desired ERC20 back _swapExactETHForERC20(_changeIn, _recipient, 0); } } // converts ETH to ERC1155(s) and returns change in changeIn ERC20 function swapEthForERC1155( address toNft, uint256[] calldata toIds, uint256[] calldata toAmounts, address changeIn ) virtual external payable { _swapETHForERC1155(toNft, toIds, toAmounts, changeIn, msg.sender); } function _swapETHForERC1155( address _toNft, uint256[] calldata _toIds, uint256[] calldata _toAmounts, address _changeIn, address _recipient ) virtual internal { // ETH -> eq. ERC20 -> ERC1155(s) // Calculate the total amount needed uint256 totalAmount = 0; for (uint256 i = 0; i < _toAmounts.length; i++) { totalAmount = totalAmount.add(_toAmounts[i]); } // ETH -> Eq. ERC20 _swapETHForExactERC20(nftToErc20[_toNft], address(this), totalAmount*NFT20_NFT_VALUE); // Convert eq. ERC20 to ERC721(s) _swapERC20EquivalentForNFTViaNft20(nftToErc20[_toNft], _toIds, _toAmounts, _recipient); // check if the user wants the change in ETH if(_changeIn == ETH) { // Return the change ETH back (bool success, ) = _recipient.call{value:address(this).balance}(""); require(success, "swapEthForERC721: ETH dust transfer failed."); } else if (_changeIn == address(0)) {} else { // Return the change in desired ERC20 back _swapExactETHForERC20(_changeIn, _recipient, 0); } } // User needs to approve ERC20 tokens function swapERC20ForERC721( ERC20Details calldata fromERC20s, address toNft, uint256[] calldata toIds, address changeIn ) virtual external { // ERC20 -> ETH -> Eq. ERC20 -> ERC721 // Transfer the ERC20s to this contract for(uint256 i = 0; i < fromERC20s.tokenAddrs.length; i++) { IERC20(fromERC20s.tokenAddrs[i]).transferFrom(msg.sender, address(this), fromERC20s.amounts[i]); // ERC20 -> ETH _swapExactERC20ForETH(fromERC20s.tokenAddrs[i], address(this), fromERC20s.amounts[i]); } // ETH -> Eq. ERC20 _swapETHForExactERC20(nftToErc20[toNft], address(this), toIds.length*NFT20_NFT_VALUE); uint256[] memory amounts; // Eq. ERC20 -> ERC721 _swapERC20EquivalentForNFTViaNft20( nftToErc20[toNft], toIds, amounts, msg.sender ); // Return the dust in changeIn asset if ETH balance is greater than 0 if(address(this).balance > 0) { if(changeIn != ETH) { _swapExactETHForERC20(changeIn, msg.sender, 0); } else { // Transfer remaining ETH to the msg.sender (bool success, ) = msg.sender.call{value:address(this).balance}(""); require(success, "swapERC20ForERC721: ETH dust transfer failed."); } } } function swapERC20ForERC1155( ERC20Details calldata fromERC20s, address toNft, uint256[] calldata toIds, uint256[] calldata toAmounts, address changeIn //uint256[] calldata toVaultIds, ) virtual external { // ERC20 -> WETH -> Eq. ERC20 -> ERC1155 // Transfer the ERC20s to this contract for(uint256 i = 0; i < fromERC20s.tokenAddrs.length; i++) { IERC20(fromERC20s.tokenAddrs[i]).transferFrom(msg.sender, address(this), fromERC20s.amounts[i]); // ERC20 -> WETH _swapExactERC20ForETH(fromERC20s.tokenAddrs[i], address(this), fromERC20s.amounts[i]); } uint256 totalAmount = 0; for (uint256 i = 0; i < toAmounts.length; i++) { totalAmount = totalAmount.add(toAmounts[i]); } // WETH -> Eq. ERC20 _swapETHForExactERC20(nftToErc20[toNft], address(this), totalAmount*NFT20_NFT_VALUE); // Eq. ERC20 -> ERC1155 _swapERC20EquivalentForNFTViaNft20( nftToErc20[toNft], toIds, toAmounts, msg.sender ); // Return the dust in changeIn asset if ETH balance is greater than 0 if(address(this).balance > 0) { if(changeIn != ETH) { _swapExactETHForERC20(changeIn, msg.sender, 0); } else { // Transfer remaining ETH to the msg.sender (bool success, ) = msg.sender.call{value:address(this).balance}(""); require(success, "swapERC20ForERC1155: ETH dust transfer failed."); } } } function onERC1155Received( address, address, uint256, uint256, bytes calldata ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function _receivedCoreLogic( address _erc20Address, address _from, address[] memory _decodedAddrs, uint256[] memory _toIds, uint256[] memory _toAmounts ) internal { // Check we want to convert to another NFT if (_decodedAddrs[0] == address(0)) { if (_erc20Address != _decodedAddrs[1]) { if(_decodedAddrs[1] == ETH) { // Convert all the _erc20Amount to _changeIn ERC20 _swapExactERC20ForETH(_erc20Address, _from, IERC20(_erc20Address).balanceOf(address(this))); } else { // Convert all the _erc20Amount to _changeIn ERC20 _swapExactERC20ForERC20(_erc20Address, _decodedAddrs[1], _from); } } else { IERC20(_decodedAddrs[1]).transfer(_from, IERC20(_decodedAddrs[1]).balanceOf(address(this))); } } else { // convert ERC20 equivalent to desired ERC20 equivalent _swapExactERC20ForERC20(_erc20Address, nftToErc20[_decodedAddrs[0]], address(this)); // convert desired ERC20 equivalent to desired NFTs _swapERC20EquivalentForNFTViaNft20( nftToErc20[_decodedAddrs[0]], _toIds, _toAmounts, _from ); // Handle special cases where we cannot directly send NFTs to the recipient if( _decodedAddrs[0] == 0x7CdC0421469398e0F3aA8890693d86c840Ac8931 || // Doki Doki _decodedAddrs[0] == 0x89eE76cC25Fcbf1714ed575FAa6A10202B71c26A || // Node Runners _decodedAddrs[0] == 0xC805658931f959abc01133aa13fF173769133512 // Chonker Finance ) { IERC1155(_decodedAddrs[0]).safeBatchTransferFrom(address(this), _from, _toIds, _toAmounts, ""); } // convert remaining desired ERC20 equivalent to desired change if (nftToErc20[_decodedAddrs[0]] != _decodedAddrs[1]) { if(_decodedAddrs[1] == ETH) { // Convert all the _erc20Amount to _changeIn ERC20 _swapExactERC20ForETH(nftToErc20[_decodedAddrs[0]], _from, IERC20(nftToErc20[_decodedAddrs[0]]).balanceOf(address(this))); } else { // Convert all the _erc20Amount to _changeIn ERC20 _swapExactERC20ForERC20(nftToErc20[_decodedAddrs[0]], _decodedAddrs[1], _from); } } else { IERC20(_decodedAddrs[1]).transfer(_from, IERC20(_decodedAddrs[1]).balanceOf(address(this))); } } } function onERC1155BatchReceived( address, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data // (address[] _decodedAddrs, uint256[] _toIds, uint256[] _toAmounts) ) public virtual override returns (bytes4) { // return with function selector if data is empty if(keccak256(abi.encodePacked((_data))) == keccak256(abi.encodePacked(("")))) { return this.onERC1155BatchReceived.selector; } // decode the swap details address[] memory _decodedAddrs; // [toNft, changeIn] uint256[] memory _toIds; uint256[] memory _toAmounts; (_decodedAddrs, _toIds, _toAmounts) = abi.decode( _data, (address[], uint256[], uint256[]) ); // Convert ERC1155 to its ERC20 equivalent (address _erc20Address,) = _swapERC1155BatchForERC20EquivalentViaNft20( msg.sender, _ids, _values ); _receivedCoreLogic(_erc20Address, _from, _decodedAddrs, _toIds, _toAmounts); // return with function selector return this.onERC1155BatchReceived.selector; } function onERC721Received( address, address _from, uint256 _tokenId, bytes calldata _data // (address[] _decodedAddrs, uint256[] _toIds, uint256[] _toAmounts) ) external virtual override returns (bytes4) { // return with function selector if data is empty if(keccak256(abi.encodePacked((_data))) == keccak256(abi.encodePacked(("")))) { return this.onERC721Received.selector; } // decode the swap details address[] memory _decodedAddrs; // [toNft, changeIn] uint256[] memory _toIds; uint256[] memory _toAmounts; ( _decodedAddrs, _toIds, _toAmounts ) = abi.decode( _data, (address[], uint256[], uint256[]) ); uint256[] memory _fromIds = new uint256[](1); _fromIds[0] = _tokenId; // Convert ERC721 to its ERC20 equivalent (address _erc20Address, ) = _swapERC721ForERC20EquivalentViaNft20( msg.sender, _fromIds ); _receivedCoreLogic(_erc20Address, _from, _decodedAddrs, _toIds, _toAmounts); // return with function selector return this.onERC721Received.selector; } function supportsInterface(bytes4 interfaceId) external virtual override view returns (bool) { return interfaceId == this.supportsInterface.selector; } // Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC20(address asset, address recipient) onlyOwner external returns(uint256 amountRescued) { amountRescued = IERC20(asset).balanceOf(address(this)); IERC20(asset).transfer(recipient, amountRescued); } // Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC721(asset).transferFrom(address(this), recipient, ids[i]); } } // Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally // Only owner can retrieve the asset balance to a recipient address function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external { for (uint256 i = 0; i < ids.length; i++) { IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], ""); } } receive() external payable {} }
ETH -> eq. ERC20 -> ERC1155(s) Calculate the total amount needed check if the user wants the change in ETH Return the change ETH back Return the change in desired ERC20 back
function _swapETHForERC1155( address _toNft, uint256[] calldata _toIds, uint256[] calldata _toAmounts, address _changeIn, address _recipient ) virtual internal { uint256 totalAmount = 0; for (uint256 i = 0; i < _toAmounts.length; i++) { totalAmount = totalAmount.add(_toAmounts[i]); } if(_changeIn == ETH) { require(success, "swapEthForERC721: ETH dust transfer failed."); } else { _swapExactETHForERC20(_changeIn, _recipient, 0); } }
12,536,739
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol"; /// @title Cryptographic utilities. library CryptoUtils { uint8 public constant UNCOMPRESSED_PUBLIC_KEY_SIZE = 64; /// @dev Verifies ECDSA signature of a given message hash. /// @param _hash bytes32 The hash which is the signed message. /// @param _signature bytes The signature to verify. /// @param _address The public address of the signer (allegedly). function isSignatureValid(bytes32 _hash, bytes _signature, address _address) public pure returns (bool) { if (_address == address(0)) { return false; } address recovered = ECDSA.recover(_hash, _signature); return recovered != address(0) && recovered == _address; } /// @dev Converts a public key to an address. /// @param _publicKey bytes32 The uncompressed public key. function toAddress(bytes _publicKey) public pure returns (address) { if (_publicKey.length != UNCOMPRESSED_PUBLIC_KEY_SIZE) { return address(0); } return address(keccak256(_publicKey)); } /// @dev Verifies the Merkle proof for the existence of a specific data. Please not that that this implementation /// assumes that each pair of leaves and each pair of pre-images are sorted (see tests for examples of /// construction). /// @param _proof bytes32[] The Merkle proof containing sibling SHA256 hashes on the branch from the leaf to the /// root. /// @param _root bytes32 The Merkle root. /// @param _leaf bytes The data to check. function isMerkleProofValid(bytes32[] _proof, bytes32 _root, bytes _leaf) public pure returns (bool) { return isMerkleProofValid(_proof, _root, sha256(_leaf)); } /// @dev Verifies the Merkle proof for the existence of a specific data. Please not that that this implementation /// assumes that each pair of leaves and each pair of pre-images are sorted (see tests for examples of /// construction). /// @param _proof bytes32[] The Merkle proof containing sibling SHA256 hashes on the branch from the leaf to the /// root. /// @param _root bytes32 The Merkle root. /// @param _leafHash bytes32 The hash of the data to check. function isMerkleProofValid(bytes32[] _proof, bytes32 _root, bytes32 _leafHash) public pure returns (bool) { bytes32 computedHash = _leafHash; for (uint256 i = _proof.length; i > 0; i--) { bytes32 proofElement = _proof[i-1]; if (computedHash < proofElement) { // Hash the current computed hash with the current element of the proof. computedHash = sha256(abi.encodePacked(computedHash, proofElement)); } else { // Hash the current element of the proof with the current computed hash. computedHash = sha256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root. return computedHash == _root; } }
Verifies the Merkle proof for the existence of a specific data. Please not that that this implementation assumes that each pair of leaves and each pair of pre-images are sorted (see tests for examples of construction). _proof bytes32[] The Merkle proof containing sibling SHA256 hashes on the branch from the leaf to the root. _root bytes32 The Merkle root. _leaf bytes The data to check.
function isMerkleProofValid(bytes32[] _proof, bytes32 _root, bytes _leaf) public pure returns (bool) { return isMerkleProofValid(_proof, _root, sha256(_leaf)); }
892,315
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; abstract contract IDFSRegistry { function getAddr(bytes32 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } interface IERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { 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); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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 { 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; } } 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _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) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } contract AdminVault { address public owner; address public admin; constructor() { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { require(admin == msg.sender, "msg.sender not admin"); owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { require(admin == msg.sender, "msg.sender not admin"); admin = _admin; } } contract AdminAuth { using SafeERC20 for IERC20; address public constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD; AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR); modifier onlyOwner() { require(adminVault.owner() == msg.sender, "msg.sender not owner"); _; } modifier onlyAdmin() { require(adminVault.admin() == msg.sender, "msg.sender not admin"); _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log( address _contract, address _caller, string memory _logName, bytes memory _data ) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } } abstract contract ActionBase is AdminAuth { address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C; DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value"; string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value"; /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (address)); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32)); } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE); return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE); return (_type - SUB_MIN_INDEX_VALUE); } } abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } interface IERC3156FlashBorrower { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } interface IERC3156FlashLender { /** * @dev The amount of currency available to be lent. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee( address token, uint256 amount ) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } contract StrategyData { struct Template { string name; bytes32[] triggerIds; bytes32[] actionIds; uint8[][] paramMapping; } struct Task { string name; bytes[][] callData; bytes[][] subData; bytes32[] actionIds; uint8[][] paramMapping; } struct Strategy { uint templateId; address proxy; bytes[][] subData; bytes[][] triggerData; bool active; uint posInUserArr; } } abstract contract IDSProxy { // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address, bytes32); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32); function setCache(address _cacheAddr) public payable virtual returns (bool); function owner() public view virtual returns (address); } abstract contract IFLParamGetter { function getFlashLoanParams(bytes memory _data) public view virtual returns ( address[] memory tokens, uint256[] memory amount, uint256[] memory modes ); } abstract contract IWETH { function allowance(address, address) public virtual view returns (uint256); function balanceOf(address) public virtual view returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { _amount = getBalance(_token, _from); } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } contract FLMaker is ActionBase, ReentrancyGuard, IERC3156FlashBorrower { using TokenUtils for address; using SafeMath for uint256; address public constant DSS_FLASH_ADDR = 0x1EB4CF3A948E7D72A198fe073cCb8C7a948cD853; address public constant DAI_ADDR = 0x6B175474E89094C44Da98b954EedeAC495271d0F; /// @dev Function sig of TaskExecutor._executeActionsFromFL() bytes4 public constant CALLBACK_SELECTOR = 0xd6741b9e; bytes32 constant TASK_EXECUTOR_ID = keccak256("TaskExecutor"); bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); struct Params { uint256 amount; // Amount of DAI to flash loan address flParamGetterAddr; // On-chain contract used for piping FL action parameters bytes flParamGetterData; // Data to supply to flParamGetter } function executeAction( bytes[] memory _callData, bytes[] memory, uint8[] memory, bytes32[] memory ) public override payable returns (bytes32) { Params memory params = parseInputs(_callData); if (params.flParamGetterAddr != address(0)) { (, uint256[] memory amounts,) = IFLParamGetter(params.flParamGetterAddr).getFlashLoanParams(params.flParamGetterData); params.amount = amounts[0]; } bytes memory taskData = _callData[_callData.length - 1]; uint256 amount = _flMaker(params.amount, taskData); return bytes32(amount); } // solhint-disable-next-line no-empty-blocks function executeActionDirect(bytes[] memory _callData) public override payable {} /// @inheritdoc ActionBase function actionType() public override pure returns (uint8) { return uint8(ActionType.FL_ACTION); } /// @notice Gets a DAI flash loan from Maker and returns back the execution to the action address /// @param _amount Amount of DAI to FL /// @param _taskData Rest of the data we have in the task function _flMaker(uint256 _amount, bytes memory _taskData) internal returns (uint256) { IERC3156FlashLender(DSS_FLASH_ADDR).flashLoan( IERC3156FlashBorrower(address(this)), DAI_ADDR, _amount, _taskData ); logger.Log( address(this), msg.sender, "FLMaker", abi.encode( _amount ) ); return _amount; } /// @notice ERC3156 callback function that formats and calls back TaskExecutor function onFlashLoan( address _initiator, address _token, uint256 _amount, uint256 _fee, bytes calldata _data ) external override nonReentrant returns (bytes32) { require(msg.sender == address(DSS_FLASH_ADDR), "Untrusted lender"); require(_initiator == address(this), "Untrusted loan initiator"); (StrategyData.Task memory currTask, address proxy) = abi.decode(_data, (StrategyData.Task, address)); _token.withdrawTokens(proxy, _amount); address payable taskExecutor = payable(registry.getAddr(TASK_EXECUTOR_ID)); uint256 paybackAmount = _amount.add(_fee); // call Action execution IDSProxy(proxy).execute{value: address(this).balance}( taskExecutor, abi.encodeWithSelector(CALLBACK_SELECTOR, currTask, paybackAmount) ); require(_token.getBalance(address(this)) == paybackAmount, "Wrong payback amount"); _token.approveToken(DSS_FLASH_ADDR, paybackAmount); return CALLBACK_SUCCESS; } function parseInputs(bytes[] memory _callData) public pure returns (Params memory params) { params = abi.decode(_callData[0], (Params)); } }
ERC3156 callback function that formats and calls back TaskExecutor call Action execution
function onFlashLoan( address _initiator, address _token, uint256 _amount, uint256 _fee, bytes calldata _data ) external override nonReentrant returns (bytes32) { require(msg.sender == address(DSS_FLASH_ADDR), "Untrusted lender"); require(_initiator == address(this), "Untrusted loan initiator"); (StrategyData.Task memory currTask, address proxy) = abi.decode(_data, (StrategyData.Task, address)); _token.withdrawTokens(proxy, _amount); address payable taskExecutor = payable(registry.getAddr(TASK_EXECUTOR_ID)); uint256 paybackAmount = _amount.add(_fee); taskExecutor, abi.encodeWithSelector(CALLBACK_SELECTOR, currTask, paybackAmount) ); require(_token.getBalance(address(this)) == paybackAmount, "Wrong payback amount"); _token.approveToken(DSS_FLASH_ADDR, paybackAmount); return CALLBACK_SUCCESS; }
10,299,111
./partial_match/5/0xB4A96AF88fF6F621D345C4812A8dB5C27688737F/sources/DigitalaxGenesisStaking.sol
Lets a user with rewards owing to claim tokens
function claimReward( address _user ) public { require( tokensClaimable == true, "Tokens cannnot be claimed yet" ); updateReward(_user); Staker storage staker = stakers[_user]; uint256 payableAmount = staker.rewardsEarned.sub(staker.rewardsReleased); staker.rewardsReleased = staker.rewardsReleased.add(payableAmount); rewardsToken.transfer(_user, payableAmount); emit RewardPaid(_user, payableAmount); }
16,862,827
pragma solidity ^0.4.21; /// @title A mortality base contract for destroyable contracts. /// @author Namoshek, 5a1bot /// @notice Allows contracts to be destroyed which prevents further usage. /// @dev The creator of a contract is also the owner. Ownership cannot be transferred. Only the owner can destroy a contract. contract Mortal { address owner; /// @dev Sets the transaction sender as owner of the contract. constructor() public { owner = msg.sender; } event ContractOwnershipChanged(address indexed oldOwner, address indexed newOwner); modifier isOwner { require(msg.sender == owner); _; } modifier noBalance { require(address(this).balance == 0); _; } /// @notice Can be used to destroy the contract. /// @dev Can only be executed by the owner of the contract. The contract may not hold any Ether. function kill() public isOwner noBalance { selfdestruct(owner); } /// @notice Can be used to transfer ownership of the contract to another wallet. /// @dev Can only be executed by the owner of the contract. Once the ownership is transfered, the old /// owner does not have access to the contract anymore. function transferOwnership(address newOwner) public isOwner { owner = newOwner; emit ContractOwnershipChanged(msg.sender, newOwner); } } /// @title A coffee economy contract to manage customers, coffee makers and transactions in between them. /// @author Namoshek, 5a1bot /// @notice Offers functionality to add wallets as customer and coffee maker, to add coffee programs to coffee makers, /// to buy tokens and to buy coffee for these tokens. Also token transfers in between parties are possible. /// @dev Expects to be run in an environment with infinite Ether due to high transaction costs. Also expects some /// trusted parties are available that will be able to trade real-world money for coffee tokens and the other way round. contract CoffeeMakerEconomy is Mortal { enum MachineType { Capsules, Pads, Filter, Pulver, FullyAutomatic, VendingMachine } struct Location { string descriptive; string department; string latitude; string longitude; } struct MachineInfo { MachineType machineType; string description; } struct CoffeeProgram { string name; uint price; } struct CoffeeMaker { bool exists; address owner; string name; Location location; MachineInfo machineInfo; mapping(uint8 => CoffeeProgram) programs; uint8 programCounter; } struct Customer { bool exists; string name; string department; string telephone; string email; } /// @dev Sets the transaction sender as the initially only available authorized exchange party. constructor() public { authorizedExchangeWallets[msg.sender] = true; } uint constant tokensPerEther = 100; mapping(address => uint) tokenStore; mapping(address => CoffeeMaker) private coffeeMakers; mapping(address => Customer) private customers; mapping(address => bool) private authorizedExchangeWallets; event ExchangeWalletAuthorized(address indexed wallet); event CustomerAdded(address indexed wallet); event CoffeeMakerAdded(address indexed wallet, address indexed owner); event CoffeeMakerProgramAdded(address indexed coffeeMaker, string indexed name, uint indexed price); event CoffeeBought(address indexed coffeeMaker, uint8 indexed program, uint8 indexed amount); event TokensBought(address indexed customer, uint indexed tokens); event TokensSold(address indexed customer, uint indexed tokens); event TokensTransfered(address indexed sender, address indexed recipient, uint indexed tokens); modifier isAuthorizedWallet { require(authorizedExchangeWallets[msg.sender] == true); _; } modifier walletIsKnown(address wallet) { require(customers[wallet].exists == true || coffeeMakers[wallet].exists == true); _; } /// @notice Adds a wallet as authorized exchange wallet, which allows the wallet to trade real-world money for tokens. /// @dev A wallet should only be authorized as exchange wallet if the owner is trusted. Otherwise, an infinite amount of /// coffee tokens could be created. /// @param wallet The wallet to be added as authorized exchange wallet. function addAuthorizedExchangeWallet(address wallet) public { require(msg.sender == owner); authorizedExchangeWallets[wallet] = true; emit ExchangeWalletAuthorized(wallet); } /// @notice Adds a customer for the given wallet with some basic personal information like name and contact details. /// @dev This function may only be called if no customer exists yet for the given wallet. /// @param wallet The wallet to be added as customer. /// @param name The customers name. /// @param telephone The customers telephone number. /// @param email The customers email address. function addCustomer(address wallet, string name, string department, string telephone, string email) public { require(wallet != 0x0); require(customers[wallet].exists == false); Customer memory details; details.exists = true; details.name = name; details.department = department; details.telephone = telephone; details.email = email; customers[wallet] = details; emit CustomerAdded(wallet); } /// @notice Adds a coffee maker for the given wallet with some basic machine information like location and machine type. /// @dev This function may only be called if no coffee maker exists yet for the given wallet. The message sender must be a customer. /// @param wallet The wallet to be added as coffee maker. /// @param name The coffee makers name. /// @param locDescriptive A description of the coffee makers location. /// @param locDepartment The department name where the coffee maker is located. /// @param locLatitude The latitude of the coffee makers location. /// @param locLongitude The longitude of the coffee makers location. /// @param infoMachineType The machine type of the coffee maker. /// @param infoDescription An additional description. function addCoffeemaker( address wallet, string name, string locDescriptive, string locDepartment, string locLatitude, string locLongitude, MachineType infoMachineType, string infoDescription ) public { require(wallet != 0x0); require(coffeeMakers[wallet].exists == false); require(customers[msg.sender].exists == true); CoffeeMaker memory details; details.exists = true; details.owner = msg.sender; details.name = name; details.location.descriptive = locDescriptive; details.location.department = locDepartment; details.location.latitude = locLatitude; details.location.longitude = locLongitude; details.machineInfo.machineType = infoMachineType; details.machineInfo.description = infoDescription; coffeeMakers[wallet] = details; emit CoffeeMakerAdded(wallet, details.owner); } /// @notice Adds a coffee program to an existing coffee maker. /// @dev This function may only be called for existing coffee makers. Only 256 programs per coffee maker are possible. /// @param coffeeMaker The address of a coffee maker. /// @param name The coffee program name (e.g. Espresso). /// @param price The price for the coffee program. function addCoffeeMakerProgram(address coffeeMaker, string name, uint price) public { require(coffeeMakers[coffeeMaker].exists == true); require(coffeeMakers[coffeeMaker].programCounter < 256); uint8 programCounter = coffeeMakers[coffeeMaker].programCounter; coffeeMakers[coffeeMaker].programs[programCounter] = CoffeeProgram({name: name, price: price}); coffeeMakers[coffeeMaker].programCounter += 1; emit CoffeeMakerProgramAdded(coffeeMaker, name, price); } /// @notice Sends Ether to the contract and adds an equal amount of tokens to the buyers wallet. /// @dev At least one Ether has to be sent to this function. Also the tokens are calculated based on the sent Ether, /// but with a tokens-per-ether factor taken into account. /// @param buyer The address of the buyers wallet. To this wallet, the tokens will be added. /// @return The amount of tokens the buyer received. function buyTokens(address buyer) public payable isAuthorizedWallet walletIsKnown(buyer) returns (uint receivedTokens) { require(msg.value >= 1 ether); uint etherValue = msg.value / (1 ether); require(etherValue * (1 ether) == msg.value); uint tokens = etherValue * tokensPerEther; tokenStore[buyer] += tokens; emit TokensBought(buyer, tokens); return tokens; } /// @notice Sends Ether from the contract to the message sender and removes an equal amount of tokens from the sellers wallet. /// @dev If less tokens than required for selling are available, all available tokens will be sold. /// @param seller The address of the sellers wallet. From this wallet, the tokens will be subtracted. /// @param tokens The amount of tokens to sell. /// @return The amount of tokens that have actually be sold. function sellTokens(address seller, uint tokens) public isAuthorizedWallet walletIsKnown(seller) returns (uint soldTokens) { require(tokens > 0); require(tokenStore[seller] > 0); uint tokensToSell = tokens; if (tokenStore[seller] < tokensToSell) { tokensToSell = tokenStore[seller]; } tokenStore[seller] -= tokensToSell; uint weiValue = (tokensToSell / tokensPerEther) * (1 ether); msg.sender.transfer(weiValue); emit TokensSold(seller, tokensToSell); return tokensToSell; } /// @notice Sends tokens from one wallet to another. /// @dev The message sender is the source wallet. The function can only be executed for known wallets. /// @param receiver The wallet to receive the sent tokens. /// @param tokens The amount of tokens to transfer. /// @return The amount of tokens that have actually be transferred. function transferTokens( address receiver, uint tokens ) public walletIsKnown(receiver) walletIsKnown(msg.sender) returns (uint transferedTokens) { require(tokens > 0); require(tokenStore[msg.sender] > 0); uint tokensToTransfer = tokens; if (tokenStore[msg.sender] < tokensToTransfer) { tokensToTransfer = tokenStore[msg.sender]; } tokenStore[msg.sender] -= tokensToTransfer; tokenStore[receiver] += tokensToTransfer; emit TokensTransfered(msg.sender, receiver, tokensToTransfer); return tokensToTransfer; } /// @notice Buys a coffee with tokens using the given program and amount. /// @dev Requires enough tokens to be available to buy the coffee program the given amount of times. /// @param coffeeMaker The coffee maker at which coffee is bought. /// @param program The program which is selected. /// @param amount The number of times the selected program is bought. /// @return The amount of tokens that have been billed. function buyCoffee(address coffeeMaker, uint8 program, uint8 amount) public returns (uint transferedTokens) { require(customers[msg.sender].exists == true); require(coffeeMakers[coffeeMaker].exists == true); require(coffeeMakers[coffeeMaker].programCounter > program); uint totalPrice = coffeeMakers[coffeeMaker].programs[program].price * amount; require(tokenStore[msg.sender] >= totalPrice); tokenStore[msg.sender] -= totalPrice; tokenStore[coffeeMaker] += totalPrice; emit CoffeeBought(coffeeMaker, program, amount); return amount; } /// @notice Getter for the tokens on a wallet. /// @dev Does not perform any kind of access control. /// @param wallet The wallet to check the token balance for. /// @return The amount of tokens available for the given wallet. function getTokens(address wallet) public view returns (uint tokens) { return tokenStore[wallet]; } /// @notice Getter to check if a wallet is registered as customer. /// @dev Does not perform any kind of access control. /// @param wallet The wallet to check for a customer registration. /// @return If a customer exists for the given wallet or not. function isCustomer(address wallet) public view returns (bool trueOrFalse) { return customers[wallet].exists; } /// @notice Getter to check if a wallet is registered as coffee maker. /// @dev Does not perform any kind of access control. /// @param wallet The wallet to check for a coffee maker registration. /// @return If a coffee maker exists for the given wallet or not. function isCoffeeMaker(address wallet) public view returns (bool trueOrFalse) { return coffeeMakers[wallet].exists; } /// @notice Getter to check if a wallet is an authorized exchange wallet. /// @dev Does not perform any kind of access control. /// @param wallet The wallet to check for being an authorized exchange wallet. /// @return If the given wallt is an authorized exchange wallet or not. function isAuthorizedExchangeWallet(address wallet) public view returns (bool trueOrFalse) { return authorizedExchangeWallets[wallet]; } /// @notice Getter for customer data on a wallet. /// @dev Does not perform any kind of access control. But does only work for known wallets. /// @param wallet The wallet to check for customer data. /// @return { /// "name": "The customers name.", /// "department": "The customers department.", /// "telephone": "The customers telephone number.", /// "email": "The customers email address." /// } function getCustomerData(address wallet) public view returns (string name, string department, string telephone, string email) { require(customers[wallet].exists == true); Customer memory customer = customers[wallet]; return (customer.name, customer.department, customer.telephone, customer.email); } /// @notice Getter for coffee maker data on a wallet. /// @dev Does not perform any kind of access control. But does only work for known wallets. /// @param wallet The wallet to check for coffee maker data. /// @return { /// "owner": "Address of the owner.", /// "name": "The coffee makers name.", /// "descriptiveLocation": "A description of the coffee makers location.", /// "department": "The department where the coffee maker is located at.", /// "latitude": "The latitude of the coffee makers location.", /// "longitude": "The longitude of the coffee makers location.", /// "machineType": "The machine type of the coffee maker.", /// "description": "Additional information." /// } function getCoffeeMakerData(address wallet) public view returns (address owner, string name, string descriptiveLocation, string department, string latitude, string longitude, MachineType machineType, string description) { require(coffeeMakers[wallet].exists == true); CoffeeMaker memory coffeeMaker = coffeeMakers[wallet]; return ( coffeeMaker.owner, coffeeMaker.name, coffeeMaker.location.descriptive, coffeeMaker.location.department, coffeeMaker.location.latitude, coffeeMaker.location.longitude, coffeeMaker.machineInfo.machineType, coffeeMaker.machineInfo.description ); } /// @notice Getter for the number of available programs of a coffee maker. /// @dev Does not perform any kind of access control. /// @param wallet The coffee maker to check for programs. /// @return The number of available programs. function getCoffeeMakerProgramCount(address wallet) public view returns (uint8 programCount) { return coffeeMakers[wallet].programCounter; } /// @notice Getter for program details of a coffee maker. /// @dev Does not perform any kind of access control. But does only work for known coffee makers. /// @param wallet The coffee maker to check for a program. /// @param program The program to get additional information for. /// @return { /// "name": "The name of the coffee program (e.g. Espresso).", /// "price": "The price of the coffee program." /// } function getCoffeeMakerProgramDetails(address wallet, uint8 program) public view returns (string name, uint price) { return (coffeeMakers[wallet].programs[program].name, coffeeMakers[wallet].programs[program].price); } }
Getter for coffee maker data on a wallet. Does not perform any kind of access control. But does only work for known wallets. wallet The wallet to check for coffee maker data. return { "owner": "Address of the owner.", "name": "The coffee makers name.", "descriptiveLocation": "A description of the coffee makers location.", "department": "The department where the coffee maker is located at.", "latitude": "The latitude of the coffee makers location.", "longitude": "The longitude of the coffee makers location.", "machineType": "The machine type of the coffee maker.", "description": "Additional information." }
function getCoffeeMakerData(address wallet) public view returns (address owner, string name, string descriptiveLocation, string department, string latitude, string longitude, MachineType machineType, string description) { require(coffeeMakers[wallet].exists == true); CoffeeMaker memory coffeeMaker = coffeeMakers[wallet]; return ( coffeeMaker.owner, coffeeMaker.name, coffeeMaker.location.descriptive, coffeeMaker.location.department, coffeeMaker.location.latitude, coffeeMaker.location.longitude, coffeeMaker.machineInfo.machineType, coffeeMaker.machineInfo.description ); }
1,799,753
pragma solidity ^0.5.0; import "./HasAuditRegistry.sol"; /* @title Proof of Life Proxy with delegateCall */ contract ProofOfLifeProxy is HasAuditRegistry { // State variables mapping(address => bool) public authorizedUsers; address public contractOwner; bool public isOpenToEveryUser; bool public isLocked; uint256 public lastId = 0; mapping(bytes32 => uint256) public idByDocumentHash; mapping(uint256 => address) public ownerByDocumentId; mapping(uint256 => string) public ipfsHashByDocumentId; mapping(uint256 => bytes32) public hashByDocumentId; mapping(address => uint256[]) public documentsByOwnerAddress; mapping(uint256 => AuditRegistry[]) public auditRegistryByDocumentId; // Delegate call address address public delegateCallAddress; // Events event DelegateCallEvent (string call, bool result); // Modifiers modifier onlyContractOwner(){ require(msg.sender == contractOwner, "E-POLP-001 - Only the proxy contract owner add execute this transaction"); _; } // ------ Local functions to update proxy configuration ------- /* @notice Proxy constructor * @dev It creates a proxy instance * @param _existingContractAddress - the new delegated contract address */ constructor (address existingContractAddress) public { delegateCallAddress = existingContractAddress; contractOwner = msg.sender; authorizedUsers[contractOwner] = true; } /* @notice Update Delegate Call Address * @dev It allows the owner to update the address of the delegate contract * @param _existingContractAddress - the new delegated contract address */ function updateDelegateCallAddress(address existingContractAddress) public onlyContractOwner { delegateCallAddress = existingContractAddress; } // ---- Functions with delegateCall ----- /* @notice Lock contract * @dev Maintenance and security circuit locker */ function lock() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodePacked(bytes4(keccak256("lock()")))); emit DelegateCallEvent("lock", success); } /* @notice Unlock contract * @dev Maintenance and security circuit locker */ function unlock() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodePacked(bytes4(keccak256("unlock()")))); emit DelegateCallEvent("unlock", success); } /* @notice Add authorized user * @dev Includes a new user in the authorized users list * @param user - the address you want to authorize */ function addAuthorizedUser(address user) public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("addAuthorizedUser(address)", user)); if (success) { emit DelegateCallEvent("addAuthorizedUser", success); } else { revert(); } } /* @notice Remove credentials * @dev Remove credentials of an authorized user * @param user - the authorized address to be removed */ function removeCredentials(address user) public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("removeCredentials(address)", user)); if (success) { emit DelegateCallEvent("removeCredentials", success); } else { revert(); } } /* @notice Open to every user * @dev Allows every address to certify documents in the contract */ function openToEveryUser() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("openToEveryUser()")); if (success) { emit DelegateCallEvent("openToEveryUser", success); } else { revert(); } } /* @notice Close to authorized users * @dev Only allows document certification to authorized users */ function closeToAuthorizedUsers() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("closeToAuthorizedUsers()")); if (success) { emit DelegateCallEvent("closeToAuthorizedUsers", success); } else { revert(); } } /* @notice Certify document creation with hash and timestamp * @dev It registers in the blockchain the proof-of-existence of an external document * @param _documentHash - Hash of the document (it should have 32 bytes) * @param _ipfsHash - IPFS Hash, if it exists * @return id - returns certified document id */ function certifyDocumentCreationWithIPFSHash(bytes32 _documentHash, string memory _ipfsHash, string memory _timestamp) public { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("certifyDocumentCreationWithIPFSHash(bytes32,string,string)", _documentHash, _ipfsHash, _timestamp)); if (success) { emit DelegateCallEvent("certifyDocumentCreationWithIPFSHash", success); } else { revert(); } } /* @notice Append Audit Registry * @dev A document owner can use this function to append audit information to it * @param _id - Id of the document * @param _description - Content of the audit registry (status change, extra information, etc...) * @param _timestamp - Local timestamp (UNIX Epoch format) from the external * system or the UI which executes the contract */ function appendAuditRegistry(uint256 _id, string memory _description, string memory _timestamp) public { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("appendAuditRegistry(uint256,string,string)", _id, _description, _timestamp)); if (success) { emit DelegateCallEvent("appendAuditRegistry", success); } else { revert(); } } // ------ Query functions to request information about the contract state ------- /* @notice Get documents by owner * @dev Retrieves a list with all the documents ids of one owner * @return bytes32[] documentsByOwnerAddress */ function getDocumentsByOwner(address owner) public view returns(uint256[] memory) { return documentsByOwnerAddress[owner]; } /* @notice Get Document Details * @dev Retrieves all the information of a document * @param _documentHash - Hash of the document * @return uint256 id, string docHash, string ipfsHash, address documentOwner */ function getDocumentDetailsByHash(bytes32 _documentHash) public view returns (uint256, bytes32, string memory, address) { uint256 _id = getId(_documentHash); return (_id, hashByDocumentId[_id], ipfsHashByDocumentId[_id], ownerByDocumentId[_id]); } /* @notice Get auditRegistry by documentHash * @dev Retrieves the audit registry of a document * @param _documentHash - Hash of the document * @param _index - Position of the auditRegistry in the list * @return string description, string timestamp, uint256 blockTimestamp */ function getAuditRegistryByDocumentHash(bytes32 _documentHash, uint256 _index) public view returns (string memory, string memory, uint256) { uint256 _id = getId(_documentHash); return getAuditRegistryByDocumentId(_id, _index); } /* @notice CountAuditRegistries by hash * @dev Count the number of audit registries of a document * @param _documentHash - Hash of the document * @return uint256 number of elements */ function countAuditRegistriesByDocumentHash(bytes32 _documentHash) public view returns(uint256) { uint256 _id = getId(_documentHash); return auditRegistryByDocumentId[_id].length; } /* @notice Get Document Details * @dev Retrieves all the information of a document * @param _id - Id of the document * @return uint256 id, string docHash, address documentOwner */ function getDocumentDetailsById(uint256 _id) public view returns (uint256, bytes32, string memory, address) { return (_id, hashByDocumentId[_id], ipfsHashByDocumentId[_id], ownerByDocumentId[_id]); } /* @notice Get auditRegistry by documentId * @dev Retrieves the audit registry of a document * @param _id - Id of the document * @param _index - Position of the auditRegistry in the list * @return string description, string timestamp, uint256 blockTimestamp */ function getAuditRegistryByDocumentId(uint256 _id, uint256 _index) public view returns (string memory, string memory, uint256) { return (auditRegistryByDocumentId[_id][_index].description, auditRegistryByDocumentId[_id][_index].timestamp, auditRegistryByDocumentId[_id][_index].blockTimestamp); } /* @notice Get document id from hash * @dev Retrieves a document id from a string with the hash * @param _documentHash - Hash of the document * @return uint256 */ function getId(bytes32 _documentHash) public view returns(uint256) { return idByDocumentHash[_documentHash]; } }
Get auditRegistry by documentId Retrieves the audit registry of a document _id - Id of the document _index - Position of the auditRegistry in the list return string description, string timestamp, uint256 blockTimestamp/
function getAuditRegistryByDocumentId(uint256 _id, uint256 _index) public view returns (string memory, string memory, uint256) { return (auditRegistryByDocumentId[_id][_index].description, auditRegistryByDocumentId[_id][_index].timestamp, auditRegistryByDocumentId[_id][_index].blockTimestamp); }
13,012,397
./partial_match/1/0xefB611d0DfC0b27C2C675B52845dEdcDE9942d11/sources/SWDMToken.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); ███████╗██╗ ██╗██████╗ ███╗ ███╗ }
15,656,624
./partial_match/1/0x494c83dE7da10546Ce84106c544a279154c3CEd6/sources/contracts/Liquidation.sol
Checks if input data meets requirements accountAssetsLength The length of borrower's accountAssets array seizeIndexes_ An array with market indexes that will be used as collateral. Each element corresponds to the market index in the accountAssets array debtRates_ An array of debt redemption rates for each debt markets (scaled by 1e18). Indexes for arrays accountAssets && debtRates match each other/ Check all DRR are <= 100% Check all seizeIndexes are <= to (accountAssetsLength - 1) Check seizeIndexes array does not contain duplicates
function verifyExternalData( uint256 accountAssetsLength, uint256[] memory seizeIndexes_, uint256[] memory debtRates_ ) internal pure { uint256 debtRatesLength = debtRates_.length; uint256 seizeIndexesLength = seizeIndexes_.length; require(accountAssetsLength != 0 && debtRatesLength == accountAssetsLength, ErrorCodes.LQ_INVALID_DRR_ARRAY); require( seizeIndexesLength != 0 && seizeIndexesLength <= accountAssetsLength, ErrorCodes.LQ_INVALID_SEIZE_ARRAY ); for (uint256 i = 0; i < debtRatesLength; i++) { require(debtRates_[i] <= EXP_SCALE, ErrorCodes.LQ_INVALID_DEBT_REDEMPTION_RATE); } for (uint256 i = 0; i < seizeIndexesLength; i++) { require(seizeIndexes_[i] < accountAssetsLength, ErrorCodes.LQ_INVALID_SEIZE_INDEX); for (uint256 j = i + 1; j < seizeIndexesLength; j++) { require(seizeIndexes_[i] != seizeIndexes_[j], ErrorCodes.LQ_DUPLICATE_SEIZE_INDEX); } } }
2,849,839
// SPDX-License-Identifier: MIT pragma solidity ^0.8.8; /// @title ERC20 Token Standard, ERC2612 optional extension: permit – 712-signed approvals /// @notice Interface for allowing ERC20 approvals to be made via ECDSA `secp256k1` signatures. /// @dev See https://eips.ethereum.org/EIPS/eip-2612 /// @dev Note: the ERC-165 identifier for this interface is 0x9d8ff7da. interface IERC20Permit { /// @notice Sets the allowance to an account from another account using a signed permit. /// @notice Warning: The standard ERC20 race condition for approvals applies to `permit()` as well: https://swcregistry.io/docs/SWC-114 /// @dev Reverts if `owner` is the zero address. /// @dev Reverts if the current blocktime is greather than `deadline`. /// @dev Reverts if `r`, `s`, and `v` do not represent a valid `secp256k1` signature from `owner`. /// @dev Emits an {IERC20-Approval} event. /// @param owner The token owner granting the allowance to `spender`. /// @param spender The token spender being granted the allowance by `owner`. /// @param value The allowance amount to grant. /// @param deadline The deadline from which the permit signature is no longer valid. /// @param v Permit signature v parameter /// @param r Permit signature r parameter. /// @param s Permis signature s parameter. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /// @notice Gets the current permit nonce of an account. /// @param owner The account to check the nonce of. /// @return nonce The current permit nonce of `owner`. function nonces(address owner) external view returns (uint256 nonce); /// @notice Returns the EIP-712 encoded hash struct of the domain-specific information for permits. /// @dev A common ERC-20 permit implementation choice for the `DOMAIN_SEPARATOR` is: /// keccak256( /// abi.encode( /// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), /// keccak256(bytes(name)), /// keccak256(bytes(version)), /// chainId, /// address(this))) /// /// where /// - `name` (string) is the ERC-20 token name. /// - `version` (string) refers to the ERC-20 token contract version. /// - `chainId` (uint256) is the chain ID to which the ERC-20 token contract is deployed to. /// - `verifyingContract` (address) is the ERC-20 token contract address. /// /// @return domainSeparator The EIP-712 encoded hash struct of the domain-specific information for permits. // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32 domainSeparator); }
ERC20 Token Standard, ERC2612 optional extension: permit – 712-signed approvals Interface for allowing ERC20 approvals to be made via ECDSA `secp256k1` signatures. See https://eips.ethereum.org/EIPS/eip-2612 Note: the ERC-165 identifier for this interface is 0x9d8ff7da. solhint-disable-next-line func-name-mixedcase
interface IERC20Permit { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256 nonce); function DOMAIN_SEPARATOR() external view returns (bytes32 domainSeparator); pragma solidity ^0.8.8; }
938,283
/* Simple token - simple token for PreICO and ICO Copyright (C) 2017 Sergey Sherkunov <[email protected]> Copyright (C) 2017 OOM.AG <[email protected]> This file is part of simple token. Token is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.4.18; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { assert(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; assert(c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a % b; } function min(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a; if(a > b) c = b; } } contract ABXToken { using SafeMath for uint256; address public owner; address public minter; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed oldTokensHolder, address indexed newTokensHolder, uint256 tokensNumber); //An Attack Vector on Approve/TransferFrom Methods: //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 event Transfer(address indexed tokensSpender, address indexed oldTokensHolder, address indexed newTokensHolder, uint256 tokensNumber); event Approval(address indexed tokensHolder, address indexed tokensSpender, uint256 newTokensNumber); //An Attack Vector on Approve/TransferFrom Methods: //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 event Approval(address indexed tokensHolder, address indexed tokensSpender, uint256 oldTokensNumber, uint256 newTokensNumber); modifier onlyOwner { require(owner == msg.sender); _; } //ERC20 Short Address Attack: //https://vessenes.com/the-erc20-short-address-attack-explained //https://blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95 //https://ericrafaloff.com/analyzing-the-erc20-short-address-attack modifier checkPayloadSize(uint256 size) { require(msg.data.length == size + 4); _; } modifier onlyNotNullTokenHolder(address tokenHolder) { require(tokenHolder != address(0)); _; } function ABXToken(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { owner = msg.sender; name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply.mul(10 ** uint256(decimals)); require(decimals <= 77); balanceOf[this] = totalSupply; } function setOwner(address _owner) public onlyOwner returns(bool) { owner = _owner; return true; } function setMinter(address _minter) public onlyOwner returns(bool) { safeApprove(this, minter, 0); minter = _minter; safeApprove(this, minter, balanceOf[this]); return true; } //ERC20 Short Address Attack: //https://vessenes.com/the-erc20-short-address-attack-explained //https://blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95 //https://ericrafaloff.com/analyzing-the-erc20-short-address-attack function transfer(address newTokensHolder, uint256 tokensNumber) public checkPayloadSize(2 * 32) returns(bool) { transfer(msg.sender, newTokensHolder, tokensNumber); return true; } //An Attack Vector on Approve/TransferFrom Methods: //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 // //ERC20 Short Address Attack: //https://vessenes.com/the-erc20-short-address-attack-explained //https://blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95 //https://ericrafaloff.com/analyzing-the-erc20-short-address-attack function transferFrom(address oldTokensHolder, address newTokensHolder, uint256 tokensNumber) public checkPayloadSize(3 * 32) returns(bool) { allowance[oldTokensHolder][msg.sender] = allowance[oldTokensHolder][msg.sender].sub(tokensNumber); transfer(oldTokensHolder, newTokensHolder, tokensNumber); Transfer(msg.sender, oldTokensHolder, newTokensHolder, tokensNumber); return true; } //ERC20 Short Address Attack: //https://vessenes.com/the-erc20-short-address-attack-explained //https://blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95 //https://ericrafaloff.com/analyzing-the-erc20-short-address-attack function approve(address tokensSpender, uint256 newTokensNumber) public checkPayloadSize(2 * 32) returns(bool) { safeApprove(msg.sender, tokensSpender, newTokensNumber); return true; } //An Attack Vector on Approve/TransferFrom Methods: //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 // //ERC20 Short Address Attack: //https://vessenes.com/the-erc20-short-address-attack-explained //https://blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95 //https://ericrafaloff.com/analyzing-the-erc20-short-address-attack function approve(address tokensSpender, uint256 oldTokensNumber, uint256 newTokensNumber) public checkPayloadSize(3 * 32) returns(bool) { require(allowance[msg.sender][tokensSpender] == oldTokensNumber); unsafeApprove(msg.sender, tokensSpender, newTokensNumber); Approval(msg.sender, tokensSpender, oldTokensNumber, newTokensNumber); return true; } function transfer(address oldTokensHolder, address newTokensHolder, uint256 tokensNumber) private onlyNotNullTokenHolder(oldTokensHolder) { balanceOf[oldTokensHolder] = balanceOf[oldTokensHolder].sub(tokensNumber); balanceOf[newTokensHolder] = balanceOf[newTokensHolder].add(tokensNumber); Transfer(oldTokensHolder, newTokensHolder, tokensNumber); } //An Attack Vector on Approve/TransferFrom Methods: //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 function unsafeApprove(address tokensHolder, address tokensSpender, uint256 newTokensNumber) private onlyNotNullTokenHolder(tokensHolder) { allowance[tokensHolder][tokensSpender] = newTokensNumber; Approval(msg.sender, tokensSpender, newTokensNumber); } //An Attack Vector on Approve/TransferFrom Methods: //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 function safeApprove(address tokensHolder, address tokensSpender, uint256 newTokensNumber) private { require(allowance[tokensHolder][tokensSpender] == 0 || newTokensNumber == 0); unsafeApprove(tokensHolder, tokensSpender, newTokensNumber); } }
An Attack Vector on Approve/TransferFrom Methods:https:github.com/ethereum/EIPs/issues/20issuecomment-263524729ERC20 Short Address Attack:https:vessenes.com/the-erc20-short-address-attack-explainedhttps:blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95https:ericrafaloff.com/analyzing-the-erc20-short-address-attack
function approve(address tokensSpender, uint256 oldTokensNumber, uint256 newTokensNumber) public checkPayloadSize(3 * 32) returns(bool) { require(allowance[msg.sender][tokensSpender] == oldTokensNumber); unsafeApprove(msg.sender, tokensSpender, newTokensNumber); Approval(msg.sender, tokensSpender, oldTokensNumber, newTokensNumber); return true; }
12,952,540
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IERC20Decimals is IERC20 { function decimals() external view returns (uint8); } /** * @title GNSwap * @dev Swap MONGv1 for MONGv2 */ contract GNSwap is Ownable { IERC20Decimals private gnV1; IERC20Decimals private gnV2; mapping(address => uint256) public v1Balances; mapping(address => bool) public swapped; constructor(address _v1, address _v2) { gnV1 = IERC20Decimals(_v1); gnV2 = IERC20Decimals(_v2); } function swap() external { require(!swapped[msg.sender], 'already swapped V1 for V2'); require(gnV1.balanceOf(msg.sender) > 0, 'we do not see your balance'); // TODO: determine ratio user should receive from V1 to V2 // and update here // uint256 _v2Amount = gnV1.balanceOf(msg.sender); uint256 _v2Amount = getV2Amount(msg.sender); require(_v2Amount > 0, 'you do not have any V1 tokens'); require( gnV2.balanceOf(address(this)) >= _v2Amount, 'not enough V2 liquidity to complete swap' ); swapped[msg.sender] = true; gnV1.transferFrom(msg.sender, address(this), gnV1.balanceOf(msg.sender)); gnV2.transfer( msg.sender, (_v2Amount * 10**gnV2.decimals()) / 10**gnV1.decimals() ); } function setSwapped(address _wallet, bool _swapped) external onlyOwner { swapped[_wallet] = _swapped; } function v1() external view returns (address) { return address(gnV1); } function v2() external view returns (address) { return address(gnV2); } function getV2Amount(address _user) public view returns (uint256) { // return (gnV1.balanceOf(_user) * 120) / 100; return (v1Balances[_user] * 120) / 100; } function setBalances(address[] memory _users, uint256[] memory _v1Balances) external onlyOwner { require(_users.length == _v1Balances.length, 'must be same size'); for (uint256 i = 0; i < _users.length; i++) { v1Balances[_users[i]] = _v1Balances[i]; } } function withdrawTokens(address _tokenAddy, uint256 _amount) external onlyOwner { IERC20 _token = IERC20(_tokenAddy); _amount = _amount > 0 ? _amount : _token.balanceOf(address(this)); require(_amount > 0, 'make sure there is a balance available to withdraw'); _token.transfer(owner(), _amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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; } }
TODO: determine ratio user should receive from V1 to V2 and update here uint256 _v2Amount = gnV1.balanceOf(msg.sender);
function swap() external { require(!swapped[msg.sender], 'already swapped V1 for V2'); require(gnV1.balanceOf(msg.sender) > 0, 'we do not see your balance'); uint256 _v2Amount = getV2Amount(msg.sender); require(_v2Amount > 0, 'you do not have any V1 tokens'); require( gnV2.balanceOf(address(this)) >= _v2Amount, 'not enough V2 liquidity to complete swap' ); swapped[msg.sender] = true; gnV1.transferFrom(msg.sender, address(this), gnV1.balanceOf(msg.sender)); gnV2.transfer( msg.sender, (_v2Amount * 10**gnV2.decimals()) / 10**gnV1.decimals() ); }
10,407,540
pragma solidity ^0.5.10; import "./eth_merkle_bridge.sol"; contract Oracle { // Global State root included in block headers bytes32 public _anchorRoot; // Height of the last block anchored uint public _anchorHeight; // _tAnchor is the anchoring periode: sets a minimal delay between anchors to prevent spamming // and give time to applications to build merkle proof for their data. uint public _tAnchor; // _tFinal is the time after which the validators considere a block finalised // this value is only useful if the anchored chain doesn't have LIB // Since Aergo has LIB it is a simple indicator for wallets. uint public _tFinal; // 2/3 of validators must sign to interact address[] public _validators; // _nonce is a replay protection for anchors and settings update uint public _nonce; // _contractId is a replay protection between sidechains as the same addresses can be validators // on multiple chains. bytes32 public _contractId; // address of the bridge contract being controled EthMerkleBridge public _bridge; // General Aergo state trie key of the bridge contract on Aergo blockchain bytes32 public _destinationBridgeKey; event newValidatorsEvent(address indexed sender, address[] validators); event anchorEvent(address indexed sender, bytes32 root, uint height); // Create a new oracle contract // @param validators - array of Ethereum addresses // @param bridge - address of already deployed bridge contract // @param destinationBridgeKey - trie key of destination bridge contract in Aergo state trie constructor( address[] memory validators, EthMerkleBridge bridge, bytes32 destinationBridgeKey, uint tAnchor, uint tFinal ) public { _validators = validators; _tAnchor = tAnchor; _tFinal = tFinal; _bridge = bridge; _destinationBridgeKey = destinationBridgeKey; _contractId = keccak256(abi.encodePacked(blockhash(block.number - 1), this)); } function getValidators() public view returns (address[] memory) { return _validators; } // Register a new set of validators // @param validators - signers of state anchors // @param signers - array of signer indexes // @param vs, rs, ss - array of signatures matching signers indexes function validatorsUpdate( address[] memory validators, uint[] memory signers, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss ) public { // validators should not sign a set that is equal to the current one to prevent spamming bytes32 message = keccak256(abi.encodePacked(validators, _nonce, _contractId, "V")); validateSignatures(message, signers, vs, rs, ss); _validators = validators; _nonce += 1; emit newValidatorsEvent(msg.sender, validators); } // Replace the oracle of the bridge // @param oracle - new contract that will replace this one for controlling the bridge // @param signers - array of signer indexes // @param vs, rs, ss - array of signatures matching signers indexes function oracleUpdate( address oracle, uint[] memory signers, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss ) public { // validators should not sign a set that is equal to the current one to prevent spamming bytes32 message = keccak256(abi.encodePacked(oracle, _nonce, _contractId, "O")); validateSignatures(message, signers, vs, rs, ss); _nonce += 1; // this contract now doesnt have controle over the bridge anymore _bridge.oracleUpdate(oracle); } // Register new anchoring periode // @param tAnchor - new anchoring periode // @param signers - array of signer indexes // @param vs, rs, ss - array of signatures matching signers indexes function tAnchorUpdate( uint tAnchor, uint[] memory signers, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss ) public { // validators should not sign a number that is equal to the current one to prevent spamming bytes32 message = keccak256(abi.encodePacked(tAnchor, _nonce, _contractId, "A")); validateSignatures(message, signers, vs, rs, ss); _nonce += 1; // _t_anchor prevents anchor spamming just like the _t_anchor in the bridge contract. // also useful info for wallets. _tAnchor = tAnchor; _bridge.tAnchorUpdate(tAnchor); } // Register new finality of anchored chain // @param tFinal - new finality of anchored chain // @param signers - array of signer indexes // @param vs, rs, ss - array of signatures matching signers indexes function tFinalUpdate( uint tFinal, uint[] memory signers, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss ) public { // validators should not sign a number that is equal to the current one to prevent spamming bytes32 message = keccak256(abi.encodePacked(tFinal, _nonce, _contractId, "F")); validateSignatures(message, signers, vs, rs, ss); _nonce += 1; // _tfinal is redundant with the value stored in the bridge: just a useful information for apps. _tFinal = tFinal; _bridge.tFinalUpdate(tFinal); } // Register a new anchor // @param root - Aergo blocks state root // @param height - block height of root // @param signers - array of signer indexes // @param vs, rs, ss - array of signatures matching signers indexes function newStateAnchor( bytes32 root, uint height, uint[] memory signers, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss ) public { require(height > _anchorHeight + _tAnchor, "Next anchor height not reached"); bytes32 message = keccak256(abi.encodePacked(root, height, _nonce, _contractId, "R")); validateSignatures(message, signers, vs, rs, ss); _nonce += 1; _anchorRoot = root; _anchorHeight = height; emit anchorEvent(msg.sender, root, height); } // Register a new bridge anchor // @param proto - Proto bytes of the serialized contract account // @param mp - merkle proof of inclusion of proto serialized account in general trie // @param bitmap - bitmap of non default nodes in the merkle proof // @param leafHeight - height of leaf containing the value in the state SMT function newBridgeAnchor( bytes memory proto, bytes32[] memory mp, // bytes[] is not yet supported so we use a bitmap of proof elements bytes32 bitmap, uint8 leafHeight ) public { bytes32 root = parseRootFromProto(proto); bytes32 accountHash = sha256(proto); require(verifyAergoStateProof(_destinationBridgeKey, accountHash, mp, bitmap, leafHeight), "Failed to verify bridge state inside general state"); _bridge.newAnchor(root, _anchorHeight); } // Register a new state anchor and update the bridge anchor // @param stateRoot - Aergo general state root // @param height - block height of root // @param signers - array of signer indexes // @param vs, rs, ss - array of signatures matching signers indexes // @param proto - Proto bytes of the serialized contract account // @param mp - merkle proof of inclusion of proto serialized account in general trie // @param bitmap - bitmap of non default nodes in the merkle proof // @param leafHeight - height of leaf containing the value in the state SMT function newStateAndBridgeAnchor( bytes32 stateRoot, uint height, uint[] memory signers, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss, bytes memory proto, bytes32[] memory mp, // bytes[] is not yet supported so we use a bitmap of proof elements bytes32 bitmap, uint8 leafHeight ) public { newStateAnchor(stateRoot, height, signers, vs, rs, ss); newBridgeAnchor(proto, mp, bitmap, leafHeight); } // Aergo State Trie Merkle proof verification // @param trieKey - General trie key storing the bridge contract account // @param trieValue - Hash of the contract account state // @param mp - merkle proof of inclusion of accountRef, balance in _anchorRoot // @param bitmap - bitmap of non default nodes in the merkle proof // @param leafHeight - height of leaf containing the value in the state SMT function verifyAergoStateProof( bytes32 trieKey, bytes32 trieValue, bytes32[] memory mp, // bytes[] is not yet supported so we use a bitmap of proof elements bytes32 bitmap, uint8 leafHeight ) public view returns(bool) { bytes32 nodeHash = sha256(abi.encodePacked(trieKey, trieValue, uint8(256-leafHeight))); uint proofIndex = 0; for (uint8 i = leafHeight; i>0; i--){ if (bitIsSet(bitmap, leafHeight-i)) { if (bitIsSet(trieKey, i-1)) { nodeHash = sha256(abi.encodePacked(mp[proofIndex], nodeHash)); } else { nodeHash = sha256(abi.encodePacked(nodeHash, mp[proofIndex])); } proofIndex++; } else { if (bitIsSet(trieKey, i-1)) { nodeHash = sha256(abi.encodePacked(byte(0x00), nodeHash)); } else { nodeHash = sha256(abi.encodePacked(nodeHash, byte(0x00))); } } } return _anchorRoot == nodeHash; } // check if the ith bit is set in bytes // @param bits - bytesin which we check the ith bit // @param i - index of bit to check function bitIsSet(bytes32 bits, uint8 i) public pure returns (bool) { return bits[i/8]&bytes1(uint8(1)<<uint8(7-i%8)) != 0; } // Check 2/3 validators signed message hash // @param message - message signed (hash of data) // @param signers - array of signer indexes // @param vs, rs, ss - array of signatures matching signers indexes function validateSignatures( bytes32 message, uint[] memory signers, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss ) public view returns (bool) { require(_validators.length*2 <= signers.length*3, "2/3 validators must sign"); for (uint i = 0; i < signers.length; i++) { if (i > 0) { require(signers[i] > signers[i-1], "Provide ordered signers"); } address signer = ecrecover(message, vs[i], rs[i], ss[i]); require(signer == _validators[signers[i]], "Signature doesn't match validator"); } return true; } // Parse a proto serialized contract account state to extract the storage root // @param proto - serialized proto account function parseRootFromProto(bytes memory proto) public pure returns(bytes32) { /* Aergo account state object: message State { uint64 nonce = 1; bytes balance = 2; bytes codeHash = 3; bytes storageRoot = 4; uint64 sqlRecoveryPoint = 5; } https://developers.google.com/protocol-buffers/docs/encoding +--------------+-----------+----------+--------------+ | field number | wire type | tag(hex) | tag(bin) | | 1 | 0 | 0x08 | 0000 1000 | | 2 | 2 | 0x12 | 0001 0010 | | 3 | 2 | 0x1a | 0001 1010 | | 4 | 2 | 0x22 | 0010 0010 | | 5 | 0 | 0x2a | 0010 1010 | +--------------+-----------+----------+--------------+ Contracts can have 0 balance and 0 nonce, so their tags 0x08 and 0x12 are not always present in the serialized state. */ uint index = 0; // keep track of byte index while steping through the proto bytes. // parse uint64 nonce = 1 if (proto[index] == 0x08) { index++; for (index; index<proto.length;) { // 0x80 = 128 => check if the first bit is 0 or 1. // The first bit of the last byte of the varint nb is 0 if (proto[index] < 0x80) { index++; break; } index++; } } // parse bytes balance = 2 if (proto[index] == 0x12) { index++; // calculate varint nb of bytes used to encode balance // the balance is encoded with 32 bytes (0x20) maximum so the length takes a single byte require(proto[index] <= 0x20, "Invalid balance length"); uint balanceLength = uint8(proto[index]); index += balanceLength + 1; } // parse bytes codeHash = 3 require(proto[index] == 0x1a, "Invalid codeHash proto tag"); index++; require(proto[index] == 0x20, "Invalid codeHash length"); index += 33; // parse bytes storageRoot = 4 require(proto[index] == 0x22, "Invalid storageRoot proto tag"); index++; require(proto[index] == 0x20, "Invalid storageRoot length"); index++; // start of storageRoot bytes // extrack storageRoot bytes32 storageRoot; assembly { // https://github.com/GNSPS/solidity-bytes-utils/blob/e3d1f6831e870896a5cd5efe5e87efbbcb86e2c4/contracts/BytesLib.sol#L381 storageRoot := mload(add(add(proto, 0x20), index)) } return storageRoot; } }
Register a new bridge anchor proto - Proto bytes of the serialized contract account mp - merkle proof of inclusion of proto serialized account in general trie bitmap - bitmap of non default nodes in the merkle proof leafHeight - height of leaf containing the value in the state SMT
function newBridgeAnchor( bytes memory proto, bytes32 bitmap, uint8 leafHeight ) public { bytes32 root = parseRootFromProto(proto); bytes32 accountHash = sha256(proto); require(verifyAergoStateProof(_destinationBridgeKey, accountHash, mp, bitmap, leafHeight), "Failed to verify bridge state inside general state"); _bridge.newAnchor(root, _anchorHeight); }
6,441,897
./full_match/5/0x4886000cDA0CC2dcBeCCC3a682AF5b83e4757354/sources/project_/contracts/ShippingPass.sol
_newPrice is the new price of shippingCost2 in wei
function setPrice2(uint256 _newPrice) external onlyOwner { shippingCost2 = _newPrice; }
1,868,527
./full_match/43114/0x6741db012578615Ee07e029C1062B46730093912/sources/flatten-StakingPool.sol
Obtain the stake balance of this contract
function totalStakeTokenBalance() public view returns (uint256) { if (STAKE_TOKEN == REWARD_TOKEN) return totalStaked; return STAKE_TOKEN.balanceOf(address(this)); }
4,518,206
./full_match/5/0xc312795203ffaA4049815Dd6c2B4CF8caa17AFE9/sources/contracts/ensSubDomainerERC20.sol
set base fee letters
function setLetterFeesERC20(bytes32 node, address erc20Contract, uint256 threeUpLetterFee_, uint256 fourFiveLetterFee_, uint256 sixDownLetterFee_) external isNodeActiveOwnerorApproved(node) { for (uint i = 0; i < parentNodeERC20Contracts[node].length; i++) { require(parentNodeERC20Contracts[node][i] == erc20Contract, 'not added'); } threeUpLetterFeeERC20[node][erc20Contract] = threeUpLetterFee_; fourFiveLetterFeeERC20[node][erc20Contract] = fourFiveLetterFee_; sixDownLetterFeeERC20[node][erc20Contract] = sixDownLetterFee_; }
1,935,818
./full_match/1/0x8A676d790C0a4f8dC2b647579A7Cb8eb2a770418/sources/browser/tests/4_Ballot_test.sol
Views total number of YFTE tokens deposited for rewards. return YFTE token balance of the faucet./
function balance() public view returns (uint256) { return YFTE.balanceOf(address(this)); }
5,015,684
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155MultiURI_A.sol"; import {ModeratedUris} from "./Moderated Uris.sol"; import "@openzeppelin/[email protected]/access/IAccessControl.sol"; import "@openzeppelin/[email protected]/utils/Strings.sol"; import {AccessControl} from "@openzeppelin/[email protected]/access/AccessControl.sol"; /** * @dev Extension of ERC1155MultiURI that adds support for changing the metadata * associated with a token id, only for ids which correspond to unique NFTs, * and only among an approved list of URIs. * THIS IS NOT AN OPENZEPPELIN CONTRACT. It was created by Conor McKenzie. * * Useful for scenarios where multiple types of tokens are to be created with * metadata stored using a content-addressing naming scheme, such as when * stored on IPFS or Arweave, and where the option for holders to be able to * change or upgrade their NFT(s)' metadata (within an approved set of * changes) is desired. * * Caution: The following ERC1155 components have not been overwritten to * maintain the integrity of OpenZeppelin's original ERC1155 contracts, but they * should not be used: * function _setURI(string memory) * * function _mint(address, uint256, uint256, bytes memory) * * Note: _mint(address to, uint256 id, uint256 amount, bytes memory data) * from OpenZeppelin's ERC1155 contract is replaced with: * _mintWithoutURI(address to, uint256 id, uint256 amount, bytes memory data), * _mintWithURI(address to, uint256 id, uint256 amount, bytes memory data, * string memory newuri) * for minting existing tokens and new tokens, respectively. * These functions both call _mint(address, uint256, uint256, bytes memory) * to mint tokens. */ abstract contract ERC1155MultiURI_UserUpgradeable_ModeratedUris is ERC1155MultiURI_UserUpgradeable, AccessControl { ModeratedUris u = new ModeratedUris(); /* * @dev Adds a require statement to check the user-given URI against a list * of pre-approved metadata, and then runs _safeUpdateURI(...) */ function safeUpdateURI( string memory newuri, address owner, uint256 id ) public virtual { require( u.isMetadataApprovedForId(id, newuri), string(abi.encode( "Given metadata is not approved for token id ", id )) ); _safeUpdateURI(newuri, owner, id); } /* * @dev Overrides _mintWithURI(...) from ERC1155MultiURI, providing an * updated require message and an additional condition to check if a * token is non-mintable. */ function _mintWithURI( address to, uint256 id, uint256 amount, bytes memory data, string memory newuri ) internal virtual override mintsTokens(id) { require ( !exists(id), "Cannot change metadata of existing token via minting" ); require( u.isMetadataApprovedForId(id, newuri), string(abi.encode( "Given metadata is not approved for token id ", id) ) ); _setURI(id, newuri); _mint(to, id, amount, data); } constructor() { } /* * @dev Override required by Solidity compiler */ // not sure if this is correct or not function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AccessControl) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } }
Override required by Solidity compiler/ not sure if this is correct or not
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AccessControl) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); }
12,551,407
/** *Submitted for verification at Etherscan.io on 2020-07-06 */ // File: contracts/sol6/utils/zeppelin/SafeMath.sol pragma solidity 0.6.6; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // File: contracts/sol6/Dao/IEpochUtils.sol pragma solidity 0.6.6; interface IEpochUtils { function epochPeriodInSeconds() external view returns (uint256); function firstEpochStartTimestamp() external view returns (uint256); function getCurrentEpochNumber() external view returns (uint256); function getEpochNumber(uint256 timestamp) external view returns (uint256); } // File: contracts/sol6/Dao/EpochUtils.sol pragma solidity 0.6.6; contract EpochUtils is IEpochUtils { using SafeMath for uint256; uint256 public override epochPeriodInSeconds; uint256 public override firstEpochStartTimestamp; function getCurrentEpochNumber() public view override returns (uint256) { return getEpochNumber(now); } function getEpochNumber(uint256 timestamp) public view override returns (uint256) { if (timestamp < firstEpochStartTimestamp || epochPeriodInSeconds == 0) { return 0; } // ((timestamp - firstEpochStartTimestamp) / epochPeriodInSeconds) + 1; return ((timestamp.sub(firstEpochStartTimestamp)).div(epochPeriodInSeconds)).add(1); } } // File: contracts/sol6/Dao/DaoOperator.sol pragma solidity 0.6.6; contract DaoOperator { address public daoOperator; constructor(address _daoOperator) public { require(_daoOperator != address(0), "daoOperator is 0"); daoOperator = _daoOperator; } modifier onlyDaoOperator() { require(msg.sender == daoOperator, "only daoOperator"); _; } } // File: contracts/sol6/IERC20.sol pragma solidity 0.6.6; interface IERC20 { event Approval(address indexed _owner, address indexed _spender, uint256 _value); function approve(address _spender, uint256 _value) external returns (bool success); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function balanceOf(address _owner) external view returns (uint256 balance); function decimals() external view returns (uint8 digits); function totalSupply() external view returns (uint256 supply); } // to support backward compatible contract name -- so function signature remains same abstract contract ERC20 is IERC20 { } // File: contracts/sol6/utils/zeppelin/ReentrancyGuard.sol pragma solidity 0.6.6; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: contracts/sol6/Dao/IKyberStaking.sol pragma solidity 0.6.6; interface IKyberStaking is IEpochUtils { event Delegated( address indexed staker, address indexed representative, uint256 indexed epoch, bool isDelegated ); event Deposited(uint256 curEpoch, address indexed staker, uint256 amount); event Withdraw(uint256 indexed curEpoch, address indexed staker, uint256 amount); function initAndReturnStakerDataForCurrentEpoch(address staker) external returns ( uint256 stake, uint256 delegatedStake, address representative ); function deposit(uint256 amount) external; function delegate(address dAddr) external; function withdraw(uint256 amount) external; /** * @notice return combine data (stake, delegatedStake, representative) of a staker * @dev allow to get staker data up to current epoch + 1 */ function getStakerData(address staker, uint256 epoch) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); function getLatestStakerData(address staker) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); /** * @notice return raw data of a staker for an epoch * WARN: should be used only for initialized data * if data has not been initialized, it will return all 0 * pool master shouldn't use this function to compute/distribute rewards of pool members */ function getStakerRawData(address staker, uint256 epoch) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); } // File: contracts/sol6/IKyberDao.sol pragma solidity 0.6.6; interface IKyberDao is IEpochUtils { event Voted(address indexed staker, uint indexed epoch, uint indexed campaignID, uint option); function getLatestNetworkFeeDataWithCache() external returns (uint256 feeInBps, uint256 expiryTimestamp); function getLatestBRRDataWithCache() external returns ( uint256 burnInBps, uint256 rewardInBps, uint256 rebateInBps, uint256 epoch, uint256 expiryTimestamp ); function handleWithdrawal(address staker, uint256 penaltyAmount) external; function vote(uint256 campaignID, uint256 option) external; function getLatestNetworkFeeData() external view returns (uint256 feeInBps, uint256 expiryTimestamp); function shouldBurnRewardForEpoch(uint256 epoch) external view returns (bool); /** * @dev return staker's reward percentage in precision for a past epoch only * fee handler should call this function when a staker wants to claim reward * return 0 if staker has no votes or stakes */ function getPastEpochRewardPercentageInPrecision(address staker, uint256 epoch) external view returns (uint256); /** * @dev return staker's reward percentage in precision for the current epoch * reward percentage is not finalized until the current epoch is ended */ function getCurrentEpochRewardPercentageInPrecision(address staker) external view returns (uint256); } // File: contracts/sol6/Dao/KyberStaking.sol pragma solidity 0.6.6; /** * @notice This contract is using SafeMath for uint, which is inherited from EpochUtils * Some events are moved to interface, easier for public uses * Staking contract will be deployed by KyberDao's contract */ contract KyberStaking is IKyberStaking, EpochUtils, ReentrancyGuard { struct StakerData { uint256 stake; uint256 delegatedStake; address representative; } IERC20 public immutable kncToken; IKyberDao public immutable kyberDao; // staker data per epoch, including stake, delegated stake and representative mapping(uint256 => mapping(address => StakerData)) internal stakerPerEpochData; // latest data of a staker, including stake, delegated stake, representative mapping(address => StakerData) internal stakerLatestData; // true/false: if data has been initialized at an epoch for a staker mapping(uint256 => mapping(address => bool)) internal hasInited; // event is fired if something is wrong with withdrawal // even though the withdrawal is still successful event WithdrawDataUpdateFailed(uint256 curEpoch, address staker, uint256 amount); constructor( IERC20 _kncToken, uint256 _epochPeriod, uint256 _startTimestamp, IKyberDao _kyberDao ) public { require(_epochPeriod > 0, "ctor: epoch period is 0"); require(_startTimestamp >= now, "ctor: start in the past"); require(_kncToken != IERC20(0), "ctor: kncToken 0"); require(_kyberDao != IKyberDao(0), "ctor: kyberDao 0"); epochPeriodInSeconds = _epochPeriod; firstEpochStartTimestamp = _startTimestamp; kncToken = _kncToken; kyberDao = _kyberDao; } /** * @dev calls to set delegation for msg.sender, will take effect from the next epoch * @param newRepresentative address to delegate to */ function delegate(address newRepresentative) external override { require(newRepresentative != address(0), "delegate: representative 0"); address staker = msg.sender; uint256 curEpoch = getCurrentEpochNumber(); initDataIfNeeded(staker, curEpoch); address curRepresentative = stakerPerEpochData[curEpoch + 1][staker].representative; // nothing changes here if (newRepresentative == curRepresentative) { return; } uint256 updatedStake = stakerPerEpochData[curEpoch + 1][staker].stake; // reduce delegatedStake for curRepresentative if needed if (curRepresentative != staker) { initDataIfNeeded(curRepresentative, curEpoch); stakerPerEpochData[curEpoch + 1][curRepresentative].delegatedStake = stakerPerEpochData[curEpoch + 1][curRepresentative].delegatedStake.sub(updatedStake); stakerLatestData[curRepresentative].delegatedStake = stakerLatestData[curRepresentative].delegatedStake.sub(updatedStake); emit Delegated(staker, curRepresentative, curEpoch, false); } stakerLatestData[staker].representative = newRepresentative; stakerPerEpochData[curEpoch + 1][staker].representative = newRepresentative; // ignore if staker is delegating back to himself if (newRepresentative != staker) { initDataIfNeeded(newRepresentative, curEpoch); stakerPerEpochData[curEpoch + 1][newRepresentative].delegatedStake = stakerPerEpochData[curEpoch + 1][newRepresentative].delegatedStake.add(updatedStake); stakerLatestData[newRepresentative].delegatedStake = stakerLatestData[newRepresentative].delegatedStake.add(updatedStake); emit Delegated(staker, newRepresentative, curEpoch, true); } } /** * @dev call to stake more KNC for msg.sender * @param amount amount of KNC to stake */ function deposit(uint256 amount) external override { require(amount > 0, "deposit: amount is 0"); uint256 curEpoch = getCurrentEpochNumber(); address staker = msg.sender; // collect KNC token from staker require( kncToken.transferFrom(staker, address(this), amount), "deposit: can not get token" ); initDataIfNeeded(staker, curEpoch); stakerPerEpochData[curEpoch + 1][staker].stake = stakerPerEpochData[curEpoch + 1][staker].stake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW stakerLatestData[staker].stake = stakerLatestData[staker].stake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW // increase delegated stake for address that staker has delegated to (if it is not staker) address representative = stakerPerEpochData[curEpoch + 1][staker].representative; if (representative != staker) { initDataIfNeeded(representative, curEpoch); stakerPerEpochData[curEpoch + 1][representative].delegatedStake = stakerPerEpochData[curEpoch + 1][representative].delegatedStake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW stakerLatestData[representative].delegatedStake = stakerLatestData[representative].delegatedStake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW } emit Deposited(curEpoch, staker, amount); } /** * @dev call to withdraw KNC from staking, it could affect reward when calling KyberDao handleWithdrawal * @param amount amount of KNC to withdraw */ function withdraw(uint256 amount) external override nonReentrant { require(amount > 0, "withdraw: amount is 0"); uint256 curEpoch = getCurrentEpochNumber(); address staker = msg.sender; require( stakerLatestData[staker].stake >= amount, "withdraw: latest amount staked < withdrawal amount" ); (bool success, ) = address(this).call( abi.encodeWithSignature( "handleWithdrawal(address,uint256,uint256)", staker, amount, curEpoch ) ); if (!success) { // Note: should catch this event to check if something went wrong emit WithdrawDataUpdateFailed(curEpoch, staker, amount); } stakerLatestData[staker].stake = stakerLatestData[staker].stake.sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW // transfer KNC back to staker require(kncToken.transfer(staker, amount), "withdraw: can not transfer knc"); emit Withdraw(curEpoch, staker, amount); } /** * @dev initialize data if needed, then return staker's data for current epoch * @dev for safe, only allow calling this func from KyberDao address * @param staker - staker's address to initialize and get data for */ function initAndReturnStakerDataForCurrentEpoch(address staker) external override returns ( uint256 stake, uint256 delegatedStake, address representative ) { require( msg.sender == address(kyberDao), "initAndReturnData: only kyberDao" ); uint256 curEpoch = getCurrentEpochNumber(); initDataIfNeeded(staker, curEpoch); StakerData memory stakerData = stakerPerEpochData[curEpoch][staker]; stake = stakerData.stake; delegatedStake = stakerData.delegatedStake; representative = stakerData.representative; } /** * @notice return raw data of a staker for an epoch * WARN: should be used only for initialized data * if data has not been initialized, it will return all 0 * pool master shouldn't use this function to compute/distribute rewards of pool members * @dev in KyberDao contract, if staker wants to claim reward for past epoch, * we must know the staker's data for that epoch * if the data has not been initialized, it means staker hasn't done any action -> no reward */ function getStakerRawData(address staker, uint256 epoch) external view override returns ( uint256 stake, uint256 delegatedStake, address representative ) { StakerData memory stakerData = stakerPerEpochData[epoch][staker]; stake = stakerData.stake; delegatedStake = stakerData.delegatedStake; representative = stakerData.representative; } /** * @dev allow to get data up to current epoch + 1 */ function getStake(address staker, uint256 epoch) external view returns (uint256) { uint256 curEpoch = getCurrentEpochNumber(); if (epoch > curEpoch + 1) { return 0; } uint256 i = epoch; while (true) { if (hasInited[i][staker]) { return stakerPerEpochData[i][staker].stake; } if (i == 0) { break; } i--; } return 0; } /** * @dev allow to get data up to current epoch + 1 */ function getDelegatedStake(address staker, uint256 epoch) external view returns (uint256) { uint256 curEpoch = getCurrentEpochNumber(); if (epoch > curEpoch + 1) { return 0; } uint256 i = epoch; while (true) { if (hasInited[i][staker]) { return stakerPerEpochData[i][staker].delegatedStake; } if (i == 0) { break; } i--; } return 0; } /** * @dev allow to get data up to current epoch + 1 */ function getRepresentative(address staker, uint256 epoch) external view returns (address) { uint256 curEpoch = getCurrentEpochNumber(); if (epoch > curEpoch + 1) { return address(0); } uint256 i = epoch; while (true) { if (hasInited[i][staker]) { return stakerPerEpochData[i][staker].representative; } if (i == 0) { break; } i--; } // not delegated to anyone, default to yourself return staker; } /** * @notice return combine data (stake, delegatedStake, representative) of a staker * @dev allow to get staker data up to current epoch + 1 */ function getStakerData(address staker, uint256 epoch) external view override returns ( uint256 stake, uint256 delegatedStake, address representative ) { stake = 0; delegatedStake = 0; representative = address(0); uint256 curEpoch = getCurrentEpochNumber(); if (epoch > curEpoch + 1) { return (stake, delegatedStake, representative); } uint256 i = epoch; while (true) { if (hasInited[i][staker]) { stake = stakerPerEpochData[i][staker].stake; delegatedStake = stakerPerEpochData[i][staker].delegatedStake; representative = stakerPerEpochData[i][staker].representative; return (stake, delegatedStake, representative); } if (i == 0) { break; } i--; } // not delegated to anyone, default to yourself representative = staker; } function getLatestRepresentative(address staker) external view returns (address) { return stakerLatestData[staker].representative == address(0) ? staker : stakerLatestData[staker].representative; } function getLatestDelegatedStake(address staker) external view returns (uint256) { return stakerLatestData[staker].delegatedStake; } function getLatestStakeBalance(address staker) external view returns (uint256) { return stakerLatestData[staker].stake; } function getLatestStakerData(address staker) external view override returns ( uint256 stake, uint256 delegatedStake, address representative ) { stake = stakerLatestData[staker].stake; delegatedStake = stakerLatestData[staker].delegatedStake; representative = stakerLatestData[staker].representative == address(0) ? staker : stakerLatestData[staker].representative; } /** * @dev separate logics from withdraw, so staker can withdraw as long as amount <= staker's deposit amount calling this function from withdraw function, ignore reverting * @param staker staker that is withdrawing * @param amount amount to withdraw * @param curEpoch current epoch */ function handleWithdrawal( address staker, uint256 amount, uint256 curEpoch ) external { require(msg.sender == address(this), "only staking contract"); initDataIfNeeded(staker, curEpoch); // Note: update latest stake will be done after this function // update staker's data for next epoch stakerPerEpochData[curEpoch + 1][staker].stake = stakerPerEpochData[curEpoch + 1][staker].stake.sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW address representative = stakerPerEpochData[curEpoch][staker].representative; uint256 curStake = stakerPerEpochData[curEpoch][staker].stake; uint256 lStakeBal = stakerLatestData[staker].stake.sub(amount); uint256 newStake = curStake.min(lStakeBal); uint256 reduceAmount = curStake.sub(newStake); // newStake is always <= curStake if (reduceAmount > 0) { if (representative != staker) { initDataIfNeeded(representative, curEpoch); // staker has delegated to representative, withdraw will affect representative's delegated stakes stakerPerEpochData[curEpoch][representative].delegatedStake = stakerPerEpochData[curEpoch][representative].delegatedStake.sub(reduceAmount); } stakerPerEpochData[curEpoch][staker].stake = newStake; // call KyberDao to reduce reward, if staker has delegated, then pass his representative if (address(kyberDao) != address(0)) { // don't revert if KyberDao revert so data will be updated correctly (bool success, ) = address(kyberDao).call( abi.encodeWithSignature( "handleWithdrawal(address,uint256)", representative, reduceAmount ) ); if (!success) { emit WithdrawDataUpdateFailed(curEpoch, staker, amount); } } } representative = stakerPerEpochData[curEpoch + 1][staker].representative; if (representative != staker) { initDataIfNeeded(representative, curEpoch); stakerPerEpochData[curEpoch + 1][representative].delegatedStake = stakerPerEpochData[curEpoch + 1][representative].delegatedStake.sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW stakerLatestData[representative].delegatedStake = stakerLatestData[representative].delegatedStake.sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW } } /** * @dev initialize data if it has not been initialized yet * @param staker staker's address to initialize * @param epoch should be current epoch */ function initDataIfNeeded(address staker, uint256 epoch) internal { address representative = stakerLatestData[staker].representative; if (representative == address(0)) { // not delegate to anyone, consider as delegate to yourself stakerLatestData[staker].representative = staker; representative = staker; } uint256 ldStake = stakerLatestData[staker].delegatedStake; uint256 lStakeBal = stakerLatestData[staker].stake; if (!hasInited[epoch][staker]) { hasInited[epoch][staker] = true; StakerData storage stakerData = stakerPerEpochData[epoch][staker]; stakerData.representative = representative; stakerData.delegatedStake = ldStake; stakerData.stake = lStakeBal; } // whenever stakers deposit/withdraw/delegate, the current and next epoch data need to be updated // as the result, we will also initialize data for staker at the next epoch if (!hasInited[epoch + 1][staker]) { hasInited[epoch + 1][staker] = true; StakerData storage nextEpochStakerData = stakerPerEpochData[epoch + 1][staker]; nextEpochStakerData.representative = representative; nextEpochStakerData.delegatedStake = ldStake; nextEpochStakerData.stake = lStakeBal; } } } // File: contracts/sol6/utils/Utils5.sol pragma solidity 0.6.6; /** * @title Kyber utility file * mostly shared constants and rate calculation helpers * inherited by most of kyber contracts. * previous utils implementations are for previous solidity versions. */ contract Utils5 { IERC20 internal constant ETH_TOKEN_ADDRESS = IERC20( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); uint256 internal constant PRECISION = (10**18); uint256 internal constant MAX_QTY = (10**28); // 10B tokens uint256 internal constant MAX_RATE = (PRECISION * 10**7); // up to 10M tokens per eth uint256 internal constant MAX_DECIMALS = 18; uint256 internal constant ETH_DECIMALS = 18; uint256 constant BPS = 10000; // Basic Price Steps. 1 step = 0.01% uint256 internal constant MAX_ALLOWANCE = uint256(-1); // token.approve inifinite mapping(IERC20 => uint256) internal decimals; function getUpdateDecimals(IERC20 token) internal returns (uint256) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint256 tokenDecimals = decimals[token]; // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if (tokenDecimals == 0) { tokenDecimals = token.decimals(); decimals[token] = tokenDecimals; } return tokenDecimals; } function setDecimals(IERC20 token) internal { if (decimals[token] != 0) return; //already set if (token == ETH_TOKEN_ADDRESS) { decimals[token] = ETH_DECIMALS; } else { decimals[token] = token.decimals(); } } /// @dev get the balance of a user. /// @param token The token type /// @return The balance function getBalance(IERC20 token, address user) internal view returns (uint256) { if (token == ETH_TOKEN_ADDRESS) { return user.balance; } else { return token.balanceOf(user); } } function getDecimals(IERC20 token) internal view returns (uint256) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint256 tokenDecimals = decimals[token]; // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if (tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDestAmount( IERC20 src, IERC20 dest, uint256 srcAmount, uint256 rate ) internal view returns (uint256) { return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate); } function calcSrcAmount( IERC20 src, IERC20 dest, uint256 destAmount, uint256 rate ) internal view returns (uint256) { return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate); } function calcDstQty( uint256 srcQty, uint256 srcDecimals, uint256 dstDecimals, uint256 rate ) internal pure returns (uint256) { require(srcQty <= MAX_QTY, "srcQty > MAX_QTY"); require(rate <= MAX_RATE, "rate > MAX_RATE"); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS"); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS"); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty( uint256 dstQty, uint256 srcDecimals, uint256 dstDecimals, uint256 rate ) internal pure returns (uint256) { require(dstQty <= MAX_QTY, "dstQty > MAX_QTY"); require(rate <= MAX_RATE, "rate > MAX_RATE"); //source quantity is rounded up. to avoid dest quantity being too low. uint256 numerator; uint256 denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS"); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS"); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } function calcRateFromQty( uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals ) internal pure returns (uint256) { require(srcAmount <= MAX_QTY, "srcAmount > MAX_QTY"); require(destAmount <= MAX_QTY, "destAmount > MAX_QTY"); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS"); return ((destAmount * PRECISION) / ((10**(dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS"); return ((destAmount * PRECISION * (10**(srcDecimals - dstDecimals))) / srcAmount); } } function minOf(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } } // File: contracts/sol6/Dao/KyberDao.sol pragma solidity 0.6.6; /** * @notice This contract is using SafeMath for uint, which is inherited from EpochUtils Some events are moved to interface, easier for public uses * @dev Network fee campaign: options are fee in bps * BRR fee handler campaign: options are combined of rebate (left most 128 bits) + reward (right most 128 bits) * General campaign: options are from 1 to num_options */ contract KyberDao is IKyberDao, EpochUtils, ReentrancyGuard, Utils5, DaoOperator { // max number of campaigns for each epoch uint256 public constant MAX_EPOCH_CAMPAIGNS = 10; // max number of options for each campaign uint256 public constant MAX_CAMPAIGN_OPTIONS = 8; uint256 internal constant POWER_128 = 2**128; enum CampaignType {General, NetworkFee, FeeHandlerBRR} struct FormulaData { uint256 minPercentageInPrecision; uint256 cInPrecision; uint256 tInPrecision; } struct CampaignVoteData { uint256 totalVotes; uint256[] votePerOption; } struct Campaign { CampaignType campaignType; bool campaignExists; uint256 startTimestamp; uint256 endTimestamp; uint256 totalKNCSupply; // total KNC supply at the time campaign was created FormulaData formulaData; // formula params for concluding campaign result bytes link; // link to KIP, explaination of options, etc. uint256[] options; // data of options CampaignVoteData campaignVoteData; // campaign vote data: total votes + vote per option } struct BRRData { uint256 rewardInBps; uint256 rebateInBps; } uint256 public minCampaignDurationInSeconds = 4 days; IERC20 public immutable kncToken; IKyberStaking public immutable staking; // use to generate increasing campaign ID uint256 public numberCampaigns = 0; mapping(uint256 => Campaign) internal campaignData; // epochCampaigns[epoch]: list campaign IDs for an epoch (epoch => campaign IDs) mapping(uint256 => uint256[]) internal epochCampaigns; // totalEpochPoints[epoch]: total points for an epoch (epoch => total points) mapping(uint256 => uint256) internal totalEpochPoints; // numberVotes[staker][epoch]: number of campaigns that the staker has voted in an epoch mapping(address => mapping(uint256 => uint256)) public numberVotes; // stakerVotedOption[staker][campaignID]: staker's voted option ID for a campaign mapping(address => mapping(uint256 => uint256)) public stakerVotedOption; uint256 internal latestNetworkFeeResult; // epoch => campaignID for network fee campaigns mapping(uint256 => uint256) public networkFeeCampaigns; // latest BRR data (reward and rebate in bps) BRRData internal latestBrrData; // epoch => campaignID for brr campaigns mapping(uint256 => uint256) public brrCampaigns; event NewCampaignCreated( CampaignType campaignType, uint256 indexed campaignID, uint256 startTimestamp, uint256 endTimestamp, uint256 minPercentageInPrecision, uint256 cInPrecision, uint256 tInPrecision, uint256[] options, bytes link ); event CancelledCampaign(uint256 indexed campaignID); constructor( uint256 _epochPeriod, uint256 _startTimestamp, IERC20 _knc, uint256 _defaultNetworkFeeBps, uint256 _defaultRewardBps, uint256 _defaultRebateBps, address _daoOperator ) public DaoOperator(_daoOperator) { require(_epochPeriod > 0, "ctor: epoch period is 0"); require(_startTimestamp >= now, "ctor: start in the past"); require(_knc != IERC20(0), "ctor: knc token 0"); // in Network, maximum fee that can be taken from 1 tx is (platform fee + 2 * network fee) // so network fee should be less than 50% require(_defaultNetworkFeeBps < BPS / 2, "ctor: network fee high"); require(_defaultRewardBps.add(_defaultRebateBps) <= BPS, "reward plus rebate high"); epochPeriodInSeconds = _epochPeriod; firstEpochStartTimestamp = _startTimestamp; kncToken = _knc; latestNetworkFeeResult = _defaultNetworkFeeBps; latestBrrData = BRRData({ rewardInBps: _defaultRewardBps, rebateInBps: _defaultRebateBps }); // deploy staking contract staking = new KyberStaking({ _kncToken: _knc, _epochPeriod: _epochPeriod, _startTimestamp: _startTimestamp, _kyberDao: IKyberDao(this) }); } modifier onlyStakingContract { require(msg.sender == address(staking), "only staking contract"); _; } /** * @dev called by staking contract when staker wanted to withdraw * @param staker address of staker to reduce reward * @param reduceAmount amount voting power to be reduced for each campaign staker has voted at this epoch */ function handleWithdrawal(address staker, uint256 reduceAmount) external override onlyStakingContract { // staking shouldn't call this func with reduce amount = 0 if (reduceAmount == 0) { return; } uint256 curEpoch = getCurrentEpochNumber(); uint256 numVotes = numberVotes[staker][curEpoch]; // staker has not participated in any campaigns at the current epoch if (numVotes == 0) { return; } // update total points for current epoch totalEpochPoints[curEpoch] = totalEpochPoints[curEpoch].sub(numVotes.mul(reduceAmount)); // update voted count for each campaign staker has voted uint256[] memory campaignIDs = epochCampaigns[curEpoch]; for (uint256 i = 0; i < campaignIDs.length; i++) { uint256 campaignID = campaignIDs[i]; uint256 votedOption = stakerVotedOption[staker][campaignID]; if (votedOption == 0) { continue; } // staker has not voted yet Campaign storage campaign = campaignData[campaignID]; if (campaign.endTimestamp >= now) { // the staker has voted for this campaign and the campaign has not ended yet // reduce total votes and vote count of staker's voted option campaign.campaignVoteData.totalVotes = campaign.campaignVoteData.totalVotes.sub(reduceAmount); //injected INTEGER OVERFLOW OR UNDERFLOW campaign.campaignVoteData.votePerOption[votedOption - 1] = campaign.campaignVoteData.votePerOption[votedOption - 1].sub(reduceAmount); //injected INTEGER OVERFLOW OR UNDERFLOW } } } /** * @dev create new campaign, only called by daoOperator * @param campaignType type of campaign (General, NetworkFee, FeeHandlerBRR) * @param startTimestamp timestamp to start running the campaign * @param endTimestamp timestamp to end this campaign * @param minPercentageInPrecision min percentage (in precision) for formula to conclude campaign * @param cInPrecision c value (in precision) for formula to conclude campaign * @param tInPrecision t value (in precision) for formula to conclude campaign * @param options list values of options to vote for this campaign * @param link additional data for this campaign */ function submitNewCampaign( CampaignType campaignType, uint256 startTimestamp, uint256 endTimestamp, uint256 minPercentageInPrecision, uint256 cInPrecision, uint256 tInPrecision, uint256[] calldata options, bytes calldata link ) external onlyDaoOperator returns (uint256 campaignID) { // campaign epoch could be different from current epoch // as we allow to create campaign of next epoch as well uint256 campaignEpoch = getEpochNumber(startTimestamp); validateCampaignParams( campaignType, startTimestamp, endTimestamp, minPercentageInPrecision, cInPrecision, tInPrecision, options ); numberCampaigns = numberCampaigns.add(1); campaignID = numberCampaigns; // add campaignID into the list campaign IDs epochCampaigns[campaignEpoch].push(campaignID); // update network fee or fee handler brr campaigns if (campaignType == CampaignType.NetworkFee) { networkFeeCampaigns[campaignEpoch] = campaignID; } else if (campaignType == CampaignType.FeeHandlerBRR) { brrCampaigns[campaignEpoch] = campaignID; } FormulaData memory formulaData = FormulaData({ minPercentageInPrecision: minPercentageInPrecision, cInPrecision: cInPrecision, tInPrecision: tInPrecision }); CampaignVoteData memory campaignVoteData = CampaignVoteData({ totalVotes: 0, votePerOption: new uint256[](options.length) }); campaignData[campaignID] = Campaign({ campaignExists: true, campaignType: campaignType, startTimestamp: startTimestamp, endTimestamp: endTimestamp, totalKNCSupply: kncToken.totalSupply(), link: link, formulaData: formulaData, options: options, campaignVoteData: campaignVoteData }); emit NewCampaignCreated( campaignType, campaignID, startTimestamp, endTimestamp, minPercentageInPrecision, cInPrecision, tInPrecision, options, link ); } /** * @dev cancel a campaign with given id, called by daoOperator only * only can cancel campaigns that have not started yet * @param campaignID id of the campaign to cancel */ function cancelCampaign(uint256 campaignID) external onlyDaoOperator { Campaign storage campaign = campaignData[campaignID]; require(campaign.campaignExists, "cancelCampaign: campaignID doesn't exist"); require(campaign.startTimestamp > now, "cancelCampaign: campaign already started"); uint256 epoch = getEpochNumber(campaign.startTimestamp); if (campaign.campaignType == CampaignType.NetworkFee) { delete networkFeeCampaigns[epoch]; } else if (campaign.campaignType == CampaignType.FeeHandlerBRR) { delete brrCampaigns[epoch]; } delete campaignData[campaignID]; uint256[] storage campaignIDs = epochCampaigns[epoch]; for (uint256 i = 0; i < campaignIDs.length; i++) { if (campaignIDs[i] == campaignID) { // remove this campaign id out of list campaignIDs[i] = campaignIDs[campaignIDs.length - 1]; campaignIDs.pop(); break; } } emit CancelledCampaign(campaignID); } /** * @dev vote for an option of a campaign * options are indexed from 1 to number of options * @param campaignID id of campaign to vote for * @param option id of options to vote for */ function vote(uint256 campaignID, uint256 option) external override { validateVoteOption(campaignID, option); address staker = msg.sender; uint256 curEpoch = getCurrentEpochNumber(); (uint256 stake, uint256 dStake, address representative) = staking.initAndReturnStakerDataForCurrentEpoch(staker); uint256 totalStake = representative == staker ? stake.add(dStake) : dStake; uint256 lastVotedOption = stakerVotedOption[staker][campaignID]; CampaignVoteData storage voteData = campaignData[campaignID].campaignVoteData; if (lastVotedOption == 0) { // increase number campaigns that the staker has voted at the current epoch numberVotes[staker][curEpoch]++; totalEpochPoints[curEpoch] = totalEpochPoints[curEpoch].add(totalStake); // increase voted count for this option voteData.votePerOption[option - 1] = voteData.votePerOption[option - 1].add(totalStake); // increase total votes voteData.totalVotes = voteData.totalVotes.add(totalStake); } else if (lastVotedOption != option) { // deduce previous option voted count voteData.votePerOption[lastVotedOption - 1] = voteData.votePerOption[lastVotedOption - 1].sub(totalStake); // increase new option voted count voteData.votePerOption[option - 1] = voteData.votePerOption[option - 1].add(totalStake); } stakerVotedOption[staker][campaignID] = option; emit Voted(staker, curEpoch, campaignID, option); } /** * @dev get latest network fee data + expiry timestamp * conclude network fee campaign if needed and caching latest result in KyberDao */ function getLatestNetworkFeeDataWithCache() external override returns (uint256 feeInBps, uint256 expiryTimestamp) { (feeInBps, expiryTimestamp) = getLatestNetworkFeeData(); // cache latest data latestNetworkFeeResult = feeInBps; } /** * @dev return latest burn/reward/rebate data, also affecting epoch + expiry timestamp * conclude brr campaign if needed and caching latest result in KyberDao */ function getLatestBRRDataWithCache() external override returns ( uint256 burnInBps, uint256 rewardInBps, uint256 rebateInBps, uint256 epoch, uint256 expiryTimestamp ) { (burnInBps, rewardInBps, rebateInBps, epoch, expiryTimestamp) = getLatestBRRData(); latestBrrData.rewardInBps = rewardInBps; latestBrrData.rebateInBps = rebateInBps; } /** * @dev some epochs have reward but no one can claim, for example: epoch 0 * return true if should burn all that reward * @param epoch epoch to check for burning reward */ function shouldBurnRewardForEpoch(uint256 epoch) external view override returns (bool) { uint256 curEpoch = getCurrentEpochNumber(); if (epoch >= curEpoch) { return false; } return totalEpochPoints[epoch] == 0; } // return list campaign ids for epoch, excluding non-existed ones function getListCampaignIDs(uint256 epoch) external view returns (uint256[] memory campaignIDs) { campaignIDs = epochCampaigns[epoch]; } // return total points for an epoch function getTotalEpochPoints(uint256 epoch) external view returns (uint256) { return totalEpochPoints[epoch]; } function getCampaignDetails(uint256 campaignID) external view returns ( CampaignType campaignType, uint256 startTimestamp, uint256 endTimestamp, uint256 totalKNCSupply, uint256 minPercentageInPrecision, uint256 cInPrecision, uint256 tInPrecision, bytes memory link, uint256[] memory options ) { Campaign storage campaign = campaignData[campaignID]; campaignType = campaign.campaignType; startTimestamp = campaign.startTimestamp; endTimestamp = campaign.endTimestamp; totalKNCSupply = campaign.totalKNCSupply; minPercentageInPrecision = campaign.formulaData.minPercentageInPrecision; cInPrecision = campaign.formulaData.cInPrecision; tInPrecision = campaign.formulaData.tInPrecision; link = campaign.link; options = campaign.options; } function getCampaignVoteCountData(uint256 campaignID) external view returns (uint256[] memory voteCounts, uint256 totalVoteCount) { CampaignVoteData memory voteData = campaignData[campaignID].campaignVoteData; totalVoteCount = voteData.totalVotes; voteCounts = voteData.votePerOption; } /** * @dev return staker's reward percentage in precision for a past epoch only * fee handler should call this function when a staker wants to claim reward * return 0 if staker has no votes or stakes */ function getPastEpochRewardPercentageInPrecision(address staker, uint256 epoch) external view override returns (uint256) { // return 0 if epoch is not past epoch uint256 curEpoch = getCurrentEpochNumber(); if (epoch >= curEpoch) { return 0; } return getRewardPercentageInPrecision(staker, epoch); } /** * @dev return staker's reward percentage in precision for the current epoch */ function getCurrentEpochRewardPercentageInPrecision(address staker) external view override returns (uint256) { uint256 curEpoch = getCurrentEpochNumber(); return getRewardPercentageInPrecision(staker, curEpoch); } /** * @dev return campaign winning option and its value * return (0, 0) if campaign does not exist * return (0, 0) if campaign has not ended yet * return (0, 0) if campaign has no winning option based on the formula * @param campaignID id of campaign to get result */ function getCampaignWinningOptionAndValue(uint256 campaignID) public view returns (uint256 optionID, uint256 value) { Campaign storage campaign = campaignData[campaignID]; if (!campaign.campaignExists) { return (0, 0); } // not exist // campaign has not ended yet, return 0 as winning option if (campaign.endTimestamp > now) { return (0, 0); } uint256 totalSupply = campaign.totalKNCSupply; // something is wrong here, total KNC supply shouldn't be 0 if (totalSupply == 0) { return (0, 0); } uint256 totalVotes = campaign.campaignVoteData.totalVotes; uint256[] memory voteCounts = campaign.campaignVoteData.votePerOption; // Finding option with most votes uint256 winningOption = 0; uint256 maxVotedCount = 0; for (uint256 i = 0; i < voteCounts.length; i++) { if (voteCounts[i] > maxVotedCount) { winningOption = i + 1; maxVotedCount = voteCounts[i]; } else if (voteCounts[i] == maxVotedCount) { winningOption = 0; } } // more than 1 options have same vote count if (winningOption == 0) { return (0, 0); } FormulaData memory formulaData = campaign.formulaData; // compute voted percentage (in precision) uint256 votedPercentage = totalVotes.mul(PRECISION).div(campaign.totalKNCSupply); // total voted percentage is below min acceptable percentage, no winning option if (formulaData.minPercentageInPrecision > votedPercentage) { return (0, 0); } // as we already limit value for c & t, no need to check for overflow here uint256 x = formulaData.tInPrecision.mul(votedPercentage).div(PRECISION); if (x <= formulaData.cInPrecision) { // threshold is not negative, need to compare with voted count uint256 y = formulaData.cInPrecision.sub(x); // (most voted option count / total votes) is below threshold, no winining option if (maxVotedCount.mul(PRECISION) < y.mul(totalVotes)) { return (0, 0); } } optionID = winningOption; value = campaign.options[optionID - 1]; } /** * @dev return latest network fee and expiry timestamp */ function getLatestNetworkFeeData() public view override returns (uint256 feeInBps, uint256 expiryTimestamp) { uint256 curEpoch = getCurrentEpochNumber(); feeInBps = latestNetworkFeeResult; // expiryTimestamp = firstEpochStartTimestamp + curEpoch * epochPeriodInSeconds - 1; expiryTimestamp = firstEpochStartTimestamp.add(curEpoch.mul(epochPeriodInSeconds)).sub(1); if (curEpoch == 0) { return (feeInBps, expiryTimestamp); } uint256 campaignID = networkFeeCampaigns[curEpoch.sub(1)]; if (campaignID == 0) { // don't have network fee campaign, return latest result return (feeInBps, expiryTimestamp); } uint256 winningOption; (winningOption, feeInBps) = getCampaignWinningOptionAndValue(campaignID); if (winningOption == 0) { // fallback to previous result feeInBps = latestNetworkFeeResult; } return (feeInBps, expiryTimestamp); } /** * @dev return latest brr result, conclude brr campaign if needed */ function getLatestBRRData() public view returns ( uint256 burnInBps, uint256 rewardInBps, uint256 rebateInBps, uint256 epoch, uint256 expiryTimestamp ) { epoch = getCurrentEpochNumber(); // expiryTimestamp = firstEpochStartTimestamp + epoch * epochPeriodInSeconds - 1; expiryTimestamp = firstEpochStartTimestamp.add(epoch.mul(epochPeriodInSeconds)).sub(1); rewardInBps = latestBrrData.rewardInBps; rebateInBps = latestBrrData.rebateInBps; if (epoch > 0) { uint256 campaignID = brrCampaigns[epoch.sub(1)]; if (campaignID != 0) { uint256 winningOption; uint256 brrData; (winningOption, brrData) = getCampaignWinningOptionAndValue(campaignID); if (winningOption > 0) { // has winning option, update reward and rebate value (rebateInBps, rewardInBps) = getRebateAndRewardFromData(brrData); } } } burnInBps = BPS.sub(rebateInBps).sub(rewardInBps); //injected INTEGER OVERFLOW OR UNDERFLOW } // Helper functions for squeezing data function getRebateAndRewardFromData(uint256 data) public pure returns (uint256 rebateInBps, uint256 rewardInBps) { rewardInBps = data & (POWER_128.sub(1)); rebateInBps = (data.div(POWER_128)) & (POWER_128.sub(1)); } /** * @dev helper func to get encoded reward and rebate * revert if validation failed */ function getDataFromRewardAndRebateWithValidation(uint256 rewardInBps, uint256 rebateInBps) public pure returns (uint256 data) { require(rewardInBps.add(rebateInBps) <= BPS, "reward plus rebate high"); data = (rebateInBps.mul(POWER_128)).add(rewardInBps); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev options are indexed from 1 */ function validateVoteOption(uint256 campaignID, uint256 option) internal view { Campaign storage campaign = campaignData[campaignID]; require(campaign.campaignExists, "vote: campaign doesn't exist"); require(campaign.startTimestamp <= now, "vote: campaign not started"); require(campaign.endTimestamp >= now, "vote: campaign already ended"); // option is indexed from 1 to options.length require(option > 0, "vote: option is 0"); require(option <= campaign.options.length, "vote: option is not in range"); } /** * @dev Validate params to check if we could submit a new campaign with these params */ function validateCampaignParams( CampaignType campaignType, uint256 startTimestamp, uint256 endTimestamp, uint256 minPercentageInPrecision, uint256 cInPrecision, uint256 tInPrecision, uint256[] memory options ) internal view { // now <= start timestamp < end timestamp require(startTimestamp >= now, "validateParams: start in the past"); // campaign duration must be at least min campaign duration // endTimestamp - startTimestamp + 1 >= minCampaignDurationInSeconds, require( endTimestamp.add(1) >= startTimestamp.add(minCampaignDurationInSeconds), "validateParams: campaign duration is low" ); uint256 startEpoch = getEpochNumber(startTimestamp); uint256 endEpoch = getEpochNumber(endTimestamp); require( epochCampaigns[startEpoch].length < MAX_EPOCH_CAMPAIGNS, "validateParams: too many campaigns" ); // start timestamp and end timestamp must be in the same epoch require(startEpoch == endEpoch, "validateParams: start & end not same epoch"); uint256 currentEpoch = getCurrentEpochNumber(); require( startEpoch <= currentEpoch.add(1), "validateParams: only for current or next epochs" ); // verify number of options uint256 numOptions = options.length; require( numOptions > 1 && numOptions <= MAX_CAMPAIGN_OPTIONS, "validateParams: invalid number of options" ); // Validate option values based on campaign type if (campaignType == CampaignType.General) { // option must be positive number for (uint256 i = 0; i < options.length; i++) { require(options[i] > 0, "validateParams: general campaign option is 0"); } } else if (campaignType == CampaignType.NetworkFee) { require( networkFeeCampaigns[startEpoch] == 0, "validateParams: already had network fee campaign for this epoch" ); // network fee campaign, option must be fee in bps for (uint256 i = 0; i < options.length; i++) { // in Network, maximum fee that can be taken from 1 tx is (platform fee + 2 * network fee) // so network fee should be less than 50% require( options[i] < BPS / 2, "validateParams: network fee must be smaller then BPS / 2" ); } } else { require( brrCampaigns[startEpoch] == 0, "validateParams: already had brr campaign for this epoch" ); // brr fee handler campaign, option must be combined for reward + rebate % for (uint256 i = 0; i < options.length; i++) { // rebate (left most 128 bits) + reward (right most 128 bits) (uint256 rebateInBps, uint256 rewardInBps) = getRebateAndRewardFromData(options[i]); require( rewardInBps.add(rebateInBps) <= BPS, "validateParams: rebate + reward can't be bigger than BPS" ); } } // percentage should be smaller than or equal 100% require(minPercentageInPrecision <= PRECISION, "validateParams: min percentage is high"); // limit value of c and t to avoid overflow require(cInPrecision < POWER_128, "validateParams: c is high"); require(tInPrecision < POWER_128, "validateParams: t is high"); } /** * @dev return staker's reward percentage in precision for an epoch * return 0 if staker has no votes or stakes * called by 2 functions in KyberDao */ function getRewardPercentageInPrecision(address staker, uint256 epoch) internal view returns (uint256) { uint256 numVotes = numberVotes[staker][epoch]; // no votes, no rewards if (numVotes == 0) { return 0; } (uint256 stake, uint256 delegatedStake, address representative) = staking.getStakerRawData(staker, epoch); uint256 totalStake = representative == staker ? stake.add(delegatedStake) : delegatedStake; if (totalStake == 0) { return 0; } uint256 points = numVotes.mul(totalStake); uint256 totalPts = totalEpochPoints[epoch]; // staker's reward percentage should be <= 100% assert(points <= totalPts); return points.mul(PRECISION).div(totalPts); } }
calls to set delegation for msg.sender, will take effect from the next epoch newRepresentative address to delegate to/ nothing changes here reduce delegatedStake for curRepresentative if needed ignore if staker is delegating back to himself
function delegate(address newRepresentative) external override { require(newRepresentative != address(0), "delegate: representative 0"); address staker = msg.sender; uint256 curEpoch = getCurrentEpochNumber(); initDataIfNeeded(staker, curEpoch); address curRepresentative = stakerPerEpochData[curEpoch + 1][staker].representative; if (newRepresentative == curRepresentative) { return; } uint256 updatedStake = stakerPerEpochData[curEpoch + 1][staker].stake; if (curRepresentative != staker) { initDataIfNeeded(curRepresentative, curEpoch); stakerPerEpochData[curEpoch + 1][curRepresentative].delegatedStake = stakerPerEpochData[curEpoch + 1][curRepresentative].delegatedStake.sub(updatedStake); stakerLatestData[curRepresentative].delegatedStake = stakerLatestData[curRepresentative].delegatedStake.sub(updatedStake); emit Delegated(staker, curRepresentative, curEpoch, false); } stakerLatestData[staker].representative = newRepresentative; stakerPerEpochData[curEpoch + 1][staker].representative = newRepresentative; if (newRepresentative != staker) { initDataIfNeeded(newRepresentative, curEpoch); stakerPerEpochData[curEpoch + 1][newRepresentative].delegatedStake = stakerPerEpochData[curEpoch + 1][newRepresentative].delegatedStake.add(updatedStake); stakerLatestData[newRepresentative].delegatedStake = stakerLatestData[newRepresentative].delegatedStake.add(updatedStake); emit Delegated(staker, newRepresentative, curEpoch, true); } }
1,774,681
pragma solidity 0.5.4; import "@daostack/arc/contracts/controller/Avatar.sol"; import "@daostack/arc/contracts/controller/ControllerInterface.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../identity/Identity.sol"; import "../../identity/IdentityGuard.sol"; import "../../token/GoodDollar.sol"; import "./ActivePeriod.sol"; import "./SchemeGuard.sol"; /* @title Base contract template for UBI scheme */ contract AbstractUBI is IdentityGuard, ActivePeriod, SchemeGuard { using SafeMath for uint256; uint256 initialReserve; uint256 public claimDistribution; struct Day { mapping (address => bool) hasClaimed; uint256 amountOfClaimers; uint256 claimAmount; } mapping (uint => Day) claimDay; uint public currentDay; uint public lastCalc; event UBIClaimed(address indexed claimer, uint256 amount); event UBIEnded(uint256 claimers, uint256 claimamount); /** * @dev Constructor. Checks if avatar is a zero address * and if periodEnd variable is after periodStart. * @param _avatar the avatar contract * @param _periodStart period from when the contract is able to start * @param _periodEnd period from when the contract is able to end */ constructor( Avatar _avatar, Identity _identity, uint256 _initialReserve, uint _periodStart, uint _periodEnd ) public IdentityGuard(_identity) ActivePeriod(_periodStart, _periodEnd) SchemeGuard(_avatar) { initialReserve = _initialReserve; } /** * @dev function that returns an uint256 that * represents the amount each claimer can claim. * @param reserve the account balance to calculate from * @return The distribution for each claimer */ function distributionFormula(uint256 reserve, address user) internal returns(uint256); /* @dev function that gets the amount of people who claimed on the given day * @param day the day to get claimer count from, with 0 being the starting day * @returns an integer indicating the amount of people who claimed that day */ function getClaimerCount(uint day) public view returns (uint256) { return claimDay[day].amountOfClaimers; } /* @dev function that gets the amount that was claimed on the given day * @param day the day to get claimer count from, with 0 being the starting day * @returns an integer indicating the amount that has been claimed on the given day */ function getClaimAmount(uint day) public view returns (uint256) { return claimDay[day].claimAmount; } /* @dev function that gets count of claimers and amount claimed for the most recent * day where claiming transpired. * @returns the amount of claimers and the amount claimed. */ function getDailyStats() public view returns (uint256 count, uint256 amount) { return (getClaimerCount(currentDay), getClaimAmount(currentDay)); } /* @dev Function that commences distribution period on contract. * Can only be called after periodStart and before periodEnd and * can only be done once. The reserve is sent * to this contract to allow claimers to claim from said reserve. * The claim distribution is then calculated and true is returned * to indicate that claiming can be done. */ function start() public onlyRegistered returns(bool) { require(super.start()); currentDay = 0; lastCalc = now; // Transfer the fee reserve to this contract DAOToken token = avatar.nativeToken(); if(initialReserve > 0) { require(initialReserve <= token.balanceOf(address(avatar)), "Not enough funds to start"); controller.genericCall( address(token), abi.encodeWithSignature("transfer(address,uint256)", address(this), initialReserve), avatar, 0); } return true; } /** * @dev Function that ends the claiming period. Can only be done if * Contract has been started and periodEnd is passed. * Sends the remaining funds on contract back to the avatar contract * address */ function end(Avatar /*_avatar*/) public requirePeriodEnd { DAOToken token = avatar.nativeToken(); uint256 remainingReserve = token.balanceOf(address(this)); if (remainingReserve > 0) { token.transfer(address(avatar), remainingReserve); } super.end(avatar); } /* @dev Function that claims UBI to message sender. * Each claimer can only claim once per UBI contract */ function claim() public requireActive onlyClaimer onlyAddedBefore(periodStart) returns(bool) { require(!claimDay[currentDay].hasClaimed[msg.sender], "has already claimed"); GoodDollar token = GoodDollar(address(avatar.nativeToken())); claimDay[currentDay].hasClaimed[msg.sender] = true; token.transfer(msg.sender, claimDistribution); claimDay[currentDay].amountOfClaimers = claimDay[currentDay].amountOfClaimers.add(1); claimDay[currentDay].claimAmount = claimDay[currentDay].claimAmount.add(claimDistribution); emit UBIClaimed(msg.sender, claimDistribution); return true; } } /* @title UBI scheme contract responsible for calculating distribution * and performing the distribution itself */ contract UBI is AbstractUBI { /* @dev Constructor. Checks if avatar is a zero address * and if periodEnd variable is after periodStart. * @param _avatar the avatar contract * @param _identity the identity contract * @param _periodStart period from when the contract is able to start * @param _periodEnd period from when the contract is able to end */ constructor( Avatar _avatar, Identity _identity, uint256 _initialReserve, uint _periodStart, uint _periodEnd ) public AbstractUBI(_avatar, _identity, _initialReserve, _periodStart, _periodEnd) {} /* @dev function that returns an uint256 that * represents the amount each claimer can claim. * @param reserve the account balance to calculate from * @return The reserve divided by the amount of registered claimers */ function distributionFormula(uint256 reserve, address /*user*/) internal returns(uint256) { uint claimers = identity.getClaimerCount(); return reserve.div(claimers); } /* @dev starts scheme and calculates dispersion of UBI * @returns a bool indicating if scheme has started */ function start() public returns (bool) { require(super.start()); DAOToken token = avatar.nativeToken(); claimDistribution = distributionFormula(token.balanceOf(address(this)), address(0)); } }
Function that claims UBI to message sender. Each claimer can only claim once per UBI contract/
function claim() public requireActive onlyClaimer onlyAddedBefore(periodStart) returns(bool) { require(!claimDay[currentDay].hasClaimed[msg.sender], "has already claimed"); GoodDollar token = GoodDollar(address(avatar.nativeToken())); claimDay[currentDay].hasClaimed[msg.sender] = true; token.transfer(msg.sender, claimDistribution); claimDay[currentDay].amountOfClaimers = claimDay[currentDay].amountOfClaimers.add(1); claimDay[currentDay].claimAmount = claimDay[currentDay].claimAmount.add(claimDistribution); emit UBIClaimed(msg.sender, claimDistribution); return true; }
13,135,145
// File: contracts/exchange/ownable.sol pragma solidity 0.5.6; /** * @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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/exchange/safe-math.sol pragma solidity 0.5.6; /** * @dev Math operations with safety checks that throw on error. This contract is based on the * source code at: * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol. */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. * @param _factor1 Factor number. * @param _factor2 Factor number. * @return The product of the two factors. */ function mul( uint256 _factor1, uint256 _factor2 ) internal pure returns (uint256 product) { // 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 (_factor1 == 0) { return 0; } product = _factor1 * _factor2; require(product / _factor1 == _factor2); } /** * @dev Integer division of two numbers, truncating the quotient, reverts on division by zero. * @param _dividend Dividend number. * @param _divisor Divisor number. * @return The quotient. */ function div( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 quotient) { // Solidity automatically asserts when dividing by 0, using all gas. require(_divisor > 0); quotient = _dividend / _divisor; // assert(_dividend == _divisor * quotient + _dividend % _divisor); // There is no case in which this doesn't hold. } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). * @param _minuend Minuend number. * @param _subtrahend Subtrahend number. * @return Difference. */ function sub( uint256 _minuend, uint256 _subtrahend ) internal pure returns (uint256 difference) { require(_subtrahend <= _minuend); difference = _minuend - _subtrahend; } /** * @dev Adds two numbers, reverts on overflow. * @param _addend1 Number. * @param _addend2 Number. * @return Sum. */ function add( uint256 _addend1, uint256 _addend2 ) internal pure returns (uint256 sum) { sum = _addend1 + _addend2; require(sum >= _addend1); } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), reverts when * dividing by zero. * @param _dividend Number. * @param _divisor Number. * @return Remainder. */ function mod( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 remainder) { require(_divisor != 0); remainder = _dividend % _divisor; } } // File: contracts/exchange/erc721-token-receiver.sol pragma solidity 0.5.6; /** * @dev ERC-721 interface for accepting safe transfers. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. * @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4); function onERC721Received( address _from, uint256 _tokenId, bytes calldata _data ) external returns (bytes4); } // File: contracts/exchange/ERC165Checker.sol pragma solidity ^0.5.6; /** * @title ERC165Checker * @dev Use `using ERC165Checker for address`; to include this library * https://eips.ethereum.org/EIPS/eip-165 */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /* * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @notice Query if a contract supports ERC165 * @param account The address of the contract to query for support of ERC165 * @return true if the contract at account implements ERC165 */ function _supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @notice Query if a contract implements an interface, also checks support of ERC165 * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Interface identification is specified in ERC-165. */ function _supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return _supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @notice Query if a contract implements interfaces, also checks support of ERC165 * @param account The address of the contract to query for support of an interface * @param interfaceIds A list of interface identifiers, as specified in ERC-165 * @return true if the contract at account indicates support all interfaces in the * interfaceIds list, false otherwise * @dev Interface identification is specified in ERC-165. */ function _supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!_supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with the `supportsERC165` method in this library. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool success, bool result) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); // solhint-disable-next-line no-inline-assembly assembly { let encodedParams_data := add(0x20, encodedParams) let encodedParams_size := mload(encodedParams) let output := mload(0x40) // Find empty storage location using "free memory pointer" mstore(output, 0x0) success := staticcall( 30000, // 30k gas account, // To addr encodedParams_data, encodedParams_size, output, 0x20 // Outputs are 32 bytes long ) result := mload(output) // Load the result } } } // File: contracts/exchange/exchange.sol pragma solidity 0.5.6; /** * @dev Interface to Interative with ERC-721 Contract. */ contract Erc721Interface { function transferFrom(address _from, address _to, uint256 _tokenId) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool); function ownerOf(uint256 _tokenId) external view returns (address _owner); } /** * @dev Interface to Interative with CryptoKitties Contract. */ contract KittyInterface { mapping (uint256 => address) public kittyIndexToApproved; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function ownerOf(uint256 _tokenId) external view returns (address _owner); } contract Exchange is Ownable, ERC721TokenReceiver { using SafeMath for uint256; using SafeMath for uint; using ERC165Checker for address; /** * @dev CryptoKitties KittyCore Contract address. */ address constant internal CryptoKittiesAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant ERC721_RECEIVED_THREE_INPUT = 0xf0b9e5ba; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant ERC721_RECEIVED_FOUR_INPUT = 0x150b7a02; /** * @dev A mapping from NFT ID to the owner address. */ mapping (address => mapping (uint256 => address)) internal TokenToOwner; /** * @dev A mapping from owner address to specific contract address's all NFT IDs */ mapping (address => mapping (address => uint256[])) internal OwnerToTokens; /** * @dev A mapping from specific contract address's NFT ID to its index in owner tokens array */ mapping (address => mapping(uint256 => uint256)) internal TokenToIndex; /** * @dev A mapping from the address to all order it owns */ mapping (address => bytes32[]) internal OwnerToOrders; /** * @dev A mapping from order to owner address */ mapping (bytes32 => address) internal OrderToOwner; /** * @dev A mapping from order to its index in owner order array. */ mapping (bytes32 => uint) internal OrderToIndex; /** * @dev A mapping from matchorder to owner address */ mapping (bytes32 => address) internal MatchOrderToOwner; /** * @dev A mapping from order to all matchorder it owns */ mapping (bytes32 => bytes32[]) internal OrderToMatchOrders; /** * @dev A mapping from matchorder to its index in order's matchorder array */ mapping (bytes32 => mapping(bytes32 => uint)) internal OrderToMatchOrderIndex; /** * @dev A mapping from order to confirm it exist or not */ mapping (bytes32 => bool) internal OrderToExist; /** * @dev An array which contains all support NFT interface in Exchange */ bytes4[] internal SupportNFTInterface; /** * @dev order and matchorder is equal to keccak256(contractAddress, tokenId, owner), * because order is just a hash, so OrderObj is use to record details. */ struct OrderObj { // NFT's owner address owner; // NFT's contract address address contractAddress; // NFT's id uint256 tokenId; } /** * @dev An mapping from order or matchorder's hash to it order obj */ mapping (bytes32 => OrderObj) internal HashToOrderObj; /** * @dev This emits when someone called receiveErc721Token and success transfer NFT to * exchange contract. * @param _from Owner of NFT * @param _contractAddress NFT's contract address * @param _tokenId NFT's id */ event ReceiveToken( address indexed _from, address _contractAddress, uint256 _tokenId ); /** * @dev This emits when someone called SendBackToken and transfer NFT from * exchange contract to it owner * @param _owner Owner of NFT * @param _contractAddress NFT's contract address * @param _tokenId NFT's id */ event SendBackToken( address indexed _owner, address _contractAddress, uint256 _tokenId ); /** * @dev This emits when send NFT happened from exchange contract to other address * @param _to exchange contract send address * @param _contractAddress NFT's contract address * @param _tokenId NFT's id */ event SendToken( address indexed _to, address _contractAddress, uint256 _tokenId ); /** * @dev This emits when an OrderObj be created * @param _hash order's hash * @param _owner Owner of NFT * @param _contractAddress NFT's contract address * @param _tokenId NFT's id */ event CreateOrderObj( bytes32 indexed _hash, address _owner, address _contractAddress, uint256 _tokenId ); /** * @dev This emits when an order be created * @param _from this order's owner * @param _orderHash this order's hash * @param _contractAddress NFT's contract address * @param _tokenId NFT's id */ event CreateOrder( address indexed _from, bytes32 indexed _orderHash, address _contractAddress, uint256 _tokenId ); /** * @dev This emits when an matchorder be created * @param _from this order's owner * @param _orderHash order's hash which matchorder pairing * @param _matchOrderHash this matchorder's hash * @param _contractAddress NFT's contract address * @param _tokenId NFT's id */ event CreateMatchOrder( address indexed _from, bytes32 indexed _orderHash, bytes32 indexed _matchOrderHash, address _contractAddress, uint256 _tokenId ); /** * @dev This emits when an order be deleted * @param _from this order's owner * @param _orderHash this order's hash */ event DeleteOrder( address indexed _from, bytes32 indexed _orderHash ); /** * @dev This emits when an matchorder be deleted * @param _from this matchorder's owner * @param _orderHash order which matchorder pairing * @param _matchOrderHash this matchorder */ event DeleteMatchOrder( address indexed _from, bytes32 indexed _orderHash, bytes32 indexed _matchOrderHash ); /** * @dev Function only be executed when massage sender is NFT's owner * @param contractAddress NFT's contract address * @param tokenId NFT's id */ modifier onlySenderIsOriginalOwner( address contractAddress, uint256 tokenId ) { require(TokenToOwner[contractAddress][tokenId] == msg.sender, "original owner should be message sender"); _; } constructor () public { //nf-token SupportNFTInterface.push(0x80ac58cd); //nf-token-metadata SupportNFTInterface.push(0x780e9d63); //nf-token-enumerable SupportNFTInterface.push(0x5b5e139f); } /** * @dev Add support NFT interface in Exchange * @notice Only Exchange owner can do tihs * @param interface_id Support NFT interface's interface_id */ function addSupportNFTInterface( bytes4 interface_id ) external onlyOwner() { SupportNFTInterface.push(interface_id); } /** * @dev NFT contract will call when it use safeTransferFrom method */ function onERC721Received( address _from, uint256 _tokenId, bytes calldata _data ) external returns (bytes4) { return ERC721_RECEIVED_THREE_INPUT; } /** * @dev NFT contract will call when it use safeTransferFrom method */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata data ) external returns(bytes4) { return ERC721_RECEIVED_FOUR_INPUT; } /** * @dev Create an order for your NFT and other people can pairing their NFT to exchange * @notice You must call receiveErc721Token method first to send your NFT to exchange contract, * if your NFT have matchorder pair with other order, then they will become Invalid until you * delete this order. * @param contractAddress NFT's contract address * @param tokenId NFT's id */ function createOrder( address contractAddress, uint256 tokenId ) external onlySenderIsOriginalOwner( contractAddress, tokenId ) { bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender)); require(OrderToOwner[orderHash] != msg.sender, "Order already exist"); _addOrder(msg.sender, orderHash); emit CreateOrder(msg.sender, orderHash, contractAddress, tokenId); } /** * @dev write order information to exchange contract. * @param sender order's owner * @param orderHash order's hash */ function _addOrder( address sender, bytes32 orderHash ) internal { uint index = OwnerToOrders[sender].push(orderHash).sub(1); OrderToOwner[orderHash] = sender; OrderToIndex[orderHash] = index; OrderToExist[orderHash] = true; } /** * @dev Delete an order if you don't want exchange NFT to anyone, or you want get your NFT back. * @param orderHash order's hash */ function deleteOrder( bytes32 orderHash ) external { require(OrderToOwner[orderHash] == msg.sender, "this order hash not belongs to this address"); _removeOrder(msg.sender, orderHash); emit DeleteOrder(msg.sender, orderHash); } /** * @dev Remove order information on exchange contract * @param sender order's owner * @param orderHash order's hash */ function _removeOrder( address sender, bytes32 orderHash ) internal { OrderToExist[orderHash] = false; delete OrderToOwner[orderHash]; uint256 orderIndex = OrderToIndex[orderHash]; uint256 lastOrderIndex = OwnerToOrders[sender].length.sub(1); if (lastOrderIndex != orderIndex){ bytes32 lastOwnerOrder = OwnerToOrders[sender][lastOrderIndex]; OwnerToOrders[sender][orderIndex] = lastOwnerOrder; OrderToIndex[lastOwnerOrder] = orderIndex; } OwnerToOrders[sender].length--; } /** * @dev If your are interested in specfic order's NFT, create a matchorder and pair with it so order's owner * can know and choose to exchange with you * @notice You must call receiveErc721Token method first to send your NFT to exchange contract, * if your NFT already create order, then you will be prohibit create matchorder until you delete this NFT's * order. * @param contractAddress NFT's contract address * @param tokenId NFT's id * @param orderHash order's hash which matchorder want to pair with */ function createMatchOrder( address contractAddress, uint256 tokenId, bytes32 orderHash ) external onlySenderIsOriginalOwner( contractAddress, tokenId ) { bytes32 matchOrderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender)); require(OrderToOwner[matchOrderHash] != msg.sender, "Order already exist"); _addMatchOrder(matchOrderHash, orderHash); emit CreateMatchOrder(msg.sender, orderHash, matchOrderHash, contractAddress, tokenId); } /** * @dev add matchorder information on exchange contract * @param matchOrderHash matchorder's hash * @param orderHash order's hash which matchorder pair with */ function _addMatchOrder( bytes32 matchOrderHash, bytes32 orderHash ) internal { uint inOrderIndex = OrderToMatchOrders[orderHash].push(matchOrderHash).sub(1); OrderToMatchOrderIndex[orderHash][matchOrderHash] = inOrderIndex; } /** * @dev delete matchorder information on exchange contract * @param matchOrderHash matchorder's hash * @param orderHash order's hash which matchorder pair with */ function deleteMatchOrder( bytes32 matchOrderHash, bytes32 orderHash ) external { require(MatchOrderToOwner[matchOrderHash] == msg.sender, "match order doens't belong to this address" ); require(OrderToExist[orderHash] == true, "this order is not exist"); _removeMatchOrder(orderHash, matchOrderHash); emit DeleteMatchOrder(msg.sender, orderHash, matchOrderHash); } /** * @dev delete matchorder information on exchange contract * @param orderHash order's hash which matchorder pair with * @param matchOrderHash matchorder's hash */ function _removeMatchOrder( bytes32 orderHash, bytes32 matchOrderHash ) internal { uint256 matchOrderIndex = OrderToMatchOrderIndex[orderHash][matchOrderHash]; uint256 lastMatchOrderIndex = OrderToMatchOrders[orderHash].length.sub(1); if (lastMatchOrderIndex != matchOrderIndex){ bytes32 lastMatchOrder = OrderToMatchOrders[orderHash][lastMatchOrderIndex]; OrderToMatchOrders[orderHash][matchOrderIndex] = lastMatchOrder; OrderToMatchOrderIndex[orderHash][lastMatchOrder] = matchOrderIndex; } OrderToMatchOrders[orderHash].length--; } /** * @dev order's owner can choose NFT to exchange from it's match order array, when function * execute, order will be deleted, both NFT will be exchanged and send to corresponding address. * @param order order's hash which matchorder pair with * @param matchOrder matchorder's hash */ function exchangeToken( bytes32 order, bytes32 matchOrder ) external { require(OrderToOwner[order] == msg.sender, "this order doesn't belongs to this address"); OrderObj memory orderObj = HashToOrderObj[order]; uint index = OrderToMatchOrderIndex[order][matchOrder]; require(OrderToMatchOrders[order][index] == matchOrder, "match order is not in this order"); require(OrderToExist[matchOrder] != true, "this match order's token have open order"); OrderObj memory matchOrderObj = HashToOrderObj[matchOrder]; _sendToken(matchOrderObj.owner, orderObj.contractAddress, orderObj.tokenId); _sendToken(orderObj.owner, matchOrderObj.contractAddress, matchOrderObj.tokenId); _removeMatchOrder(order, matchOrder); _removeOrder(msg.sender, order); } /** * @dev if you want to create order and matchorder on exchange contract, you must call this function * to send your NFT to exchange contract, if your NFT is followed erc165 and erc721 standard, exchange * contract will checked and execute sucessfully, then contract will record your information so you * don't need worried about NFT lost. * @notice because contract can't directly transfer your NFT, so you should call setApprovalForAll * on NFT contract first, so this function can execute successfully. * @param contractAddress NFT's Contract address * @param tokenId NFT's id */ function receiveErc721Token( address contractAddress, uint256 tokenId ) external { bool checkSupportErc165Interface = false; if(contractAddress != CryptoKittiesAddress){ for(uint i = 0; i < SupportNFTInterface.length; i++){ if(contractAddress._supportsInterface(SupportNFTInterface[i]) == true){ checkSupportErc165Interface = true; } } require(checkSupportErc165Interface == true, "not supported Erc165 Interface"); Erc721Interface erc721Contract = Erc721Interface(contractAddress); require(erc721Contract.isApprovedForAll(msg.sender,address(this)) == true, "contract doesn't have power to control this token id"); erc721Contract.transferFrom(msg.sender, address(this), tokenId); }else { KittyInterface kittyContract = KittyInterface(contractAddress); require(kittyContract.kittyIndexToApproved(tokenId) == address(this), "contract doesn't have power to control this cryptoKitties's id"); kittyContract.transferFrom(msg.sender, address(this), tokenId); } _addToken(msg.sender, contractAddress, tokenId); emit ReceiveToken(msg.sender, contractAddress, tokenId); } /** * @dev add token and OrderObj information on exchange contract, because order hash and matchorder * hash are same, so one NFT have mapping to one OrderObj * @param sender NFT's owner * @param contractAddress NFT's contract address * @param tokenId NFT's id */ function _addToken( address sender, address contractAddress, uint256 tokenId ) internal { bytes32 matchOrderHash = keccak256(abi.encodePacked(contractAddress, tokenId, sender)); MatchOrderToOwner[matchOrderHash] = sender; HashToOrderObj[matchOrderHash] = OrderObj(sender,contractAddress,tokenId); TokenToOwner[contractAddress][tokenId] = sender; uint index = OwnerToTokens[sender][contractAddress].push(tokenId).sub(1); TokenToIndex[contractAddress][tokenId] = index; emit CreateOrderObj(matchOrderHash, sender, contractAddress, tokenId); } /** * @dev send your NFT back to address which you send token in, if your NFT still have open order, * then order will be deleted * @notice matchorder will not be deleted because cost too high, but they will be useless and other * people can't choose your match order to exchange * @param contractAddress NFT's Contract address * @param tokenId NFT's id */ function sendBackToken( address contractAddress, uint256 tokenId ) external onlySenderIsOriginalOwner( contractAddress, tokenId ) { bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender)); if(OrderToExist[orderHash] == true) { _removeOrder(msg.sender, orderHash); } _sendToken(msg.sender, contractAddress, tokenId); emit SendBackToken(msg.sender, contractAddress, tokenId); } /** * @dev Drive NFT contract to send NFT to corresponding address * @notice because cryptokittes contract method are not the same as general NFT contract, so * need treat it individually * @param sendAddress NFT's owner * @param contractAddress NFT's contract address * @param tokenId NFT's id */ function _sendToken( address sendAddress, address contractAddress, uint256 tokenId ) internal { if(contractAddress != CryptoKittiesAddress){ Erc721Interface erc721Contract = Erc721Interface(contractAddress); require(erc721Contract.ownerOf(tokenId) == address(this), "exchange contract should have this token"); erc721Contract.transferFrom(address(this), sendAddress, tokenId); }else{ KittyInterface kittyContract = KittyInterface(contractAddress); require(kittyContract.ownerOf(tokenId) == address(this), "exchange contract should have this token"); kittyContract.transfer(sendAddress, tokenId); } _removeToken(contractAddress, tokenId); emit SendToken(sendAddress, contractAddress, tokenId); } /** * @dev remove token and OrderObj information on exchange contract * @param contractAddress NFT's contract address * @param tokenId NFT's id */ function _removeToken( address contractAddress, uint256 tokenId ) internal { address owner = TokenToOwner[contractAddress][tokenId]; bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, owner)); delete HashToOrderObj[orderHash]; delete MatchOrderToOwner[orderHash]; delete TokenToOwner[contractAddress][tokenId]; uint256 tokenIndex = TokenToIndex[contractAddress][tokenId]; uint256 lastOwnerTokenIndex = OwnerToTokens[owner][contractAddress].length.sub(1); if (lastOwnerTokenIndex != tokenIndex){ uint256 lastOwnerToken = OwnerToTokens[owner][contractAddress][lastOwnerTokenIndex]; OwnerToTokens[owner][contractAddress][tokenIndex] = lastOwnerToken; TokenToIndex[contractAddress][lastOwnerToken] = tokenIndex; } OwnerToTokens[owner][contractAddress].length--; } /** * @dev get NFT owner address * @param contractAddress NFT's contract address * @param tokenId NFT's id * @return NFT owner address */ function getTokenOwner( address contractAddress, uint256 tokenId ) external view returns (address) { return TokenToOwner[contractAddress][tokenId]; } /** * @dev get owner's specfic contract address's all NFT array * @param ownerAddress owner address * @param contractAddress NFT's contract address * @return NFT's array */ function getOwnerTokens( address ownerAddress, address contractAddress ) external view returns (uint256[] memory) { return OwnerToTokens[ownerAddress][contractAddress]; } /** * @dev get NFT's index in owner NFT's array * @param contractAddress NFT's contract address * @param tokenId NFT's id * @return NFT's index */ function getTokenIndex( address contractAddress, uint256 tokenId ) external view returns (uint256) { return TokenToIndex[contractAddress][tokenId]; } /** * @dev get owner address's all orders * @param ownerAddress owner address * @return orders array */ function getOwnerOrders( address ownerAddress ) external view returns (bytes32[] memory){ return OwnerToOrders[ownerAddress]; } /** * @dev get specfit order's owner address * @param order order's hash * @return order's owner address */ function getOrderOwner( bytes32 order ) external view returns (address) { return OrderToOwner[order]; } /** * @dev get order's index in owner orders array * @param order order's hash * @return order's index */ function getOrderIndex( bytes32 order ) external view returns (uint) { return OrderToIndex[order]; } /** * @dev get order exist or not in exchange contract * @param order order's hash * @return boolean to express order exist */ function getOrderExist( bytes32 order ) external view returns (bool){ return OrderToExist[order]; } /** * @dev get specfit matchorder's owner address * @param matchOrder matchorder's hash * @return matchorder's owner address */ function getMatchOrderOwner( bytes32 matchOrder ) external view returns (address) { return MatchOrderToOwner[matchOrder]; } /** * @dev get matchorder's index in NFT order's matchorders array * @param order matchorder's hash * @return matchorder's index */ function getOrderMatchOrderIndex( bytes32 order, bytes32 matchOrder ) external view returns (uint) { return OrderToMatchOrderIndex[order][matchOrder]; } /** * @dev get order's matchorder array * @param order order's hash * @return matchorder array */ function getOrderMatchOrders( bytes32 order ) external view returns (bytes32[] memory) { return OrderToMatchOrders[order]; } /** * @dev get mapping from order or matchorder's hash to OrderObj * @param hashOrder order or matchorder's hash * @return OrderObj */ function getHashOrderObj( bytes32 hashOrder ) external view returns( address, address, uint256 ) { OrderObj memory orderObj = HashToOrderObj[hashOrder]; return( orderObj.owner, orderObj.contractAddress, orderObj.tokenId ); } }
get owner address's all orders ownerAddress owner address return orders array/
function getOwnerOrders( address ownerAddress ) external view returns (bytes32[] memory){ return OwnerToOrders[ownerAddress]; }
12,691,074
./full_match/1/0x492B6F8A53D1c42cC2DD352788a6C02c557BE9F5/sources/contracts/integrations/common/StablzLPIntegration.sol
Check if an address is an accepted deposit token _token Token address return bool true if it is a supported deposit token, false if not Check if an address is an accepted withdrawal token _token Token address return bool true if it is a supported withdrawal token, false if not Check if an address is an accepted reward token _token Token address return bool true if it is a supported reward token, false if not _user User address return uint Held rewards
function isDepositToken(address _token) public virtual view returns (bool); function isWithdrawalToken(address _token) public virtual view returns (bool); function isRewardToken(address _token) public virtual view returns (bool); function _getHeldRewards(address _user) internal view virtual returns (uint) { return users[_user].heldRewards; }
3,190,112
pragma solidity ^0.5.5; // Bytes library to concat and transform // bytes arrays library Bytes { // Concadenates two bytes array // Author: Gonçalo Sá <[email protected]> function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { return abi.encodePacked(_preBytes, _postBytes); } // Concatenates a bytes array and a bytes1 function concat(bytes memory _a, bytes1 _b) internal pure returns (bytes memory _out) { return concat(_a, abi.encodePacked(_b)); } // Concatenates 6 bytes arrays function concat( bytes memory _a, bytes memory _b, bytes memory _c, bytes memory _d, bytes memory _e, bytes memory _f ) internal pure returns (bytes memory) { return abi.encodePacked( _a, _b, _c, _d, _e, _f ); } // Transforms a bytes1 into bytes function toBytes(bytes1 _a) internal pure returns (bytes memory) { return abi.encodePacked(_a); } // Transform a uint256 into bytes (last 8 bits) function toBytes1(uint256 _a) internal pure returns (bytes1 c) { assembly { c := shl(248, _a) } } // Adds a bytes1 and the last 8 bits of a uint256 function plus(bytes1 _a, uint256 _b) internal pure returns (bytes1 c) { c = toBytes1(_b); assembly { c := add(_a, c) } } // Transforms a bytes into an array // it fails if _a has more than 20 bytes function toAddress(bytes memory _a) internal pure returns (address payable b) { require(_a.length <= 20); assembly { b := shr(mul(sub(32, mload(_a)), 8), mload(add(_a, 32))) } } // Returns the most significant bit of a given uint256 function mostSignificantBit(uint256 x) internal pure returns (uint256) { uint8 o = 0; uint8 h = 255; while (h > o) { uint8 m = uint8 ((uint16 (o) + uint16 (h)) >> 1); uint256 t = x >> m; if (t == 0) h = m - 1; else if (t > 1) o = m + 1; else return m; } return h; } // Shrinks a given address to the minimal representation in a bytes array function shrink(address _a) internal pure returns (bytes memory b) { uint256 abits = mostSignificantBit(uint256(_a)) + 1; uint256 abytes = abits / 8 + (abits % 8 == 0 ? 0 : 1); assembly { b := 0x0 mstore(0x0, abytes) mstore(0x20, shl(mul(sub(32, abytes), 8), _a)) } } }
Concatenates a bytes array and a bytes1
function concat(bytes memory _a, bytes1 _b) internal pure returns (bytes memory _out) { return concat(_a, abi.encodePacked(_b)); }
2,485,652
pragma solidity ^0.6.2; // SPDX-License-Identifier: MIT abstract contract Context { function _MSGSENDER583() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA879() 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; } } // SPDX-License-Identifier: MIT interface IERC20 { function TOTALSUPPLY430() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF616(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER244(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE387(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE425(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM381(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER617(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL460(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // SPDX-License-Identifier: MIT library SafeMath { function ADD135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB321(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB321(a, b, "SafeMath: subtraction overflow"); } function SUB321(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 MUL733(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 DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV136(a, b, "SafeMath: division by zero"); } function DIV136(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 MOD593(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD593(a, b, "SafeMath: modulo by zero"); } function MOD593(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT library Address { function ISCONTRACT469(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE193(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 FUNCTIONCALL340(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL340(target, data, "Address: low-level call failed"); } function FUNCTIONCALL340(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE922(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE944(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE944(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 _FUNCTIONCALLWITHVALUE922(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE922(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT469(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT 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 NAME100() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL131() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS904() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY430() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF616(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER244(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER73(_MSGSENDER583(), recipient, amount); return true; } function ALLOWANCE387(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE425(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE319(_MSGSENDER583(), spender, amount); return true; } function TRANSFERFROM381(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER73(sender, recipient, amount); _APPROVE319(sender, _MSGSENDER583(), _allowances[sender][_MSGSENDER583()].SUB321(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE808(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].ADD135(addedValue)); return true; } function DECREASEALLOWANCE515(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].SUB321(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER73(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"); _BEFORETOKENTRANSFER129(sender, recipient, amount); _balances[sender] = _balances[sender].SUB321(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD135(amount); emit TRANSFER617(sender, recipient, amount); } function _MINT517(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER129(address(0), account, amount); _totalSupply = _totalSupply.ADD135(amount); _balances[account] = _balances[account].ADD135(amount); emit TRANSFER617(address(0), account, amount); } function _BURN171(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER129(account, address(0), amount); _balances[account] = _balances[account].SUB321(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB321(amount); emit TRANSFER617(account, address(0), amount); } function _APPROVE319(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 APPROVAL460(owner, spender, amount); } function _SETUPDECIMALS874(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // SPDX-License-Identifier: MIT abstract contract ERC20Capped is ERC20 { uint256 private _cap; constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } function CAP360() public view returns (uint256) { //inject NONSTANDARD NAMING return _cap; } function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING super._BEFORETOKENTRANSFER129(from, to, amount); if (from == address(0)) { // When minting tokens require(TOTALSUPPLY430().ADD135(amount) <= _cap, "ERC20Capped: cap exceeded"); } } } // SPDX-License-Identifier: MIT contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED797(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER583(); _owner = msgSender; emit OWNERSHIPTRANSFERRED797(address(0), msgSender); } function OWNER971() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER607() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER583(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP525() public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED797(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP777(address newOwner) public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED797(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Router01 { function FACTORY439() external pure returns (address); //inject NONSTANDARD NAMING function WETH181() external pure returns (address); //inject NONSTANDARD NAMING function ADDLIQUIDITY85( //inject NONSTANDARD NAMING 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 ADDLIQUIDITYETH216( //inject NONSTANDARD NAMING address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function REMOVELIQUIDITY344( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function REMOVELIQUIDITYETH742( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function REMOVELIQUIDITYWITHPERMIT491( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function REMOVELIQUIDITYETHWITHPERMIT317( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function SWAPEXACTTOKENSFORTOKENS917( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPTOKENSFOREXACTTOKENS879( //inject NONSTANDARD NAMING uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPEXACTETHFORTOKENS817(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function SWAPTOKENSFOREXACTETH856(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPEXACTTOKENSFORETH218(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPETHFOREXACTTOKENS998(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function QUOTE315(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING function GETAMOUNTOUT816(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING function GETAMOUNTIN684(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING function GETAMOUNTSOUT241(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING function GETAMOUNTSIN775(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING } interface IUniswapV2Router02 is IUniswapV2Router01 { function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS846( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS1( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS219( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS501( //inject NONSTANDARD NAMING uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS54( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Pair { event APPROVAL460(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER617(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME100() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL131() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS904() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY430() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF616(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE387(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE425(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM381(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR749() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH945() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES546(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT654(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT786(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN405(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP722( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC303(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY735() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY439() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0934() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1318() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES691() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST150() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST277() external view returns (uint); //inject NONSTANDARD NAMING function KLAST634() external view returns (uint); //inject NONSTANDARD NAMING function MINT615(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN664(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP816(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM21(address to) external; //inject NONSTANDARD NAMING function SYNC269() external; //inject NONSTANDARD NAMING function INITIALIZE267(address, address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED762(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO789() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER578() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR592(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS410(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH90() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR614(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO894(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER1(address) external; //inject NONSTANDARD NAMING } interface IWETH { function DEPOSIT145() external payable; //inject NONSTANDARD NAMING function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function WITHDRAW78(uint) external; //inject NONSTANDARD NAMING } contract CGLB is ERC20Capped, Ownable { using SafeMath for uint; address public UNIPAIR; address public DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); IUniswapV2Router02 public UNIROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Factory public UNIFACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); bool public isRunning = false; bool private liquidityFlag; uint public constant supplycap690 = (10**4)*(10**18); //inject NONSTANDARD NAMING uint public constant tokensforinitialliquidity143 = 3*(10**3)*(10**18); //inject NONSTANDARD NAMING bytes32 public airdropRoot; mapping (address => bool) public claimedAirdrop; string public website = "www.cglb.fi"; constructor() public ERC20Capped(supplycap690) ERC20("Cant go lower boys", "CGLB") { airdropRoot = 0x185065ab3d54b516ee3ed54dc30e04758300a4b41e207cf3ba91715f378d7728; } function TRANSFER244(address recipient, uint256 amount) //inject NONSTANDARD NAMING public override returns (bool) { require(msg.sender == UNIPAIR || msg.sender == address(UNIROUTER)); super.TRANSFER244(recipient, amount); return true; } function TRANSFERFROM381(address sender, address recipient, uint256 amount) //inject NONSTANDARD NAMING public override returns (bool) { require(liquidityFlag); _TRANSFER73(sender, recipient, amount); return true; } function ADDLIQUIDITYTOUNISWAPPAIR951( //inject NONSTANDARD NAMING uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountDAIDesired, uint256 amountDAImin ) public payable { require(isRunning); require(IERC20(DAI).TRANSFERFROM381(msg.sender, address(this), amountDAIDesired)); require(IERC20(DAI).APPROVE425(address(UNIROUTER), amountDAIDesired)); _TRANSFER73(msg.sender, address(this), amountTokenDesired); liquidityFlag = true; (uint amountToken, uint amountDAI, uint liquidity) = UNIROUTER.ADDLIQUIDITY85( address(this), DAI, amountTokenDesired, amountDAIDesired, amountTokenMin, amountDAImin, msg.sender, now + 10 minutes ); liquidityFlag = false; //sends dust back if (amountTokenDesired - amountToken > 0 ) _TRANSFER73(address(this), msg.sender, amountTokenDesired-amountToken); if (amountDAIDesired - amountDAI > 0) require(IERC20(DAI).TRANSFER244(msg.sender, amountDAIDesired - amountDAI)); } function ADDINITIALLIQUIDITYWITHPAIR729() public ONLYOWNER607 { //inject NONSTANDARD NAMING CREATEUNISWAPPAIR64(); uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this)); require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI)); _MINT517(UNIPAIR, tokensforinitialliquidity143); IUniswapV2Pair(UNIPAIR).MINT615(msg.sender); isRunning = true; } function ADDINITIALLIQUIDITY209() public ONLYOWNER607 { //inject NONSTANDARD NAMING uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this)); require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI)); _MINT517(UNIPAIR, tokensforinitialliquidity143); IUniswapV2Pair(UNIPAIR).MINT615(msg.sender); isRunning = true; } function SETAIRDROPROOT894(bytes32 _root) public ONLYOWNER607 { //inject NONSTANDARD NAMING airdropRoot = _root; } function SETPAIR246(address _pair) public ONLYOWNER607 { //inject NONSTANDARD NAMING UNIPAIR = _pair; } function CREATEUNISWAPPAIR64() internal { //inject NONSTANDARD NAMING require(UNIPAIR == address(0), "Token: pool already created"); UNIPAIR = UNIFACTORY.CREATEPAIR614( DAI, address(this) ); } function CHECKPROOF499(bytes memory proof, bytes32 root, bytes32 hash) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 el; bytes32 h = hash; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { el := mload(add(proof, i)) } if (h < el) { h = keccak256(abi.encodePacked(h, el)); } else { h = keccak256(abi.encodePacked(el, h)); } } return h == root; } function CLAIMAIRDROP701(bytes memory proof, uint amount) public { //inject NONSTANDARD NAMING require(!claimedAirdrop[msg.sender]); bytes32 hash = keccak256(abi.encodePacked(msg.sender, amount)); require(CHECKPROOF499(proof, airdropRoot, hash), "Invalid proof"); claimedAirdrop[msg.sender] = true; _MINT517(msg.sender, amount); } function WITHDRAWERC20742(address token) ONLYOWNER607 public { //inject NONSTANDARD NAMING uint balance = IERC20(token).BALANCEOF616(address(this)); require(IERC20(token).TRANSFER244(msg.sender, balance)); } }
inject NONSTANDARD NAMING
function ADDINITIALLIQUIDITYWITHPAIR729() public ONLYOWNER607 {
1,820,620
./full_match/43113/0x1Db514148505888ac19Fd70EA1fF4DBfBE2a3933/sources/contracts/MasterChef.sol
Update the given pool's DCAU allocation point and deposit fee. Can only be called by the owner.
function set( uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate ) external onlyOwner { require(_depositFeeBP <= 401, "set: invalid deposit fee basis points"); require(_pid < poolInfo.length, "Dragon: Non-existent pool"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; emit SetPool(_pid, address(poolInfo[_pid].lpToken), _allocPoint, _depositFeeBP); }
13,190,955
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; /** * @dev On-chain art generation for MoonCatLootprints * Takes individual trait values as parameters, and outputs complete representations of them. */ contract MoonCatLootprintsMetadata { string[5] internal class_names = [ "Mech", "Sub", "Tank", "Cruiser", "Unknown" ]; /** * @dev Convert a Classification ID number into a string name */ function getClassName(uint8 classId) public view returns (string memory) { return class_names[classId]; } string[15] internal color_names = ["Hero Silver", "Genesis White", "Genesis Black", "Red", "Orange", "Yellow", "Chartreuse", "Green", "Teal", "Cyan", "SkyBlue", "Blue", "Purple", "Magenta", "Fuchsia"]; /** * @dev Convert a Color ID number into a string name */ function getColorName(uint8 colorId) public view returns (string memory) { return color_names[colorId]; } // Color codes used for the background color of an image representation string[15] internal color_codes = ["#777777", // Silver "#cccccc", // White "#111111", // Black "hsl(0,60%,38%)", // Red "hsl(30,60%,38%)", // Orange "hsl(60,60%,38%)", // Yellow "hsl(80,60%,38%)", // Chartreuse "hsl(120,60%,38%)", // Green "hsl(150,60%,38%)", // Teal "hsl(180,60%,38%)", // Cyan "hsl(210,60%,38%)", // SkyBlue "hsl(240,60%,38%)", // Blue "hsl(270,60%,38%)", // Purple "hsl(300,60%,38%)", // Magenta "hsl(330,60%,38%)"]; // Fuchsia // SVG codes for the different icons for each ship classification string[4] public ship_images = ["<path class=\"s\" d=\"M-61.74,77.79h-12.61V32.32h12.61V77.79z M-28.03,26.64l-7.58-12.63v44.12h7.58V26.64z M-0.65,52.52h10.99 L41.41,1.36L24.74-12.66H-0.65h-25.39L-42.72,1.36l31.07,51.16H-0.65z M60.43,77.79h12.61V32.32H60.43V77.79z M26.73,58.14h7.58 V14.02l-7.58,12.63V58.14z\"/><path class=\"s\" d=\"M-23.89,32.56v4.77h-44.15V8.75h29.81 M-58.76,13.76h-18.55v18.55h18.55V13.76z M22.59,32.56v4.77h44.15V8.75 H36.92 M57.46,32.32h18.55V13.76H57.46V32.32z M5.79,46.98L5.79,46.98c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94 v0c0,1.07,0.87,1.94,1.94,1.94h9C4.92,48.93,5.79,48.06,5.79,46.98z\"/><path class=\"s s1\" d=\"M-79.92,94.43V86.1 M-56.04,94.43V86.1 M78.61,94.43V86.1 M54.74,94.43V86.1 M-14.48,5.33h28.04 M-9.45,1.1 H8.52\"/><path class=\"s s1\" d=\"M-44.11,94.43h-47.87V82.76c0-2.76,2.24-5,5-5h37.87c2.76,0,5,2.24,5,5V94.43z M-19.88,57.67v-6.18 c0-1.64-1.33-2.97-2.97-2.97h-9.15v12.13h9.15C-21.22,60.65-19.88,59.32-19.88,57.67z M42.8,94.43h47.87V82.76c0-2.76-2.24-5-5-5 H47.8c-2.76,0-5,2.24-5,5V94.43z M-0.65,31.11h14.08L33.42,3.86L25.39,2.2l-8.96,8.83H-0.65h-17.08l-8.96-8.83l-8.04,1.66 l19.99,27.25H-0.65z M21.55,60.65h9.15V48.52h-9.15c-1.64,0-2.97,1.33-2.97,2.97v6.18C18.58,59.32,19.91,60.65,21.55,60.65z\"/><path class=\"s s1\" d=\"M-26.04-12.66l-11.17,9.4v-27.46h7.51l16.17,18.06H-26.04z M24.74-12.66l11.17,9.4v-27.46H28.4L12.23-12.66 H24.74z\"/><path class=\"s s2\" d=\"M-19.88,52.86h-3.79 M-19.88,56.46h-3.79 M22.37,52.86h-3.79 M18.58,56.46h3.79\"/> <path class=\"s s2\" d=\"M-39.67,8.41l-1.58,33.83h-11.47l-1.58-33.83c0-4.04,3.28-7.32,7.32-7.32C-42.95,1.1-39.67,4.37-39.67,8.41z M-43.38,42.24h-6.9l-1.01,4.74h8.91L-43.38,42.24z M38.37,8.41l1.58,33.83h11.47L53,8.41c0-4.04-3.28-7.32-7.32-7.32 C41.64,1.1,38.37,4.37,38.37,8.41z M41.06,46.98h8.91l-1.01-4.74h-6.9L41.06,46.98z\"/>", // Mech "<path class=\"s\" d=\"M55.52,60.62l-125.85,7.15c-13.35,0.76-24.59-9.86-24.59-23.23v0c0-13.37,11.24-23.99,24.59-23.23l125.85,7.15 V60.62z\"/><path class=\"s\" d=\"M48.39,42.2v10.28l-5.47-1.16v-7.96L48.39,42.2z M63.26,21.92L63.26,21.92c-2.75,0-4.82,2.5-4.31,5.2 l3.33,17.61h1.97l3.33-17.61C68.09,24.42,66.01,21.92,63.26,21.92z M63.26,67.55L63.26,67.55c2.75,0,4.82-2.5,4.31-5.2l-3.33-17.61 h-1.97l-3.33,17.61C58.44,65.05,60.51,67.55,63.26,67.55z M-44.97,43.64L-44.97,43.64c0.76,0.76,1.99,0.76,2.75,0l6.36-6.36 c0.76-0.76,0.76-1.99,0-2.75l0,0c-0.76-0.76-1.99-0.76-2.75,0l-6.36,6.36C-45.72,41.65-45.72,42.88-44.97,43.64z M-34.82,43.64 L-34.82,43.64c0.76,0.76,1.99,0.76,2.75,0l6.36-6.36c0.76-0.76,0.76-1.99,0-2.75l0,0c-0.76-0.76-1.99-0.76-2.75,0l-6.36,6.36 C-35.58,41.65-35.58,42.88-34.82,43.64z M63.26,43.33h-7.74v2.81h7.74V43.33z\"/><path class=\"s\" d=\"M-71.47,62.75v15.73 M-65.61,62.75v22.93\"/> <path class=\"s s1\" d=\"M52.24,60.8l1.72,11.04l19.89,4.4v6.21L38.9,88.39c-8.09,1.37-15.55-4.68-15.87-12.88l-0.51-13.03 M51.24,28.2 L67.16,2.56l-80.25-3.16c-6.16-0.24-12.13,2.16-16.4,6.61l-16.03,16.69\"/><path class=\"s s1\" d=\"M3.89,39.09l39.03,1.83v13.24L3.89,55.98c-4.66,0-8.44-3.78-8.44-8.44C-4.56,42.87-0.78,39.09,3.89,39.09z M-42.74,31.11l-31.49-1.26c-5.73,0-10.75,3.81-12.3,9.33l-0.67,5.36h29.01L-42.74,31.11z M30.03,47.53L30.03,47.53 c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C29.16,49.47,30.03,48.6,30.03,47.53z\"/>", // Sub "<path class=\"s\" d=\"M-41.05,64.38H-76.3c-9.83,0-17.79-7.98-17.77-17.8l0.02-7.96l53-31.34V64.38z M-33.49,21.94v36.39l12.96,9.64 c7.01,5.22,15.52,8.03,24.26,8.03h50.54V7.29l-12-2.39C27.98,2.05,13.19,3.4-0.34,8.77L-33.49,21.94z\"/> <path class=\"s\" d=\"M-53.74,49.67l93.8-17.28 M-53.74,96.38h99.86 M-60.37,44.65L-60.37,44.65c0-1.07-0.87-1.94-1.94-1.94h-9 c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C-61.24,46.59-60.37,45.72-60.37,44.65z M-60.37,37.78L-60.37,37.78 c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C-61.24,39.72-60.37,38.85-60.37,37.78 z M-33.49,26.33h-7.56v27.92h7.56V26.33z\"/><path class=\"s s1\" d=\"M-0.29,30.83v-9c0-1.07,0.87-1.94,1.94-1.94h0c1.07,0,1.94,0.87,1.94,1.94v9c0,1.07-0.87,1.94-1.94,1.94h0 C0.58,32.77-0.29,31.9-0.29,30.83z M1.47-0.14c-4.66,0-8.44,3.78-8.44,8.44l1.83,39.03H8.08L9.91,8.3 C9.91,3.64,6.13-0.14,1.47-0.14z\"/> <path class=\"s s1\" d=\"M42.26,32.38c-17.67,0-32,14.33-32,32s14.33,32,32,32s32-14.33,32-32S59.94,32.38,42.26,32.38z M42.26,89.98 c-14.14,0-25.6-11.46-25.6-25.6s11.46-25.6,25.6-25.6s25.6,11.46,25.6,25.6S56.4,89.98,42.26,89.98z M-51.74,49.57 c-12.93,0-23.4,10.48-23.4,23.41c0,12.93,10.48,23.4,23.4,23.4s23.4-10.48,23.4-23.4C-28.33,60.05-38.81,49.57-51.74,49.57z M-51.74,91.7c-10.34,0-18.72-8.38-18.72-18.72c0-10.34,8.38-18.72,18.72-18.72s18.72,8.38,18.72,18.72 C-33.01,83.32-41.4,91.7-51.74,91.7z M-46.35,29.02h-14.78l14.4-10.61L-46.35,29.02z M6.8,52.81H-3.49l1.16-5.47h7.96L6.8,52.81z M54.26,20.3l9-3v18.97l-9-3.28 M54.26,53.04l9-3v18.97l-9-3.28\"/>", // Tank "<path class=\"s\" d=\"M0.26,93.33h14.33c0,0-0.76-11.46-2.27-32s13.64-76.47,19.95-99.97s-2.52-60.03-32-60.03 s-38.31,36.54-32,60.03s21.46,79.43,19.95,99.97s-2.27,32-2.27,32H0.26\"/><path class=\"s\" d=\"M-12.9,76.57l-47.02,6.06l3.03-18.95l43.64-22.42 M-26.38-18.46l-9.09,14.31v19.33l14.78-10.8 M13.42,76.57 l47.02,6.06l-3.03-18.95L13.77,41.25 M21.22,4.37L36,15.17V-4.15l-9.09-14.31\"/><path class=\"s s1\" d=\"M-33.66,46.63l-1.83,39.03h-13.24l-1.83-39.03c0-4.66,3.78-8.44,8.44-8.44 C-37.44,38.18-33.66,41.96-33.66,46.63z M34.19,46.63l1.83,39.03h13.24l1.83-39.03c0-4.66-3.78-8.44-8.44-8.44 C37.97,38.18,34.19,41.96,34.19,46.63z\"/><path class=\"s s1\" d=\"M-19.18-74.83c1.04,1.8,0.95,17.15,3.03,27c1.51,7.14,4.01,15.92,2.38,18.14c-1.43,1.94-7.59,1.24-9.95-1.37 c-3.41-3.78-4.15-10.56-4.93-16.67C-30.13-59.39-22.35-80.31-19.18-74.83z M-37.94,85.66h-7.96l-1.16,5.47h10.28L-37.94,85.66z M-10.65,93.33l-1.33,8.05H0.26h12.24l-1.33-8.05 M0.26-34.67c0,0,1.82,0,6.12,0s7.45-32,7.04-43S9.28-88.66,0.26-88.66 s-12.75-0.01-13.16,10.99c-0.41,11,2.74,43,7.04,43S0.26-34.67,0.26-34.67z M19.71-74.83c-1.04,1.8-0.95,17.15-3.03,27 c-1.51,7.14-4.01,15.92-2.38,18.14c1.43,1.94,7.59,1.24,9.95-1.37c3.41-3.78,4.15-10.56,4.93-16.67 C30.65-59.39,22.88-80.31,19.71-74.83z M37.3,91.13h10.28l-1.16-5.47h-7.96L37.3,91.13z\"/>" // Cruiser ]; /** * @dev Render an SVG of a ship with the specified features. */ function getImage (uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName) public view returns (string memory) { string memory regStr = uint2str(lootprintId); string memory baysStr = uint2str(bays); string[15] memory parts; parts[0] = "<svg xmlns=\"http://www.w3.org/2000/svg\" preserveAspectRatio=\"xMinYMin meet\" viewBox=\"0 0 600 600\"><style> .s{fill:white;stroke:white;stroke-width:2;stroke-miterlimit:10;fill-opacity:0.1;stroke-linecap:round}.s1{fill-opacity:0.3}.s2{stroke-width:1}.t{ fill:white;font-family:serif;font-size:20px;}.k{font-weight:bold;text-anchor:end;fill:#ddd;}.n{font-size:22px;font-weight:bold;text-anchor:middle}.l{fill:none;stroke:rgb(230,230,230,0.5);stroke-width:1;clip-path:url(#c);}.r{fill:rgba(0,0,0,0.5);stroke:white;stroke-width:3;}.r1{stroke-width: 1} .a{fill:#FFFFFF;fill-opacity:0.1;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;}.b{fill:none;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;} .c{fill:#FFFFFF;fill-opacity:0.2;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;} .d{fill:#FFFFFF;fill-opacity:0.3;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;}</style><defs><clipPath id=\"c\"><rect width=\"600\" height=\"600\" /></clipPath></defs><rect width=\"600\" height=\"600\" fill=\""; parts[1] = color_codes[colorId]; parts[2] = "\"/><polyline class=\"l\" points=\"40,-5 40,605 80,605 80,-5 120,-5 120,605 160,605 160,-5 200,-5 200,605 240,605 240,-5 280,-5 280,605 320,605 320,-5 360,-5 360,605 400,605 400,-5 440,-5 440,605 480,605 480,-5 520,-5 520,605 560,605 560,-5 600,-5 600,605\" /><polyline class=\"l\" points=\"-5,40 605,40 605,80 -5,80 -5,120 605,120 605,160 -5,160 -5,200 605,200 605,240 -5,240 -5,280 605,280 605,320 -5,320 -5,360 605,360 605,400 -5,400 -5,440 605,440 605,480 -5,480 -5,520 605,520 605,560 -5,560 -5,600 605,600\" /><rect class=\"r\" x=\"10\" y=\"10\" width=\"580\" height=\"50\" rx=\"15\" /><rect class=\"l r r1\" x=\"-5\" y=\"80\" width=\"285\" height=\"535\" /><text class=\"t n\" x=\"300\" y=\"42\">"; parts[3] = shipName; parts[4] = "</text><text class=\"t k\" x=\"115\" y=\"147\">Reg:</text><text class=\"t\" x=\"125\" y=\"147\">#"; parts[5] = regStr; parts[6] = "</text><text class=\"t k\" x=\"115\" y=\"187\">Class:</text><text class=\"t\" x=\"125\" y=\"187\">"; parts[7] = class_names[classId]; parts[8] = "</text><text class=\"t k\" x=\"115\" y=\"227\">Color:</text><text class=\"t\" x=\"125\" y=\"227\">"; parts[9] = color_names[colorId]; parts[10] = "</text><text class=\"t k\" x=\"115\" y=\"267\">Bays:</text><text class=\"t\" x=\"125\" y=\"267\">"; parts[11] = baysStr; parts[12] = "</text><g transform=\"translate(440,440)scale(1.2)\">"; if (classId < 4) { parts[13] = ship_images[classId]; } parts[14] = "</g></svg>"; bytes memory svg0 = abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]); bytes memory svg1 = abi.encodePacked(parts[9], parts[10], parts[11], parts[12], parts[13], parts[14]); return string(abi.encodePacked("data:image/svg+xml;base64,", Base64.encode(abi.encodePacked(svg0, svg1)))); } /** * @dev Encode a key/value pair as a JSON trait property, where the value is a numeric item (doesn't need quotes) */ function encodeAttribute(string memory key, string memory value) internal pure returns (string memory) { return string(abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":",value,"}")); } /** * @dev Encode a key/value pair as a JSON trait property, where the value is a string item (needs quotes around it) */ function encodeStringAttribute(string memory key, string memory value) internal pure returns (string memory) { return string(abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":\"",value,"\"}")); } /** * @dev Render a JSON metadata object of a ship with the specified features. */ function getJSON(uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName) public view returns (string memory) { string memory colorName = color_names[colorId]; string memory svg = getImage(lootprintId, classId, colorId, bays, shipName); bytes memory tokenName = abi.encodePacked("Lootprint #", uint2str(lootprintId), ": ", shipName); bytes memory json = abi.encodePacked("{", "\"attributes\":[", encodeAttribute("Registration #", uint2str(lootprintId)), ",", encodeStringAttribute("Class", class_names[classId]), ",", encodeAttribute("Bays", uint2str(bays)), ",", encodeStringAttribute("Color", colorName), "],\"name\":\"", tokenName, "\",\"description\":\"Build Plans for a MoonCat Spacecraft\",\"image\":\"", svg, "\"}"); return string(abi.encodePacked('data:application/json;base64,', Base64.encode(json))); } /* Utilities */ function uint2str(uint value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; interface IMoonCatAcclimator { function getApproved(uint256 tokenId) external view returns (address); function isApprovedForAll(address owner, address operator) external view returns (bool); function ownerOf(uint256 tokenId) external view returns (address); } interface IMoonCatRescue { function rescueOrder(uint256 tokenId) external view returns (bytes5); function catOwners(bytes5 catId) external view returns (address); } interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IMoonCatLootprintsMetadata { function getJSON(uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName) external view returns (string memory); function getImage(uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName) external view returns (string memory); function getClassName(uint8 classId) external view returns (string memory); function getColorName(uint8 classId) external view returns (string memory); } /** * @dev Derived from OpenZeppelin standard template * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/EnumerableSet.sol * b0cf6fbb7a70f31527f36579ad644e1cf12fdf4e */ library EnumerableSet { struct Set { uint256[] _values; mapping (uint256 => uint256) _indexes; } function at(Set storage set, uint256 index) internal view returns (uint256) { return set._values[index]; } function contains(Set storage set, uint256 value) internal view returns (bool) { return set._indexes[value] != 0; } function length(Set storage set) internal view returns (uint256) { return set._values.length; } function add(Set storage set, uint256 value) internal 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; } } function remove(Set storage set, uint256 value) internal 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) { uint256 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; } } } /** * @title MoonCat​Lootprints * @dev MoonCats have found some plans for building spaceships */ contract MoonCatLootprints is IERC165, IERC721Enumerable, IERC721Metadata { /* ERC-165 */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) { return (interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId); } /* External Contracts */ IMoonCatAcclimator MCA = IMoonCatAcclimator(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69); IMoonCatRescue MCR = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6); IMoonCatLootprintsMetadata public Metadata; /* Name String Data */ string[4] internal honorifics = [ "Legendary", "Notorious", "Distinguished", "Renowned" ]; string[32] internal adjectives = [ "Turbo", "Tectonic", "Rugged", "Derelict", "Scratchscarred", "Purrfect", "Rickety", "Sparkly", "Ethereal", "Hissing", "Pouncing", "Stalking", "Standing", "Sleeping", "Playful", "Menancing", // Poor Steve. "Cuddly", "Neurotic", "Skittish", "Impulsive", "Sly", "Ponderous", "Prodigal", "Hungry", "Grumpy", "Harmless", "Mysterious", "Frisky", "Furry", "Scratchy", "Patchy", "Hairless" ]; string[15] internal mods = [ "Star", "Galaxy", "Constellation", "World", "Moon", "Alley", "Midnight", "Wander", "Tuna", "Mouse", "Catnip", "Toy", "Kibble", "Hairball", "Litterbox" ]; string[32] internal mains = [ "Lightning", "Wonder", "Toebean", "Whisker", "Paw", "Fang", "Tail", "Purrbox", "Meow", "Claw", "Scratcher", "Chomper", "Nibbler", "Mouser", "Racer", "Teaser", "Chaser", "Hunter", "Leaper", "Sleeper", "Pouncer", "Stalker", "Stander", "TopCat", "Ambassador", "Admiral", "Commander", "Negotiator", "Vandal", "Mischief", "Ultimatum", "Frolic" ]; string[16] internal designations = [ "Alpha", "Tau", "Pi", "I", "II", "III", "IV", "V", "X", "Prime", "Proper", "1", "1701-D", "2017", "A", "Runt" ]; /* Data */ bytes32[400] ColorTable; /* Structs */ struct Lootprint { uint16 index; address owner; } /* State */ using EnumerableSet for EnumerableSet.Set; address payable public contractOwner; bool public frozen = true; bool public mintingWindowOpen = true; uint8 revealCount = 0; uint256 public price = 50000000000000000; bytes32[100] NoChargeList; bytes32[20] revealBlockHashes; Lootprint[25600] public Lootprints; // lootprints by lootprintId/rescueOrder EnumerableSet.Set internal LootprintIdByIndex; mapping(address => EnumerableSet.Set) internal LootprintsByOwner; mapping(uint256 => address) private TokenApprovals; // lootprint id -> approved address mapping(address => mapping(address => bool)) private OperatorApprovals; // owner address -> operator address -> bool /* Modifiers */ modifier onlyContractOwner () { require(msg.sender == contractOwner, "Only Contract Owner"); _; } modifier lootprintExists (uint256 lootprintId) { require(LootprintIdByIndex.contains(lootprintId), "ERC721: operator query for nonexistent token"); _; } modifier onlyOwnerOrApproved(uint256 lootprintId) { require(LootprintIdByIndex.contains(lootprintId), "ERC721: query for nonexistent token"); address owner = ownerOf(lootprintId); require(msg.sender == owner || msg.sender == TokenApprovals[lootprintId] || OperatorApprovals[owner][msg.sender], "ERC721: transfer caller is not owner nor approved"); _; } modifier notFrozen () { require(!frozen, "Frozen"); _; } /* ERC-721 Helpers */ function setApprove(address to, uint256 lootprintId) private { TokenApprovals[lootprintId] = to; emit Approval(msg.sender, to, lootprintId); } function handleTransfer(address from, address to, uint256 lootprintId) private { require(to != address(0), "ERC721: transfer to the zero address"); setApprove(address(0), lootprintId); LootprintsByOwner[from].remove(lootprintId); LootprintsByOwner[to].add(lootprintId); Lootprints[lootprintId].owner = to; emit Transfer(from, to, lootprintId); } /* ERC-721 */ function totalSupply() public view override returns (uint256) { return LootprintIdByIndex.length(); } function balanceOf(address owner) public view override returns (uint256 balance) { return LootprintsByOwner[owner].length(); } function ownerOf(uint256 lootprintId) public view override returns (address owner) { return Lootprints[lootprintId].owner; } function approve(address to, uint256 lootprintId) public override lootprintExists(lootprintId) { address owner = ownerOf(lootprintId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all"); setApprove(to, lootprintId); } function getApproved(uint256 lootprintId) public view override returns (address operator) { return TokenApprovals[lootprintId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != msg.sender, "ERC721: approve to caller"); OperatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return OperatorApprovals[owner][operator]; } function safeTransferFrom(address from, address to, uint256 lootprintId, bytes memory _data) public override onlyOwnerOrApproved(lootprintId) { handleTransfer(from, to, lootprintId); uint256 size; assembly { size := extcodesize(to) } if (size > 0) { try IERC721Receiver(to).onERC721Received(msg.sender, from, lootprintId, _data) returns (bytes4 retval) { if (retval != IERC721Receiver.onERC721Received.selector) { revert("ERC721: transfer to non ERC721Receiver implementer"); } } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } function safeTransferFrom(address from, address to, uint256 lootprintId) public override { safeTransferFrom(from, to, lootprintId, ""); } function transferFrom(address from, address to, uint256 lootprintId) public override onlyOwnerOrApproved(lootprintId) { handleTransfer(from, to, lootprintId); } /* ERC-721 Enumerable */ function tokenByIndex(uint256 index) public view override returns (uint256) { return LootprintIdByIndex.at(index); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return LootprintsByOwner[owner].at(index); } /* Reveal */ bool pendingReveal = false; uint256 revealPrepBlock; bytes32 revealSeedHash; /** * @dev How many lootprints are awaiting being revealed? */ function pendingRevealCount() public view returns (uint256) { uint256 numRevealed = revealCount * 2560; if (numRevealed > LootprintIdByIndex.length()) return 0; return LootprintIdByIndex.length() - numRevealed; } /** * @dev Start a reveal action. * The hash submitted here must be the keccak256 hash of a secret number that will be submitted to the next function */ function prepReveal(bytes32 seedHash) public onlyContractOwner { require(!pendingReveal && seedHash != revealSeedHash && revealCount < 20, "Prep Conditions Not Met"); revealSeedHash = seedHash; revealPrepBlock = block.number; pendingReveal = true; } /** * @dev Finalize a reveal action. * Must take place at least one block after the `prepReveal` action was taken */ function reveal(uint256 revealSeed) public onlyContractOwner{ require(pendingReveal && block.number > revealPrepBlock && keccak256(abi.encodePacked(revealSeed)) == revealSeedHash , "Reveal Conditions Not Met"); if (block.number - revealPrepBlock < 255) { bytes32 blockSeed = keccak256(abi.encodePacked(revealSeed, blockhash(revealPrepBlock))); revealBlockHashes[revealCount] = blockSeed; revealCount++; } pendingReveal = false; } /* Minting */ /** * @dev Is the minting of a specific rescueOrder needing payment or is it free? */ function paidMint(uint256 rescueOrder) public view returns (bool) { uint256 wordIndex = rescueOrder / 256; uint256 bitIndex = rescueOrder % 256; return (uint(NoChargeList[wordIndex] >> (255 - bitIndex)) & 1) == 0; } /** * @dev Create the token * Checks that the address minting is the current owner of the MoonCat, and ensures that MoonCat is Acclimated */ function handleMint(uint256 rescueOrder, address to) private { require(mintingWindowOpen, "Minting Window Closed"); require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69, "Not Acclimated"); address moonCatOwner = MCA.ownerOf(rescueOrder); require((msg.sender == moonCatOwner) || (msg.sender == MCA.getApproved(rescueOrder)) || (MCA.isApprovedForAll(moonCatOwner, msg.sender)), "Not AMC Owner or Approved" ); require(!LootprintIdByIndex.contains(rescueOrder), "Already Minted"); Lootprints[rescueOrder] = Lootprint(uint16(LootprintIdByIndex.length()), to); LootprintIdByIndex.add(rescueOrder); LootprintsByOwner[to].add(rescueOrder); emit Transfer(address(0), to, rescueOrder); } /** * @dev Mint a lootprint, and give it to a specific address */ function mint(uint256 rescueOrder, address to) public payable notFrozen { if (paidMint(rescueOrder)) { require(address(this).balance >= price, "Insufficient Value"); contractOwner.transfer(price); } handleMint(rescueOrder, to); if (address(this).balance > 0) { // The buyer over-paid; transfer their funds back to them payable(msg.sender).transfer(address(this).balance); } } /** * @dev Mint a lootprint, and give it to the address making the transaction */ function mint(uint256 rescueOrder) public payable { mint(rescueOrder, msg.sender); } /** * @dev Mint multiple lootprints, sending them all to a specific address */ function mintMultiple(uint256[] calldata rescueOrders, address to) public payable notFrozen { uint256 totalPrice = 0; for (uint i = 0; i < rescueOrders.length; i++) { if (paidMint(rescueOrders[i])) { totalPrice += price; } handleMint(rescueOrders[i], to); } require(address(this).balance >= totalPrice, "Insufficient Value"); if (totalPrice > 0) { contractOwner.transfer(totalPrice); } if (address(this).balance > 0) { // The buyer over-paid; transfer their funds back to them payable(msg.sender).transfer(address(this).balance); } } /** * @dev Mint multiple lootprints, sending them all to the address making the transaction */ function mintMultiple(uint256[] calldata rescueOrders) public payable { mintMultiple(rescueOrders, msg.sender); } /* Contract Owner */ constructor(address metadataContract) { contractOwner = payable(msg.sender); Metadata = IMoonCatLootprintsMetadata(metadataContract); // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148) .claim(msg.sender); } /** * @dev Mint the 160 Hero lootprint tokens, and give them to the contract owner */ function setupHeroShips(bool groupTwo) public onlyContractOwner { uint startIndex = 25440; if (groupTwo) { startIndex = 25520; } require(Lootprints[startIndex].owner == address(0), "Already Set Up"); for (uint i = startIndex; i < (startIndex+80); i++) { Lootprints[i] = Lootprint(uint16(LootprintIdByIndex.length()), contractOwner); LootprintIdByIndex.add(i); LootprintsByOwner[contractOwner].add(i); emit Transfer(address(0), contractOwner, i); } } /** * @dev Update the contract used for image/JSON rendering */ function setMetadataContract(address metadataContract) public onlyContractOwner{ Metadata = IMoonCatLootprintsMetadata(metadataContract); } /** * @dev Set configuration values for which MoonCat creates which color lootprint when minted */ function setColorTable(bytes32[] calldata table, uint startAt) public onlyContractOwner { for (uint i = 0; i < table.length; i++) { ColorTable[startAt + i] = table[i]; } } /** * @dev Set configuration values for which MoonCats need to pay for minting a lootprint */ function setNoChargeList (bytes32[100] calldata noChargeList) public onlyContractOwner { NoChargeList = noChargeList; } /** * @dev Set configuration values for how much a paid lootprint costs */ function setPrice(uint256 priceWei) public onlyContractOwner { price = priceWei; } /** * @dev Allow current `owner` to transfer ownership to another address */ function transferOwnership (address payable newOwner) public onlyContractOwner { contractOwner = newOwner; } /** * @dev Prevent creating lootprints */ function freeze () public onlyContractOwner notFrozen { frozen = true; } /** * @dev Enable creating lootprints */ function unfreeze () public onlyContractOwner { frozen = false; } /** * @dev Prevent any further minting from happening * Checks to ensure all have been revealed before allowing locking down the minting process */ function permanentlyCloseMintingWindow() public onlyContractOwner { require(revealCount >= 20, "Reveal Pending"); mintingWindowOpen = false; } /* Property Decoders */ function decodeColor(uint256 rescueOrder) public view returns (uint8) { uint256 wordIndex = rescueOrder / 64; uint256 nibbleIndex = rescueOrder % 64; bytes32 word = ColorTable[wordIndex]; return uint8(uint(word >> (252 - nibbleIndex * 4)) & 15); } function decodeName(uint32 seed) internal view returns (string memory) { seed = seed >> 8; uint index; string[9] memory parts; //honorific index = seed & 15; if (index < 8) { parts[0] = "The "; if (index < 4) { parts[1] = honorifics[index]; parts[2] = " "; } } seed >>= 4; //adjective if ((seed & 1) == 1) { index = (seed >> 1) & 31; parts[3] = adjectives[index]; parts[4] = " "; } seed >>= 6; //mod index = seed & 15; if (index < 15) { parts[5] = mods[index]; } seed >>= 4; //main index = seed & 31; parts[6] = mains[index]; seed >>= 5; //designation if ((seed & 1) == 1) { index = (seed >> 1) & 15; parts[7] = " "; parts[8] = designations[index]; } return string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); } function decodeClass(uint32 seed) internal pure returns (uint8) { uint class_determiner = seed & 15; if (class_determiner < 2) { return 0; } else if (class_determiner < 5) { return 1; } else if (class_determiner < 9) { return 2; } else { return 3; } } function decodeBays(uint32 seed) internal pure returns (uint8) { uint bay_determiner = (seed >> 4) & 15; if (bay_determiner < 3) { return 5; } else if (bay_determiner < 8) { return 4; } else { return 3; } } uint8 constant internal STATUS_NOT_MINTED = 0; uint8 constant internal STATUS_NOT_MINTED_FREE = 1; uint8 constant internal STATUS_PENDING = 2; uint8 constant internal STATUS_MINTED = 3; /** * @dev Get detailed traits about a lootprint token * Provides trait values in native contract return values, which can be used by other contracts */ function getDetails (uint256 lootprintId) public view returns (uint8 status, string memory class, uint8 bays, string memory colorName, string memory shipName, address tokenOwner, uint32 seed) { Lootprint memory lootprint = Lootprints[lootprintId]; colorName = Metadata.getColorName(decodeColor(lootprintId)); tokenOwner = address(0); if (LootprintIdByIndex.contains(lootprintId)) { if (revealBlockHashes[lootprint.index / 1280] > 0) { seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280])))); return (STATUS_MINTED, Metadata.getClassName(decodeClass(seed)), decodeBays(seed), colorName, decodeName(seed), lootprint.owner, seed); } status = STATUS_PENDING; tokenOwner = lootprint.owner; } else if (paidMint(lootprintId)) { status = STATUS_NOT_MINTED; } else { status = STATUS_NOT_MINTED_FREE; } return (status, "Unknown", 0, colorName, "?", tokenOwner, 0); } /* ERC-721 Metadata */ function name() public pure override returns (string memory) { return "MoonCatLootprint"; } function symbol() public pure override returns (string memory) { return unicode"📜"; } function tokenURI(uint256 lootprintId) public view override lootprintExists(lootprintId) returns (string memory) { Lootprint memory lootprint = Lootprints[lootprintId]; uint8 colorId = decodeColor(lootprintId); if (revealBlockHashes[lootprint.index / 1280] > 0) { uint32 seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280])))); uint8 classId = decodeClass(seed); string memory shipName = decodeName(seed); uint8 bays = decodeBays(seed); return Metadata.getJSON(lootprintId, classId, colorId, bays, shipName); } else { return Metadata.getJSON(lootprintId, 4, colorId, 0, "?"); } } function imageURI(uint256 lootprintId) public view lootprintExists(lootprintId) returns (string memory) { Lootprint memory lootprint = Lootprints[lootprintId]; uint8 colorId = decodeColor(lootprintId); if (revealBlockHashes[lootprint.index / 1280] > 0) { uint32 seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280])))); uint8 classId = decodeClass(seed); string memory shipName = decodeName(seed); uint8 bays = decodeBays(seed); return Metadata.getImage(lootprintId, classId, colorId, bays, shipName); } else { return Metadata.getImage(lootprintId, 4, colorId, 0, "?"); } } /* Rescue Tokens */ /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20(address tokenContract) public onlyContractOwner { IERC20 token = IERC20(tokenContract); token.transfer(contractOwner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721(address tokenContract, uint256 lootprintId) public onlyContractOwner { IERC721(tokenContract).safeTransferFrom(address(this), contractOwner, lootprintId); } }
Encodes some bytes to the base64 representation multiply by 4/3 rounded up Add some extra buffer at the end
function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; uint256 encodedLen = 4 * ((len + 2) / 3); bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); }
12,100,438
./partial_match/3/0xBcc008d20736433605c6b61f185d3B605440Eb5f/sources/pool.sol
set pooler token once/
function setPoolerToken(IPoolerToken poolerToken) external override onlyOwner { require (!poolerTokenOnce, "already set"); require(poolerToken.getPool() == address(this), "owner mismatch"); poolerTokenContract = poolerToken; poolerTokenOnce = true; }
5,123,063
pragma solidity ^0.6.4; pragma experimental ABIEncoderV2; import "../curation/ICuration.sol"; import "../epochs/IEpochManager.sol"; import "../governance/Governed.sol"; import "../token/IGraphToken.sol"; import "../upgrades/GraphProxy.sol"; import "../upgrades/GraphUpgradeable.sol"; import "./IStaking.sol"; import "./StakingStorage.sol"; import "./libs/Rebates.sol"; import "./libs/Stakes.sol"; /** * @title Staking contract */ contract Staking is StakingV1Storage, GraphUpgradeable, IStaking, Governed { using SafeMath for uint256; using Stakes for Stakes.Indexer; using Rebates for Rebates.Pool; // 100% in parts per million uint32 private constant MAX_PPM = 1000000; // -- Events -- /** * @dev Emitted when `indexer` update the delegation parameters for its delegation pool. */ event DelegationParametersUpdated( address indexed indexer, uint32 indexingRewardCut, uint32 queryFeeCut, uint32 cooldownBlocks ); /** * @dev Emitted when `indexer` stake `tokens` amount. */ event StakeDeposited(address indexed indexer, uint256 tokens); /** * @dev Emitted when `indexer` unstaked and locked `tokens` amount `until` block. */ event StakeLocked(address indexed indexer, uint256 tokens, uint256 until); /** * @dev Emitted when `indexer` withdrew `tokens` staked. */ event StakeWithdrawn(address indexed indexer, uint256 tokens); /** * @dev Emitted when `indexer` was slashed for a total of `tokens` amount. * Tracks `reward` amount of tokens given to `beneficiary`. */ event StakeSlashed( address indexed indexer, uint256 tokens, uint256 reward, address beneficiary ); /** * @dev Emitted when `delegator` delegated `tokens` to the `indexer`, the delegator * gets `shares` for the delegation pool proportionally to the tokens staked. */ event StakeDelegated( address indexed indexer, address indexed delegator, uint256 tokens, uint256 shares ); /** * @dev Emitted when `delegator` undelegated `tokens` from `indexer`. * Tokens get locked for withdrawal after a period of time. */ event StakeDelegatedLocked( address indexed indexer, address indexed delegator, uint256 tokens, uint256 shares, uint256 until ); /** * @dev Emitted when `delegator` withdrew delegated `tokens` from `indexer`. */ event StakeDelegatedWithdrawn( address indexed indexer, address indexed delegator, uint256 tokens ); /** * @dev Emitted when `indexer` allocated `tokens` amount to `subgraphDeploymentID` * during `epoch`. * `allocationID` indexer derived address used to identify the allocation. * `channelPubKey` is the public key used for routing payments to the indexer channel. * `price` price the `indexer` will charge for serving queries of the `subgraphDeploymentID`. */ event AllocationCreated( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address allocationID, bytes channelPubKey, uint256 price, address assetHolder ); /** * @dev Emitted when `indexer` collected `tokens` amount in `epoch` for `allocationID`. * These funds are related to `subgraphDeploymentID`. * The `from` value is the sender of the collected funds. */ event AllocationCollected( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address allocationID, address from, uint256 curationFees, uint256 rebateFees ); /** * @dev Emitted when `indexer` settled an allocation in `epoch` for `allocationID`. * An amount of `tokens` get unallocated from `subgraphDeploymentID`. * The `effectiveAllocation` are the tokens allocated from creation to settlement. * This event also emits the POI (proof of indexing) submitted by the indexer. */ event AllocationSettled( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address allocationID, uint256 effectiveAllocation, address sender, bytes32 poi ); /** * @dev Emitted when `indexer` claimed a rebate on `subgraphDeploymentID` during `epoch` * related to the `forEpoch` rebate pool. * The rebate is for `tokens` amount and an outstanding `settlements` are left for claim * in the rebate pool. `delegationFees` collected and sent to delegation pool. */ event RebateClaimed( address indexed indexer, bytes32 indexed subgraphDeploymentID, address allocationID, uint256 epoch, uint256 forEpoch, uint256 tokens, uint256 settlements, uint256 delegationFees ); /** * @dev Emitted when `caller` set `slasher` address as `enabled` to slash stakes. */ event SlasherUpdate(address indexed caller, address indexed slasher, bool enabled); /** * @dev Emitted when `indexer` set `operator` access. */ event SetOperator(address indexed indexer, address operator, bool allowed); /** * @dev Check if the caller is the slasher. */ modifier onlySlasher { require(slashers[msg.sender] == true, "Caller is not a Slasher"); _; } /** * @dev Check if the caller is authorized (indexer or operator) */ function _onlyAuth(address _indexer) private view returns (bool) { return msg.sender == _indexer || operatorAuth[_indexer][msg.sender] == true; } /** * @dev Check if the caller is authorized (indexer, operator or delegator) */ function _onlyAuthOrDelegator(address _indexer) private view returns (bool) { return _onlyAuth(_indexer) || delegationPools[_indexer].delegators[msg.sender].shares > 0; } /** * @dev Initialize this contract. */ function initialize( address _governor, address _token, address _epochManager ) external onlyImpl { Governed._initialize(_governor); token = IGraphToken(_token); epochManager = IEpochManager(_epochManager); } /** * @dev Accept to be an implementation of proxy and run initializer. * @param _proxy Graph proxy delegate caller * @param _token Address of the Graph Protocol token * @param _epochManager Address of the EpochManager contract */ function acceptProxy( GraphProxy _proxy, address _token, address _epochManager ) external { // Accept to be the implementation for this proxy _acceptUpgrade(_proxy); // Initialization Staking(address(_proxy)).initialize(_proxy.admin(), _token, _epochManager); } /** * @dev Set the thawing period for unstaking. * @param _thawingPeriod Period in blocks to wait for token withdrawals after unstaking */ function setThawingPeriod(uint32 _thawingPeriod) external override onlyGovernor { thawingPeriod = _thawingPeriod; emit ParameterUpdated("thawingPeriod"); } /** * @dev Set the curation contract where to send curation fees. * @param _curation Address of the curation contract */ function setCuration(address _curation) external override onlyGovernor { curation = ICuration(_curation); emit ParameterUpdated("curation"); } /** * @dev Set the curation percentage of query fees sent to curators. * @param _percentage Percentage of query fees sent to curators */ function setCurationPercentage(uint32 _percentage) external override onlyGovernor { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Curation percentage must be below or equal to MAX_PPM"); curationPercentage = _percentage; emit ParameterUpdated("curationPercentage"); } /** * @dev Set a protocol percentage to burn when collecting query fees. * @param _percentage Percentage of query fees to burn as protocol fee */ function setProtocolPercentage(uint32 _percentage) external override onlyGovernor { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Protocol percentage must be below or equal to MAX_PPM"); protocolPercentage = _percentage; emit ParameterUpdated("protocolPercentage"); } /** * @dev Set the period in epochs that need to pass before fees in rebate pool can be claimed. * @param _channelDisputeEpochs Period in epochs */ function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external override onlyGovernor { channelDisputeEpochs = _channelDisputeEpochs; emit ParameterUpdated("channelDisputeEpochs"); } /** * @dev Set the max time allowed for indexers stake on allocations. * @param _maxAllocationEpochs Allocation duration limit in epochs */ function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external override onlyGovernor { maxAllocationEpochs = _maxAllocationEpochs; emit ParameterUpdated("maxAllocationEpochs"); } /** * @dev Set the delegation capacity multiplier. * @param _delegationCapacity Delegation capacity multiplier */ function setDelegationCapacity(uint32 _delegationCapacity) external override onlyGovernor { delegationCapacity = _delegationCapacity; emit ParameterUpdated("delegationCapacity"); } /** * @dev Set the delegation parameters. * @param _indexingRewardCut Percentage of indexing rewards left for delegators * @param _queryFeeCut Percentage of query fees left for delegators * @param _cooldownBlocks Period that need to pass to update delegation parameters */ function setDelegationParameters( uint32 _indexingRewardCut, uint32 _queryFeeCut, uint32 _cooldownBlocks ) external override { address indexer = msg.sender; // Incentives must be within bounds require( _queryFeeCut <= MAX_PPM, "Delegation: QueryFeeCut must be below or equal to MAX_PPM" ); require( _indexingRewardCut <= MAX_PPM, "Delegation: IndexingRewardCut must be below or equal to MAX_PPM" ); // Cooldown period set by indexer cannot be below protocol global setting require( _cooldownBlocks >= delegationParametersCooldown, "Delegation: cooldown cannot be below minimum" ); // Verify the cooldown period passed DelegationPool storage pool = delegationPools[indexer]; require( pool.updatedAtBlock == 0 || pool.updatedAtBlock.add(uint256(pool.cooldownBlocks)) <= block.number, "Delegation: must expire cooldown period to update parameters" ); // Update delegation params pool.indexingRewardCut = _indexingRewardCut; pool.queryFeeCut = _queryFeeCut; pool.cooldownBlocks = _cooldownBlocks; pool.updatedAtBlock = block.number; emit DelegationParametersUpdated( indexer, _indexingRewardCut, _queryFeeCut, _cooldownBlocks ); } /** * @dev Set the time in blocks an indexer needs to wait to change delegation parameters. * @param _blocks Number of blocks to set the delegation parameters cooldown period */ function setDelegationParametersCooldown(uint32 _blocks) external override onlyGovernor { delegationParametersCooldown = _blocks; emit ParameterUpdated("delegationParametersCooldown"); } /** * @dev Set the period for undelegation of stake from indexer. * @param _delegationUnbondingPeriod Period in epochs to wait for token withdrawals after undelegating */ function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external override onlyGovernor { delegationUnbondingPeriod = _delegationUnbondingPeriod; emit ParameterUpdated("delegationUnbondingPeriod"); } /** * @dev Set an address as allowed slasher. * @param _slasher Address of the party allowed to slash indexers * @param _allowed True if slasher is allowed */ function setSlasher(address _slasher, bool _allowed) external override onlyGovernor { slashers[_slasher] = _allowed; emit SlasherUpdate(msg.sender, _slasher, _allowed); } /** * @dev Set the rewards manager contract. * @param _rewardsManager Address of the rewards manager contract */ function setRewardsManager(address _rewardsManager) external override onlyGovernor { rewardsManager = IRewardsManager(_rewardsManager); emit ParameterUpdated("rewardsManager"); } /** * @dev Return if allocationID is used. * @param _allocationID Address used as signer by the indexer for an allocation * @return True if allocationID already used */ function isChannel(address _allocationID) external override view returns (bool) { return _getAllocationState(_allocationID) != AllocationState.Null; } /** * @dev Getter that returns if an indexer has any stake. * @param _indexer Address of the indexer * @return True if indexer has staked tokens */ function hasStake(address _indexer) external override view returns (bool) { return stakes[_indexer].hasTokens(); } /** * @dev Return the allocation by ID. * @param _allocationID Address used as allocation identifier * @return Allocation data */ function getAllocation(address _allocationID) external override view returns (Allocation memory) { return allocations[_allocationID]; } /** * @dev Return the current state of an allocation. * @param _allocationID Address used as the allocation identifier * @return AllocationState */ function getAllocationState(address _allocationID) external override view returns (AllocationState) { return _getAllocationState(_allocationID); } /** * @dev Return the total amount of tokens allocated to subgraph. * @param _subgraphDeploymentID Address used as the allocation identifier * @return Total tokens allocated to subgraph */ function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID) external override view returns (uint256) { return subgraphAllocations[_subgraphDeploymentID]; } /** * @dev Return the delegation from a delegator to an indexer. * @param _indexer Address of the indexer where funds have been delegated * @param _delegator Address of the delegator * @return Delegation data */ function getDelegation(address _indexer, address _delegator) external override view returns (Delegation memory) { return delegationPools[_indexer].delegators[_delegator]; } /** * @dev Get the amount of shares a delegator has in a delegation pool. * @param _indexer Address of the indexer * @param _delegator Address of the delegator * @return Shares owned by delegator in a delegation pool */ function getDelegationShares(address _indexer, address _delegator) external override view returns (uint256) { return delegationPools[_indexer].delegators[_delegator].shares; } /** * @dev Get the amount of tokens a delegator has in a delegation pool. * @param _indexer Address of the indexer * @param _delegator Address of the delegator * @return Tokens owned by delegator in a delegation pool */ function getDelegationTokens(address _indexer, address _delegator) external override view returns (uint256) { // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; if (pool.shares == 0) { return 0; } uint256 _shares = delegationPools[_indexer].delegators[_delegator].shares; return _shares.mul(pool.tokens).div(pool.shares); } /** * @dev Get the total amount of tokens staked by the indexer. * @param _indexer Address of the indexer * @return Amount of tokens staked by the indexer */ function getIndexerStakedTokens(address _indexer) external override view returns (uint256) { return stakes[_indexer].tokensStaked; } /** * @dev Get the total amount of tokens available to use in allocations. * @param _indexer Address of the indexer * @return Amount of tokens staked by the indexer */ function getIndexerCapacity(address _indexer) public override view returns (uint256) { Stakes.Indexer memory indexerStake = stakes[_indexer]; DelegationPool memory pool = delegationPools[_indexer]; uint256 tokensDelegatedMax = indexerStake.tokensStaked.mul(uint256(delegationCapacity)); uint256 tokensDelegated = (pool.tokens < tokensDelegatedMax) ? pool.tokens : tokensDelegatedMax; uint256 tokensUsed = indexerStake.tokensUsed(); uint256 tokensCapacity = indexerStake.tokensStaked.add(tokensDelegated); // If more tokens are used than the current capacity, the indexer is overallocated. // This means the indexer doesn't have available capacity to create new allocations. // We can reach this state when the indexer has funds allocated and then any // of these conditions happen: // - The delegationCapacity ratio is reduced. // - The indexer stake is slashed. // - A delegator removes enough stake. if (tokensUsed > tokensCapacity) { return 0; } return tokensCapacity.sub(tokensUsed); } /** * @dev Authorize an address to be an operator. * @param _operator Address to authorize * @param _allowed Whether authorized or not */ function setOperator(address _operator, bool _allowed) external override { operatorAuth[msg.sender][_operator] = _allowed; emit SetOperator(msg.sender, _operator, _allowed); } /** * @dev Deposit tokens on the indexer stake. * @param _tokens Amount of tokens to stake */ function stake(uint256 _tokens) external override { stakeTo(msg.sender, _tokens); } /** * @dev Deposit tokens on the indexer stake. * @param _indexer Adress of the indexer * @param _tokens Amount of tokens to stake */ function stakeTo(address _indexer, uint256 _tokens) public override { require(_tokens > 0, "Staking: cannot stake zero tokens"); // Transfer tokens to stake from indexer to this contract require( token.transferFrom(_indexer, address(this), _tokens), "Staking: cannot transfer tokens to stake" ); // Stake the transferred tokens _stake(_indexer, _tokens); } /** * @dev Unstake tokens from the indexer stake, lock them until thawing period expires. * @param _tokens Amount of tokens to unstake */ function unstake(uint256 _tokens) external override { address indexer = msg.sender; Stakes.Indexer storage indexerStake = stakes[indexer]; require(indexerStake.hasTokens(), "Staking: indexer has no stakes"); require( indexerStake.tokensAvailable() >= _tokens, "Staking: not enough tokens available to unstake" ); indexerStake.lockTokens(_tokens, thawingPeriod); emit StakeLocked(indexer, indexerStake.tokensLocked, indexerStake.tokensLockedUntil); } /** * @dev Withdraw indexer tokens once the thawing period has passed. */ function withdraw() external override { address indexer = msg.sender; Stakes.Indexer storage indexerStake = stakes[indexer]; // Get tokens available for withdraw and update balance uint256 tokensToWithdraw = indexerStake.withdrawTokens(); require(tokensToWithdraw > 0, "Staking: no tokens available to withdraw"); // Return tokens to the indexer require(token.transfer(indexer, tokensToWithdraw), "Staking: cannot transfer tokens"); emit StakeWithdrawn(indexer, tokensToWithdraw); } /** * @dev Slash the indexer stake. * @param _indexer Address of indexer to slash * @param _tokens Amount of tokens to slash from the indexer stake * @param _reward Amount of reward tokens to send to a beneficiary * @param _beneficiary Address of a beneficiary to receive a reward for the slashing */ function slash( address _indexer, uint256 _tokens, uint256 _reward, address _beneficiary ) external override onlySlasher { Stakes.Indexer storage indexerStake = stakes[_indexer]; // Only able to slash a non-zero number of tokens require(_tokens > 0, "Slashing: cannot slash zero tokens"); // Rewards comes from tokens slashed balance require(_tokens >= _reward, "Slashing: reward cannot be higher than slashed amount"); // Cannot slash stake of an indexer without any or enough stake require(indexerStake.hasTokens(), "Slashing: indexer has no stakes"); require( _tokens <= indexerStake.tokensStaked, "Slashing: cannot slash more than staked amount" ); // Validate beneficiary of slashed tokens require(_beneficiary != address(0), "Slashing: beneficiary must not be an empty address"); // Slashing more tokens than freely available (over allocation condition) // Unlock locked tokens to avoid the indexer to withdraw them if (_tokens > indexerStake.tokensAvailable() && indexerStake.tokensLocked > 0) { uint256 tokensOverAllocated = _tokens.sub(indexerStake.tokensAvailable()); uint256 tokensToUnlock = (tokensOverAllocated > indexerStake.tokensLocked) ? indexerStake.tokensLocked : tokensOverAllocated; indexerStake.unlockTokens(tokensToUnlock); } // Remove tokens to slash from the stake indexerStake.release(_tokens); // Set apart the reward for the beneficiary and burn remaining slashed stake uint256 tokensToBurn = _tokens.sub(_reward); if (tokensToBurn > 0) { token.burn(tokensToBurn); } // Give the beneficiary a reward for slashing if (_reward > 0) { require( token.transfer(_beneficiary, _reward), "Slashing: error sending dispute reward" ); } emit StakeSlashed(_indexer, _tokens, _reward, _beneficiary); } /** * @dev Delegate tokens to an indexer. * @param _indexer Address of the indexer to delegate tokens to * @param _tokens Amount of tokens to delegate */ function delegate(address _indexer, uint256 _tokens) external override { address delegator = msg.sender; // Transfer tokens to delegate to this contract require( token.transferFrom(delegator, address(this), _tokens), "Delegation: Cannot transfer tokens to stake" ); // Update state _delegate(delegator, _indexer, _tokens); } /** * @dev Undelegate tokens from an indexer. * @param _indexer Address of the indexer where tokens had been delegated * @param _shares Amount of shares to return and undelegate tokens */ function undelegate(address _indexer, uint256 _shares) external override { _undelegate(msg.sender, _indexer, _shares); } /** * @dev Withdraw delegated tokens once the unbonding period has passed. * @param _indexer Withdraw available tokens delegated to indexer * @param _newIndexer Re-delegate to indexer address if non-zero, withdraw if zero address */ function withdrawDelegated(address _indexer, address _newIndexer) external override { address delegator = msg.sender; // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[delegator]; // There must be locked tokens and period passed uint256 currentEpoch = epochManager.currentEpoch(); require( delegation.tokensLockedUntil > 0 && currentEpoch >= delegation.tokensLockedUntil, "Delegation: no tokens available to withdraw" ); // Get tokens available for withdrawal uint256 tokensToWithdraw = delegation.tokensLocked; // Reset lock delegation.tokensLocked = 0; delegation.tokensLockedUntil = 0; emit StakeDelegatedWithdrawn(_indexer, delegator, tokensToWithdraw); if (_newIndexer != address(0)) { // Re-delegate tokens to a new indexer _delegate(delegator, _newIndexer, tokensToWithdraw); } else { // Return tokens to the delegator require( token.transfer(delegator, tokensToWithdraw), "Delegation: cannot transfer tokens" ); } } /** * @dev Allocate available tokens to a subgraph deployment. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _channelPubKey The public key used to route payments * @param _assetHolder Authorized sender address of collected funds * @param _price Price the `indexer` will charge for serving queries of the `subgraphDeploymentID` */ function allocate( bytes32 _subgraphDeploymentID, uint256 _tokens, bytes calldata _channelPubKey, address _assetHolder, uint256 _price ) external override { require(_onlyAuth(msg.sender), "Allocation: caller must be authorized"); _allocate(msg.sender, _subgraphDeploymentID, _tokens, _channelPubKey, _assetHolder, _price); } /** * @dev Allocate available tokens to a subgraph deployment. * @param _indexer Indexer address to allocate funds from. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _channelPubKey The public key used to route payments * @param _assetHolder Authorized sender address of collected funds * @param _price Price the `indexer` will charge for serving queries of the `subgraphDeploymentID` */ function allocateFrom( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, bytes calldata _channelPubKey, address _assetHolder, uint256 _price ) external override { require(_onlyAuth(_indexer), "Allocation: caller must be authorized"); _allocate(_indexer, _subgraphDeploymentID, _tokens, _channelPubKey, _assetHolder, _price); } /** * @dev Settle an allocation and free the staked tokens. * @param _allocationID The allocation identifier * @param _poi Proof of indexing submitted for the allocated period */ function settle(address _allocationID, bytes32 _poi) external override { // Get allocation Allocation storage alloc = allocations[_allocationID]; AllocationState allocState = _getAllocationState(_allocationID); // Allocation must exist and be active require(allocState == AllocationState.Active, "Settle: allocation must be active"); // Get indexer stakes Stakes.Indexer storage indexerStake = stakes[alloc.indexer]; // Validate that an allocation cannot be settled before one epoch uint256 currentEpoch = epochManager.currentEpoch(); uint256 epochs = alloc.createdAtEpoch < currentEpoch ? currentEpoch.sub(alloc.createdAtEpoch) : 0; require(epochs > 0, "Settle: must pass at least one epoch"); // Validate ownership if (epochs > maxAllocationEpochs) { // Verify that the allocation owner or delegator is settling require(_onlyAuthOrDelegator(alloc.indexer), "Settle: caller must be authorized"); } else { // Verify that the allocation owner is settling require(_onlyAuth(alloc.indexer), "Settle: caller must be authorized"); } // Settle the allocation and start counting a period to finalize any other // withdrawal. alloc.settledAtEpoch = currentEpoch; alloc.effectiveAllocation = _getEffectiveAllocation(alloc.tokens, epochs); // Send funds to rebate pool and account the effective allocation Rebates.Pool storage rebatePool = rebates[currentEpoch]; rebatePool.addToPool(alloc.collectedFees, alloc.effectiveAllocation); // Assign rewards _assignRewards(_allocationID); // Free allocated tokens from use indexerStake.unallocate(alloc.tokens); // Track total allocations per subgraph // Used for rewards calculations subgraphAllocations[alloc.subgraphDeploymentID] = subgraphAllocations[alloc .subgraphDeploymentID] .sub(alloc.tokens); emit AllocationSettled( alloc.indexer, alloc.subgraphDeploymentID, alloc.settledAtEpoch, alloc.tokens, _allocationID, alloc.effectiveAllocation, msg.sender, _poi ); } /** * @dev Collect query fees for an allocation. * Funds received are only accepted from a valid source. * @param _tokens Amount of tokens to collect */ function collect(uint256 _tokens, address _allocationID) external override { // Allocation identifier validation require(_allocationID != address(0), "Collect: invalid allocation"); // NOTE: commented out for easier test of state-channel integrations // NOTE: this validation might be removed in the future if no harm to the // NOTE: economic incentive structure is done by an external caller use // NOTE: of this function // The contract caller must be an asset holder registered during allocate() // Allocation memory alloc = allocations[_allocationID]; // require(alloc.assetHolder == msg.sender, "Collect: caller is not authorized"); // Transfer tokens to collect from the authorized sender require( token.transferFrom(msg.sender, address(this), _tokens), "Collect: cannot transfer tokens to collect" ); _collect(_allocationID, msg.sender, _tokens); } /** * @dev Claim tokens from the rebate pool. * @param _allocationID Allocation from where we are claiming tokens * @param _restake True if restake fees instead of transfer to indexer */ function claim(address _allocationID, bool _restake) external override { // Get allocation Allocation storage alloc = allocations[_allocationID]; AllocationState allocState = _getAllocationState(_allocationID); // Validate ownership require(_onlyAuthOrDelegator(alloc.indexer), "Rebate: caller must be authorized"); // TODO: restake when delegator called should not be allowed? // Funds can only be claimed after a period of time passed since settlement require( allocState == AllocationState.Finalized, "Rebate: allocation must be in finalized state" ); // Find a rebate pool for the settled epoch Rebates.Pool storage pool = rebates[alloc.settledAtEpoch]; // Process rebate uint256 tokensToClaim = pool.redeem(alloc.collectedFees, alloc.effectiveAllocation); // When all settlements processed then prune rebate pool if (pool.settlementsCount == 0) { delete rebates[alloc.settledAtEpoch]; } // Calculate delegation fees and add them to the delegation pool uint256 delegationFees = _collectDelegationFees(alloc.indexer, tokensToClaim); tokensToClaim = tokensToClaim.sub(delegationFees); // Purge allocation data except for: // - indexer: used in disputes and to avoid reusing an allocationID // - subgraphDeploymentID: used in disputes uint256 settledAtEpoch = alloc.settledAtEpoch; alloc.tokens = 0; // This avoid collect(), settle() and claim() to be called alloc.createdAtEpoch = 0; alloc.settledAtEpoch = 0; alloc.collectedFees = 0; alloc.effectiveAllocation = 0; alloc.assetHolder = address(0); // This avoid collect() to be called // When there are tokens to claim from the rebate pool, transfer or restake if (tokensToClaim > 0) { // Assign claimed tokens if (_restake) { // Restake to place fees into the indexer stake _stake(alloc.indexer, tokensToClaim); } else { // Transfer funds back to the indexer require( token.transfer(alloc.indexer, tokensToClaim), "Rebate: cannot transfer tokens" ); } } emit RebateClaimed( alloc.indexer, alloc.subgraphDeploymentID, _allocationID, epochManager.currentEpoch(), settledAtEpoch, tokensToClaim, pool.settlementsCount, delegationFees ); } /** * @dev Stake tokens on the indexer * @param _indexer Address of staking party * @param _tokens Amount of tokens to stake */ function _stake(address _indexer, uint256 _tokens) private { // Deposit tokens into the indexer stake Stakes.Indexer storage indexerStake = stakes[_indexer]; indexerStake.deposit(_tokens); // Initialize the delegation pool the first time DelegationPool storage pool = delegationPools[_indexer]; if (pool.updatedAtBlock == 0) { pool.indexingRewardCut = MAX_PPM; pool.queryFeeCut = MAX_PPM; pool.updatedAtBlock = block.number; } emit StakeDeposited(_indexer, _tokens); } /** * @dev Allocate available tokens to a subgraph deployment. * @param _indexer Indexer address to allocate funds from. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _channelPubKey The public key used by the indexer to setup the off-chain channel * @param _assetHolder Authorized sender address of collected funds * @param _price Price the `indexer` will charge for serving queries of the `subgraphDeploymentID` */ function _allocate( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, bytes memory _channelPubKey, address _assetHolder, uint256 _price ) private { Stakes.Indexer storage indexerStake = stakes[_indexer]; // Only allocations with a non-zero token amount are allowed require(_tokens > 0, "Allocation: cannot allocate zero tokens"); // Channel public key must be in uncompressed format require( uint8(_channelPubKey[0]) == 4 && _channelPubKey.length == 65, "Allocation: invalid channel public key" ); // Needs to have free capacity not used for other purposes to allocate require( getIndexerCapacity(_indexer) >= _tokens, "Allocation: not enough tokens available to allocate" ); // A channel public key is derived by the indexer when creating the offchain payment channel. // Get the Ethereum address from the public key and use as allocation identifier. // The allocationID will work to identify collected funds related to this allocation. address allocationID = address(uint256(keccak256(_sliceByte(bytes(_channelPubKey))))); // Cannot reuse an allocationID that has already been used in an allocation require( _getAllocationState(allocationID) == AllocationState.Null, "Allocation: allocationID already used" ); // Creates an allocation // Allocation identifiers are not reused // The authorized sender address can send collected funds to the allocation Allocation memory alloc = Allocation( _indexer, _subgraphDeploymentID, _tokens, // Tokens allocated epochManager.currentEpoch(), // createdAtEpoch 0, // settledAtEpoch 0, // Initialize collected fees 0, // Initialize effective allocation _assetHolder, // Source address for allocation collected funds _updateRewards(_subgraphDeploymentID) // Initialize accumulated rewards per stake allocated ); allocations[allocationID] = alloc; // Mark allocated tokens as used indexerStake.allocate(alloc.tokens); // Track total allocations per subgraph // Used for rewards calculations subgraphAllocations[alloc.subgraphDeploymentID] = subgraphAllocations[alloc .subgraphDeploymentID] .add(alloc.tokens); emit AllocationCreated( _indexer, _subgraphDeploymentID, alloc.createdAtEpoch, alloc.tokens, allocationID, _channelPubKey, _price, _assetHolder ); } /** * @dev Withdraw and collect funds for an allocation. * @param _allocationID Allocation that is receiving collected funds * @param _from Source of collected funds for the allocation * @param _tokens Amount of tokens to withdraw */ function _collect( address _allocationID, address _from, uint256 _tokens ) private { uint256 rebateFees = _tokens; // Get allocation Allocation storage alloc = allocations[_allocationID]; AllocationState allocState = _getAllocationState(_allocationID); // The allocation must be active or settled require( allocState == AllocationState.Active || allocState == AllocationState.Settled, "Collect: allocation must be active or settled" ); // Collect protocol fees to be burned uint256 protocolFees = _collectProtocolFees(rebateFees); rebateFees = rebateFees.sub(protocolFees); // Calculate curation fees only if the subgraph deployment is curated uint256 curationFees = _collectCurationFees(alloc.subgraphDeploymentID, rebateFees); rebateFees = rebateFees.sub(curationFees); // Collect funds for the allocation alloc.collectedFees = alloc.collectedFees.add(rebateFees); // When allocation is settled redirect funds to the rebate pool // This way we can keep collecting tokens even after settlement until the allocation // gets to the finalized state. if (allocState == AllocationState.Settled) { Rebates.Pool storage rebatePool = rebates[alloc.settledAtEpoch]; rebatePool.fees = rebatePool.fees.add(rebateFees); } // TODO: for consistency we could burn protocol fees here // Send curation fees to the curator reserve pool if (curationFees > 0) { // TODO: the approve call can be optimized by approving the curation contract to fetch // funds from the Staking contract for infinity funds just once for a security tradeoff require( token.approve(address(curation), curationFees), "Collect: token approval failed" ); curation.collect(alloc.subgraphDeploymentID, curationFees); } emit AllocationCollected( alloc.indexer, alloc.subgraphDeploymentID, epochManager.currentEpoch(), _tokens, _allocationID, _from, curationFees, rebateFees ); } /** * @dev Delegate tokens to an indexer. * @param _delegator Address of the delegator * @param _indexer Address of the indexer to delegate tokens to * @param _tokens Amount of tokens to delegate * @return Amount of shares issued of the delegation pool */ function _delegate( address _delegator, address _indexer, uint256 _tokens ) private returns (uint256) { // Can only delegate a non-zero amount of tokens require(_tokens > 0, "Delegation: cannot delegate zero tokens"); // Can only delegate to non-empty address require(_indexer != address(0), "Delegation: cannot delegate to empty address"); // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; // Calculate shares to issue uint256 shares = (pool.tokens == 0) ? _tokens : _tokens.mul(pool.shares).div(pool.tokens); // Update the delegation pool pool.tokens = pool.tokens.add(_tokens); pool.shares = pool.shares.add(shares); // Update the delegation delegation.shares = delegation.shares.add(shares); emit StakeDelegated(_indexer, _delegator, _tokens, shares); return shares; } /** * @dev Undelegate tokens from an indexer. * @param _delegator Address of the delegator * @param _indexer Address of the indexer where tokens had been delegated * @param _shares Amount of shares to return and undelegate tokens * @return Amount of tokens returned for the shares of the delegation pool */ function _undelegate( address _delegator, address _indexer, uint256 _shares ) private returns (uint256) { // Can only undelegate a non-zero amount of shares require(_shares > 0, "Delegation: cannot undelegate zero shares"); // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; // Delegator need to have enough shares in the pool to undelegate require(delegation.shares >= _shares, "Delegation: delegator does not have enough shares"); // Calculate tokens to get in exchange for the shares uint256 tokens = _shares.mul(pool.tokens).div(pool.shares); // Update the delegation pool pool.tokens = pool.tokens.sub(tokens); pool.shares = pool.shares.sub(_shares); // Update the delegation delegation.shares = delegation.shares.sub(_shares); delegation.tokensLocked = delegation.tokensLocked.add(tokens); delegation.tokensLockedUntil = epochManager.currentEpoch().add(delegationUnbondingPeriod); emit StakeDelegatedLocked( _indexer, _delegator, tokens, _shares, delegation.tokensLockedUntil ); return tokens; } /** * @dev Collect the delegation fees related to an indexer from an amount of tokens. * This function will also assign the collected fees to the delegation pool. * @param _indexer Indexer to which the delegation fees are related * @param _tokens Total tokens received used to calculate the amount of fees to collect * @return Amount of delegation fees */ function _collectDelegationFees(address _indexer, uint256 _tokens) private returns (uint256) { uint256 delegationFees = 0; DelegationPool storage pool = delegationPools[_indexer]; if (pool.tokens > 0 && pool.queryFeeCut < MAX_PPM) { uint256 indexerCut = uint256(pool.queryFeeCut).mul(_tokens).div(MAX_PPM); delegationFees = _tokens.sub(indexerCut); pool.tokens = pool.tokens.add(delegationFees); } return delegationFees; } /** * @dev Collect the curation fees for a subgraph deployment from an amount of tokens. * @param _subgraphDeploymentID Subgraph deployment to which the curation fees are related * @param _tokens Total tokens received used to calculate the amount of fees to collect * @return Amount of curation fees */ function _collectCurationFees(bytes32 _subgraphDeploymentID, uint256 _tokens) private view returns (uint256) { bool isCurationEnabled = curationPercentage > 0 && address(curation) != address(0); if (isCurationEnabled && curation.isCurated(_subgraphDeploymentID)) { return uint256(curationPercentage).mul(_tokens).div(MAX_PPM); } return 0; } /** * @dev Collect and burn the protocol fees for an amount of tokens. * @param _tokens Total tokens received used to calculate the amount of fees to collect * @return Amount of protocol fees */ function _collectProtocolFees(uint256 _tokens) private returns (uint256) { if (protocolPercentage == 0) { return 0; } uint256 protocolFees = uint256(protocolPercentage).mul(_tokens).div(MAX_PPM); if (protocolFees > 0) { token.burn(protocolFees); } return protocolFees; } /** * @dev Return the current state of an allocation * @param _allocationID Allocation identifier * @return AllocationState */ function _getAllocationState(address _allocationID) private view returns (AllocationState) { Allocation memory alloc = allocations[_allocationID]; if (alloc.indexer == address(0)) { return AllocationState.Null; } if (alloc.tokens == 0) { return AllocationState.Claimed; } if (alloc.settledAtEpoch == 0) { return AllocationState.Active; } uint256 epochs = epochManager.epochsSince(alloc.settledAtEpoch); if (epochs >= channelDisputeEpochs) { return AllocationState.Finalized; } return AllocationState.Settled; } /** * @dev Get the effective stake allocation considering epochs from allocation to settlement. * @param _tokens Amount of tokens allocated * @param _numEpochs Number of epochs that passed from allocation to settlement * @return Effective allocated tokens accross epochs */ function _getEffectiveAllocation(uint256 _tokens, uint256 _numEpochs) private view returns (uint256) { bool shouldCap = maxAllocationEpochs > 0 && _numEpochs > maxAllocationEpochs; return _tokens.mul((shouldCap) ? maxAllocationEpochs : _numEpochs); } /** * @dev Get the running network chain ID * @return The chain ID */ function _getChainID() private pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Removes the first byte from a bytes array. * @param _bytes Byte array to slice * @return New bytes array */ function _sliceByte(bytes memory _bytes) private pure returns (bytes memory) { bytes memory tempBytes; uint256 length = _bytes.length - 1; assembly { tempBytes := mload(0x40) let lengthmod := and(length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), 1) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, length) mstore(0x40, and(add(mc, 31), not(31))) } return tempBytes; } /** * @dev Triggers an update of rewards due to a change in allocations. * @param _subgraphDeploymentID Subgrapy deployment updated */ function _updateRewards(bytes32 _subgraphDeploymentID) internal returns (uint256) { if (address(rewardsManager) == address(0)) { return 0; } return rewardsManager.onSubgraphAllocationUpdate(_subgraphDeploymentID); } /** * @dev Assign rewards for the settled allocation to the indexer. * @param _allocationID Allocation */ function _assignRewards(address _allocationID) internal returns (uint256) { if (address(rewardsManager) == address(0)) { return 0; } // Automatically triggers update of rewards snapshot as allocation will change return rewardsManager.assignRewards(_allocationID); } }
Initialize this contract./
function initialize( address _governor, address _token, address _epochManager ) external onlyImpl { Governed._initialize(_governor); token = IGraphToken(_token); epochManager = IEpochManager(_epochManager); }
5,377,285
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' 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: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IAccessControl.sol"; /** * @dev This contract is fully forked from OpenZeppelin `AccessControl`. * The only difference is the removal of the ERC165 implementation as it's not * needed in Angle. * * Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external override { require(account == _msgSender(), "71"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "../interfaces/external/compound/CErc20I.sol"; import "../interfaces/external/compound/IComptroller.sol"; import "../interfaces/external/compound/InterestRateModel.sol"; import "../interfaces/external/uniswap/IUniswapRouter.sol"; import "./GenericLenderBase.sol"; /// @title GenericCompound /// @author Forker from here: https://github.com/Grandthrax/yearnV2-generic-lender-strat/blob/master/contracts/GenericLender/GenericCompound.sol /// @notice A contract to lend any ERC20 to Compound contract GenericCompound is GenericLenderBase { using SafeERC20 for IERC20; using Address for address; event PathUpdated(bytes _path); uint256 public constant BLOCKS_PER_YEAR = 2_350_000; // ==================== References to contracts ============================= CErc20I public immutable cToken; address public immutable comp; IComptroller public immutable comptroller; IUniswapV3Router public immutable uniswapV3Router; // Used to get the `want` price of the AAVE token IUniswapV2Router public immutable uniswapV2Router; address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // ==================== Parameters ============================= bytes public path; uint256 public minCompToSell = 0.5 ether; // ============================= Constructor ============================= /// @notice Constructor of the `GenericCompound` /// @param _strategy Reference to the strategy using this lender /// @param _path Bytes to encode the swap from `comp` to `want` /// @param _cToken Address of the cToken /// @param governorList List of addresses with governor privilege /// @param guardian Address of the guardian constructor( address _strategy, string memory name, IUniswapV3Router _uniswapV3Router, IUniswapV2Router _uniswapV2Router, IComptroller _comptroller, address _comp, bytes memory _path, address _cToken, address[] memory governorList, address guardian ) GenericLenderBase(_strategy, name, governorList, guardian) { // This transaction is going to revert if `_strategy`, `_comp` or `_cToken` are equal to the zero address require( address(_uniswapV2Router) != address(0) && address(_uniswapV3Router) != address(0) && address(_comptroller) != address(0), "0" ); path = _path; uniswapV3Router = _uniswapV3Router; uniswapV2Router = _uniswapV2Router; comptroller = _comptroller; comp = _comp; cToken = CErc20I(_cToken); require(CErc20I(_cToken).underlying() == address(want), "wrong cToken"); want.safeApprove(_cToken, type(uint256).max); IERC20(_comp).safeApprove(address(_uniswapV3Router), type(uint256).max); } // ===================== External Strategy Functions =========================== /// @notice Deposits the current balance of the contract to the lending platform function deposit() external override onlyRole(STRATEGY_ROLE) { uint256 balance = want.balanceOf(address(this)); require(cToken.mint(balance) == 0, "mint fail"); } /// @notice Withdraws a given amount from lender /// @param amount The amount the caller wants to withdraw /// @return Amount actually withdrawn function withdraw(uint256 amount) external override onlyRole(STRATEGY_ROLE) returns (uint256) { return _withdraw(amount); } /// @notice Withdraws as much as possible from the lending platform /// @return Whether everything was withdrawn or not function withdrawAll() external override onlyRole(STRATEGY_ROLE) returns (bool) { uint256 invested = _nav(); uint256 returned = _withdraw(invested); return returned >= invested; } // ============================= External View Functions ============================= /// @notice Helper function to get the current total of assets managed by the lender. function nav() external view override returns (uint256) { return _nav(); } /// @notice Helper function the current balance of cTokens function underlyingBalanceStored() public view returns (uint256 balance) { uint256 currentCr = cToken.balanceOf(address(this)); if (currentCr == 0) { balance = 0; } else { //The current exchange rate as an unsigned integer, scaled by 1e18. balance = (currentCr * cToken.exchangeRateStored()) / 1e18; } } /// @notice Returns an estimation of the current Annual Percentage Rate function apr() external view override returns (uint256) { return _apr(); } /// @notice Returns an estimation of the current Annual Percentage Rate weighted by a factor function weightedApr() external view override returns (uint256) { uint256 a = _apr(); return a * _nav(); } /// @notice Returns an estimation of the current Annual Percentage Rate after a new deposit /// of `amount` /// @param amount Amount to add to the lending platform, and that we want to take into account /// in the apr computation function aprAfterDeposit(uint256 amount) external view override returns (uint256) { uint256 cashPrior = want.balanceOf(address(cToken)); uint256 borrows = cToken.totalBorrows(); uint256 reserves = cToken.totalReserves(); uint256 reserverFactor = cToken.reserveFactorMantissa(); InterestRateModel model = cToken.interestRateModel(); // The supply rate is derived from the borrow rate, reserve factor and the amount of total borrows. uint256 supplyRate = model.getSupplyRate(cashPrior + amount, borrows, reserves, reserverFactor); // Adding the yield from comp return supplyRate * BLOCKS_PER_YEAR + _incentivesRate(amount); } /// @notice Check if assets are currently managed by this contract function hasAssets() external view override returns (bool) { return cToken.balanceOf(address(this)) > 0 || want.balanceOf(address(this)) > 0; } // ============================= Governance ============================= /// @notice Sets the path for the swap of `comp` tokens /// @param _path New path function setPath(bytes memory _path) external onlyRole(GUARDIAN_ROLE) { path = _path; emit PathUpdated(_path); } /// @notice Withdraws as much as possible in case of emergency and sends it to the `PoolManager` /// @param amount Amount to withdraw /// @dev Does not check if any error occurs or if the amount withdrawn is correct function emergencyWithdraw(uint256 amount) external override onlyRole(GUARDIAN_ROLE) { // Do not care about errors here, what is important is to withdraw what is possible cToken.redeemUnderlying(amount); want.safeTransfer(address(poolManager), want.balanceOf(address(this))); } // ============================= Internal Functions ============================= /// @notice See `apr` function _apr() internal view returns (uint256) { return cToken.supplyRatePerBlock() * BLOCKS_PER_YEAR + _incentivesRate(0); } /// @notice See `nav` function _nav() internal view returns (uint256) { return want.balanceOf(address(this)) + underlyingBalanceStored(); } /// @notice See `withdraw` function _withdraw(uint256 amount) internal returns (uint256) { uint256 balanceUnderlying = cToken.balanceOfUnderlying(address(this)); uint256 looseBalance = want.balanceOf(address(this)); uint256 total = balanceUnderlying + looseBalance; if (amount > total) { // Can't withdraw more than we own amount = total; } if (looseBalance >= amount) { want.safeTransfer(address(strategy), amount); return amount; } // Not state changing but OK because of previous call uint256 liquidity = want.balanceOf(address(cToken)); if (liquidity > 1) { uint256 toWithdraw = amount - looseBalance; if (toWithdraw <= liquidity) { // We can take all require(cToken.redeemUnderlying(toWithdraw) == 0, "redeemUnderlying fail"); } else { // Take all we can require(cToken.redeemUnderlying(liquidity) == 0, "redeemUnderlying fail"); } } _disposeOfComp(); looseBalance = want.balanceOf(address(this)); want.safeTransfer(address(strategy), looseBalance); return looseBalance; } /// @notice Claims and swaps from Uniswap the `comp` earned function _disposeOfComp() internal { uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > minCompToSell) { uniswapV3Router.exactInput(ExactInputParams(path, address(this), block.timestamp, _comp, uint256(0))); } } /// @notice Calculates APR from Compound's Liquidity Mining Program /// @param amountToAdd Amount to add to the `totalSupplyInWant` (for the `aprAfterDeposit` function) function _incentivesRate(uint256 amountToAdd) internal view returns (uint256) { uint256 supplySpeed = comptroller.compSupplySpeeds(address(cToken)); uint256 totalSupplyInWant = (cToken.totalSupply() * cToken.exchangeRateStored()) / 1e18 + amountToAdd; // `supplySpeed` is in `COMP` unit -> the following operation is going to put it in `want` unit supplySpeed = _comptoWant(supplySpeed); uint256 incentivesRate; // Added for testing purposes and to handle the edge case where there is nothing left in a market if (totalSupplyInWant == 0) { incentivesRate = supplySpeed * BLOCKS_PER_YEAR; } else { // `incentivesRate` is expressed in base 18 like all APR incentivesRate = (supplySpeed * BLOCKS_PER_YEAR * 1e18) / totalSupplyInWant; } return (incentivesRate * 9500) / 10000; // 95% of estimated APR to avoid overestimations } /// @notice Estimates the value of `_amount` AAVE tokens /// @param _amount Amount of comp to compute the `want` price of /// @dev This function uses a UniswapV2 oracle to easily compute the price (which is not feasible /// with UniswapV3) function _comptoWant(uint256 _amount) internal view returns (uint256) { if (_amount == 0) { return 0; } // We use a different path when trying to get the price of the AAVE in `want` address[] memory pathPrice; if (address(want) == address(WETH)) { pathPrice = new address[](2); pathPrice[0] = address(comp); pathPrice[1] = address(want); } else { pathPrice = new address[](3); pathPrice[0] = address(comp); pathPrice[1] = address(WETH); pathPrice[2] = address(want); } uint256[] memory amounts = uniswapV2Router.getAmountsOut(_amount, pathPrice); // APRs are in 1e18 return amounts[amounts.length - 1]; } /// @notice Specifies the token managed by this contract during normal operation function _protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](3); protected[0] = address(want); protected[1] = address(cToken); protected[2] = comp; return protected; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../external/AccessControl.sol"; import "../interfaces/IGenericLender.sol"; import "../interfaces/IPoolManager.sol"; import "../interfaces/IStrategy.sol"; /// @title GenericLenderBase /// @author Forked from https://github.com/Grandthrax/yearnV2-generic-lender-strat/tree/master/contracts/GenericLender /// @notice A base contract to build contracts to lend assets abstract contract GenericLenderBase is IGenericLender, AccessControl { using SafeERC20 for IERC20; bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE"); string public override lenderName; // ============================= References to contracts ============================= /// @notice Reference to the protocol's collateral poolManager IPoolManager public poolManager; /// @notice Reference to the `Strategy` address public override strategy; /// @notice Reference to the token lent IERC20 public want; // ============================= Constructor ============================= /// @notice Constructor of the `GenericLenderBase` /// @param _strategy Reference to the strategy using this lender /// @param governorList List of addresses with governor privilege /// @param guardian Address of the guardian constructor( address _strategy, string memory _name, address[] memory governorList, address guardian ) { strategy = _strategy; // The corresponding `PoolManager` is inferred from the `Strategy` poolManager = IPoolManager(IStrategy(strategy).poolManager()); want = IERC20(poolManager.token()); lenderName = _name; _setupRole(GUARDIAN_ROLE, address(poolManager)); for (uint256 i = 0; i < governorList.length; i++) { _setupRole(GUARDIAN_ROLE, governorList[i]); } _setupRole(GUARDIAN_ROLE, guardian); _setupRole(STRATEGY_ROLE, _strategy); _setRoleAdmin(GUARDIAN_ROLE, STRATEGY_ROLE); _setRoleAdmin(STRATEGY_ROLE, GUARDIAN_ROLE); want.safeApprove(_strategy, type(uint256).max); } // ============================= Governance ============================= /// @notice Override this to add all tokens/tokenized positions this contract /// manages on a *persistent* basis (e.g. not just for swapping back to /// want ephemerally). /// /// Example: /// ``` /// function _protectedTokens() internal override view returns (address[] memory) { /// address[] memory protected = new address[](3); /// protected[0] = tokenA; /// protected[1] = tokenB; /// protected[2] = tokenC; /// return protected; /// } /// ``` function _protectedTokens() internal view virtual returns (address[] memory); /// @notice /// Removes tokens from this Strategy that are not the type of tokens /// managed by this Strategy. This may be used in case of accidentally /// sending the wrong kind of token to this Strategy. /// /// Tokens will be sent to `governance()`. /// /// This will fail if an attempt is made to sweep `want`, or any tokens /// that are protected by this Strategy. /// /// This may only be called by governance. /// @param _token The token to transfer out of this poolManager. /// @param to Address to send the tokens to. /// @dev /// Implement `_protectedTokens()` to specify any additional tokens that /// should be protected from sweeping in addition to `want`. function sweep(address _token, address to) external override onlyRole(GUARDIAN_ROLE) { address[] memory __protectedTokens = _protectedTokens(); for (uint256 i = 0; i < __protectedTokens.length; i++) require(_token != __protectedTokens[i], "93"); IERC20(_token).safeTransfer(to, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IERC721 is IERC165 { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IFeeManagerFunctions /// @author Angle Core Team /// @dev Interface for the `FeeManager` contract interface IFeeManagerFunctions is IAccessControl { // ================================= Keepers =================================== function updateUsersSLP() external; function updateHA() external; // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external; function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external; function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external; } /// @title IFeeManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev We need these getters as they are used in other contracts of the protocol interface IFeeManager is IFeeManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IGenericLender /// @author Yearn with slight modifications from Angle Core Team /// @dev Interface for the `GenericLender` contract, the base interface for contracts interacting /// with lending and yield farming platforms interface IGenericLender is IAccessControl { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function sweep(address _token, address to) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IOracle /// @author Angle Core Team /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink /// from just UniswapV3 or from just Chainlink interface IOracle { function read() external view returns (uint256); function readAll() external view returns (uint256 lowerRate, uint256 upperRate); function readLower() external view returns (uint256); function readUpper() external view returns (uint256); function readQuote(uint256 baseAmount) external view returns (uint256); function readQuoteLower(uint256 baseAmount) external view returns (uint256); function inBase() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IERC721.sol"; import "./IFeeManager.sol"; import "./IOracle.sol"; import "./IAccessControl.sol"; /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IPerpetualManagerFront is IERC721Metadata { function openPerpetual( address owner, uint256 amountBrought, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; function addToPerpetual(uint256 perpetualID, uint256 amount) external; function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; function liquidatePerpetuals(uint256[] memory perpetualIDs) external; function forceClosePerpetuals(uint256[] memory perpetualIDs) external; // ========================= External View Functions ============================= function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); } /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev This interface does not contain user facing functions, it just has functions that are /// interacted with in other parts of the protocol interface IPerpetualManagerFunctions is IAccessControl { // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager, IOracle oracle_ ) external; function setFeeManager(IFeeManager feeManager_) external; function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external; function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external; function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external; function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external; function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external; function setLockTime(uint64 _lockTime) external; function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external; function pause() external; function unpause() external; // ==================================== Keepers ================================ function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external; // =============================== StableMaster ================================ function setOracle(IOracle _oracle) external; } /// @title IPerpetualManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IPerpetualManager is IPerpetualManagerFunctions { function poolManager() external view returns (address); function oracle() external view returns (address); function targetHAHedge() external view returns (uint64); function totalHedgeAmount() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IFeeManager.sol"; import "./IPerpetualManager.sol"; import "./IOracle.sol"; // Struct for the parameters associated to a strategy interacting with a collateral `PoolManager` // contract struct StrategyParams { // Timestamp of last report made by this strategy // It is also used to check if a strategy has been initialized uint256 lastReport; // Total amount the strategy is expected to have uint256 totalStrategyDebt; // The share of the total assets in the `PoolManager` contract that the `strategy` can access to. uint256 debtRatio; } /// @title IPoolManagerFunctions /// @author Angle Core Team /// @notice Interface for the collateral poolManager contracts handling each one type of collateral for /// a given stablecoin /// @dev Only the functions used in other contracts of the protocol are left here interface IPoolManagerFunctions { // ============================ Constructor ==================================== function deployCollateral( address[] memory governorList, address guardian, IPerpetualManager _perpetualManager, IFeeManager feeManager, IOracle oracle ) external; // ============================ Yield Farming ================================== function creditAvailable() external view returns (uint256); function debtOutstanding() external view returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external; // ============================ Governance ===================================== function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian, address guardian) external; function revokeGuardian(address guardian) external; function setFeeManager(IFeeManager _feeManager) external; // ============================= Getters ======================================= function getBalance() external view returns (uint256); function getTotalAsset() external view returns (uint256); } /// @title IPoolManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev Used in other contracts of the protocol interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IStrategy /// @author Inspired by Yearn with slight changes from Angle Core Team /// @notice Interface for yield farming strategies interface IStrategy is IAccessControl { function estimatedAPR() external view returns (uint256); function poolManager() external view returns (address); function want() external view returns (address); function isActive() external view returns (bool); function estimatedTotalAssets() external view returns (uint256); function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; function withdraw(uint256 _amountNeeded) external returns (uint256 amountFreed, uint256 _loss); function setEmergencyExit() external; function addGuardian(address _guardian) external; function revokeGuardian(address _guardian) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; import "./CTokenI.sol"; interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function underlying() external view returns (address); function borrow(uint256 borrowAmount) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./InterestRateModel.sol"; interface CTokenI { function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function supplyRatePerBlock() external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface IComptroller { function compSupplySpeeds(address cToken) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface InterestRateModel { /** * @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( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); // Rinkeby function function getBorrowRate( uint256 cash, uint256 borrows, uint256 _reserves ) external view returns (uint256, uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniswapV3Router { /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); } /// @title Router for price estimation functionality /// @notice Functions for getting the price of one token with respect to another using Uniswap V2 /// @dev This interface is only used for non critical elements of the protocol interface IUniswapV2Router { /// @notice Given an input asset amount, returns the maximum output amount of the /// other asset (accounting for fees) given reserves. /// @param path Addresses of the pools used to get prices function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); }
Router for price estimation functionality Functions for getting the price of one token with respect to another using Uniswap V2 This interface is only used for non critical elements of the protocol
interface IUniswapV2Router { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } }
1,475,964
pragma solidity ^0.4.19; // ERC20 token protocol, see more details at // https://theethereum.wiki/w/index.php/ERC20_Token_Standard // And also https://github.com/ethereum/eips/issues/20 contract Token { string public name; string public symbol; uint8 public decimals; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // Safe mathematics to make the code more readable contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } // Ownable interface to simplify owner checks contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner { require(_newOwner != address(0)); owner = _newOwner; } } // Interface for trading discounts and rebates for specific accounts contract AccountModifiersInterface { function accountModifiers(address _user) constant returns(uint takeFeeDiscount, uint rebatePercentage); function tradeModifiers(address _maker, address _taker) constant returns(uint takeFeeDiscount, uint rebatePercentage); } // Interface for trade tacker contract TradeTrackerInterface { function tradeComplete(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, address _get, address _give, uint _takerFee, uint _makerRebate); } // Exchange contract contract TokenStore is SafeMath, Ownable { // The account that will receive fees address feeAccount; // The account that stores fee discounts/rebates address accountModifiers; // Trade tracker account address tradeTracker; // We charge only the takers and this is the fee, percentage times 1 ether uint public fee; // Mapping of token addresses to mapping of account balances (token 0 means Ether) mapping (address => mapping (address => uint)) public tokens; // Mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled) mapping (address => mapping (bytes32 => uint)) public orderFills; // Address of a next and previous versions of the contract, also status of the contract // can be used for user-triggered fund migrations address public successor; address public predecessor; bool public deprecated; uint16 public version; // Logging events // Note: Order creation is handled off-chain, see explanation further below event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give, uint nonce); event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); event FundsMigrated(address user); function TokenStore(uint _fee, address _predecessor) { feeAccount = owner; fee = _fee; predecessor = _predecessor; deprecated = false; if (predecessor != address(0)) { version = TokenStore(predecessor).version() + 1; } else { version = 1; } } // Throw on default handler to prevent direct transactions of Ether function() { revert(); } modifier deprecable() { require(!deprecated); _; } function deprecate(bool _deprecated, address _successor) onlyOwner { deprecated = _deprecated; successor = _successor; } function changeFeeAccount(address _feeAccount) onlyOwner { require(_feeAccount != address(0)); feeAccount = _feeAccount; } function changeAccountModifiers(address _accountModifiers) onlyOwner { accountModifiers = _accountModifiers; } function changeTradeTracker(address _tradeTracker) onlyOwner { tradeTracker = _tradeTracker; } // Fee can only be decreased! function changeFee(uint _fee) onlyOwner { require(_fee <= fee); fee = _fee; } // Allows a user to get her current discount/rebate function getAccountModifiers() constant returns(uint takeFeeDiscount, uint rebatePercentage) { if (accountModifiers != address(0)) { return AccountModifiersInterface(accountModifiers).accountModifiers(msg.sender); } else { return (0, 0); } } //////////////////////////////////////////////////////////////////////////////// // Deposits, withdrawals, balances //////////////////////////////////////////////////////////////////////////////// function deposit() payable deprecable { tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value); Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); } function withdraw(uint _amount) { require(tokens[0][msg.sender] >= _amount); tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], _amount); if (!msg.sender.call.value(_amount)()) { revert(); } Withdraw(0, msg.sender, _amount, tokens[0][msg.sender]); } function depositToken(address _token, uint _amount) deprecable { // Note that Token(_token).approve(this, _amount) needs to be called // first or this contract will not be able to do the transfer. require(_token != 0); if (!Token(_token).transferFrom(msg.sender, this, _amount)) { revert(); } tokens[_token][msg.sender] = safeAdd(tokens[_token][msg.sender], _amount); Deposit(_token, msg.sender, _amount, tokens[_token][msg.sender]); } function withdrawToken(address _token, uint _amount) { require(_token != 0); require(tokens[_token][msg.sender] >= _amount); tokens[_token][msg.sender] = safeSub(tokens[_token][msg.sender], _amount); if (!Token(_token).transfer(msg.sender, _amount)) { revert(); } Withdraw(_token, msg.sender, _amount, tokens[_token][msg.sender]); } function balanceOf(address _token, address _user) constant returns (uint) { return tokens[_token][_user]; } //////////////////////////////////////////////////////////////////////////////// // Trading //////////////////////////////////////////////////////////////////////////////// // Note: Order creation happens off-chain but the orders are signed by creators, // we validate the contents and the creator address in the logic below function trade(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s, uint _amount) { bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce); // Check order signatures and expiration, also check if not fulfilled yet if (ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s) != _user || block.number > _expires || safeAdd(orderFills[_user][hash], _amount) > _amountGet) { revert(); } tradeBalances(_tokenGet, _amountGet, _tokenGive, _amountGive, _user, msg.sender, _amount); orderFills[_user][hash] = safeAdd(orderFills[_user][hash], _amount); Trade(_tokenGet, _amount, _tokenGive, _amountGive * _amount / _amountGet, _user, msg.sender, _nonce); } function tradeBalances(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, address _user, address _caller, uint _amount) private { uint feeTakeValue = safeMul(_amount, fee) / (1 ether); uint rebateValue = 0; uint tokenGiveValue = safeMul(_amountGive, _amount) / _amountGet; // Proportionate to request ratio // Apply modifiers if (accountModifiers != address(0)) { var (feeTakeDiscount, rebatePercentage) = AccountModifiersInterface(accountModifiers).tradeModifiers(_user, _caller); // Check that the discounts/rebates are never higher then 100% if (feeTakeDiscount > 100) { feeTakeDiscount = 0; } if (rebatePercentage > 100) { rebatePercentage = 0; } feeTakeValue = safeMul(feeTakeValue, 100 - feeTakeDiscount) / 100; // discounted fee rebateValue = safeMul(rebatePercentage, feeTakeValue) / 100; // % of actual taker fee } tokens[_tokenGet][_user] = safeAdd(tokens[_tokenGet][_user], safeAdd(_amount, rebateValue)); tokens[_tokenGet][_caller] = safeSub(tokens[_tokenGet][_caller], safeAdd(_amount, feeTakeValue)); tokens[_tokenGive][_user] = safeSub(tokens[_tokenGive][_user], tokenGiveValue); tokens[_tokenGive][_caller] = safeAdd(tokens[_tokenGive][_caller], tokenGiveValue); tokens[_tokenGet][feeAccount] = safeAdd(tokens[_tokenGet][feeAccount], safeSub(feeTakeValue, rebateValue)); if (tradeTracker != address(0)) { TradeTrackerInterface(tradeTracker).tradeComplete(_tokenGet, _amount, _tokenGive, tokenGiveValue, _user, _caller, feeTakeValue, rebateValue); } } function testTrade(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s, uint _amount, address _sender) constant returns(bool) { if (tokens[_tokenGet][_sender] < _amount || availableVolume(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _user, _v, _r, _s) < _amount) { return false; } return true; } function availableVolume(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s) constant returns(uint) { bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce); if (ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s) != _user || block.number > _expires) { return 0; } uint available1 = safeSub(_amountGet, orderFills[_user][hash]); uint available2 = safeMul(tokens[_tokenGive][_user], _amountGet) / _amountGive; if (available1 < available2) return available1; return available2; } function amountFilled(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user) constant returns(uint) { bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce); return orderFills[_user][hash]; } function cancelOrder(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, uint8 _v, bytes32 _r, bytes32 _s) { bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce); if (!(ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s) == msg.sender)) { revert(); } orderFills[msg.sender][hash] = _amountGet; Cancel(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, msg.sender, _v, _r, _s); } //////////////////////////////////////////////////////////////////////////////// // Migrations //////////////////////////////////////////////////////////////////////////////// // User-triggered (!) fund migrations in case contract got updated // Similar to withdraw but we use a successor account instead // As we don't store user tokens list on chain, it has to be passed from the outside function migrateFunds(address[] _tokens) { // Get the latest successor in the chain require(successor != address(0)); TokenStore newExchange = TokenStore(successor); for (uint16 n = 0; n < 20; n++) { // We will look past 20 contracts in the future address nextSuccessor = newExchange.successor(); if (nextSuccessor == address(this)) { // Circular succession revert(); } if (nextSuccessor == address(0)) { // We reached the newest, stop break; } newExchange = TokenStore(nextSuccessor); } // Ether uint etherAmount = tokens[0][msg.sender]; if (etherAmount > 0) { tokens[0][msg.sender] = 0; newExchange.depositForUser.value(etherAmount)(msg.sender); } // Tokens for (n = 0; n < _tokens.length; n++) { address token = _tokens[n]; require(token != address(0)); // 0 = Ether, we handle it above uint tokenAmount = tokens[token][msg.sender]; if (tokenAmount == 0) { continue; } if (!Token(token).approve(newExchange, tokenAmount)) { revert(); } tokens[token][msg.sender] = 0; newExchange.depositTokenForUser(token, tokenAmount, msg.sender); } FundsMigrated(msg.sender); } // This is used for migrations only. To be called by previous exchange only, // user-triggered, on behalf of the user called the migrateFunds method. // Note that it does exactly the same as depositToken, but as this is called // by a previous generation of exchange itself, we credit internally not the // previous exchange, but the user it was called for. function depositForUser(address _user) payable deprecable { require(_user != address(0)); require(msg.value > 0); TokenStore caller = TokenStore(msg.sender); require(caller.version() > 0); // Make sure it's an exchange account tokens[0][_user] = safeAdd(tokens[0][_user], msg.value); } function depositTokenForUser(address _token, uint _amount, address _user) deprecable { require(_token != address(0)); require(_user != address(0)); require(_amount > 0); TokenStore caller = TokenStore(msg.sender); require(caller.version() > 0); // Make sure it's an exchange account if (!Token(_token).transferFrom(msg.sender, this, _amount)) { revert(); } tokens[_token][_user] = safeAdd(tokens[_token][_user], _amount); } } contract InstantTrade is SafeMath, Ownable { // This is needed so we can withdraw funds from other smart contracts function() payable { } // End to end trading in a single call function instantTrade(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s, uint _amount, address _store) payable { // Fix max fee (0.4%) and always reserve it uint totalValue = safeMul(_amount, 1004) / 1000; // Paying with Ethereum or token? Deposit to the actual store if (_tokenGet == address(0)) { // Check amount of ether sent to make sure it's correct if (msg.value != totalValue) { revert(); } TokenStore(_store).deposit.value(totalValue)(); } else { // Assuming user already approved transfer, transfer first to this contract if (!Token(_tokenGet).transferFrom(msg.sender, this, totalValue)) { revert(); } // Allow now actual store to deposit if (!Token(_tokenGet).approve(_store, totalValue)) { revert(); } TokenStore(_store).depositToken(_tokenGet, totalValue); } // Trade TokenStore(_store).trade(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _user, _v, _r, _s, _amount); // Check how much did we get and how much should we send back totalValue = TokenStore(_store).balanceOf(_tokenGive, this); uint customerValue = safeMul(_amountGive, _amount) / _amountGet; // Now withdraw all the funds into this contract and then pass to the user if (_tokenGive == address(0)) { TokenStore(_store).withdraw(totalValue); msg.sender.transfer(customerValue); } else { TokenStore(_store).withdrawToken(_tokenGive, totalValue); if (!Token(_tokenGive).transfer(msg.sender, customerValue)) { revert(); } } } function withdrawFees(address _token) onlyOwner { if (_token == address(0)) { msg.sender.transfer(this.balance); } else { uint amount = Token(_token).balanceOf(this); if (!Token(_token).transfer(msg.sender, amount)) { revert(); } } } }
Throw on default handler to prevent direct transactions of Ether
function() { revert(); }
9,997,042
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { MD1Types } from '../lib/MD1Types.sol'; /** * @title MD1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract MD1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Configuration ============ /// @dev The oracle which provides Merkle root updates. IRewardsOracle internal _REWARDS_ORACLE_; /// @dev The IPNS name to which trader and market maker exchange statistics are published. string internal _IPNS_NAME_; /// @dev Period of time after the epoch end after which the new epoch exchange statistics should /// be available on IPFS via the IPNS name. This can be used as a trigger for “keepers” who are /// incentivized to call the proposeRoot() and updateRoot() functions as needed. uint256 internal _IPFS_UPDATE_PERIOD_; /// @dev Max rewards distributed per epoch as market maker incentives. uint256 internal _MARKET_MAKER_REWARDS_AMOUNT_; /// @dev Max rewards distributed per epoch as trader incentives. uint256 internal _TRADER_REWARDS_AMOUNT_; /// @dev Parameter affecting the calculation of trader rewards. This is a value /// between 0 and 1, represented here in units out of 10^18. uint256 internal _TRADER_SCORE_ALPHA_; // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. MD1Types.EpochParameters internal _EPOCH_PARAMETERS_; // ============ Root Updates ============ /// @dev The active Merkle root and associated parameters. MD1Types.MerkleRoot internal _ACTIVE_ROOT_; /// @dev The proposed Merkle root and associated parameters. MD1Types.MerkleRoot internal _PROPOSED_ROOT_; /// @dev The time at which the proposed root may become active. uint256 internal _WAITING_PERIOD_END_; /// @dev Whether root updates are currently paused. bool internal _ARE_ROOT_UPDATES_PAUSED_; // ============ Claims ============ /// @dev Mapping of (user address) => (number of tokens claimed). mapping(address => uint256) internal _CLAIMED_; /// @dev Whether the user has opted into allowing anyone to trigger a claim on their behalf. mapping(address => bool) internal _ALWAYS_ALLOW_CLAIMS_FOR_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; interface IRewardsOracle { /** * @notice Returns the oracle value, agreed upon by all oracle signers. If the signers have not * agreed upon a value, should return zero for all return values. * * @return merkleRoot The Merkle root for the next Merkle distributor update. * @return epoch The epoch number corresponding to the new Merkle root. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function read() external virtual view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library MD1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev The parameters related to a certain version of the Merkle root. */ struct MerkleRoot { bytes32 merkleRoot; uint256 epoch; bytes ipfsCid; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1Getters * @author dYdX * * @notice Simple getter functions. */ abstract contract MD1Getters is MD1Storage { /** * @notice Get the address of the oracle which provides Merkle root updates. * * @return The address of the oracle. */ function getRewardsOracle() external view returns (IRewardsOracle) { return _REWARDS_ORACLE_; } /** * @notice Get the IPNS name to which trader and market maker exchange statistics are published. * * @return The IPNS name. */ function getIpnsName() external view returns (string memory) { return _IPNS_NAME_; } /** * @notice Get the period of time after the epoch end after which the new epoch exchange * statistics should be available on IPFS via the IPNS name. * * @return The IPFS update period, in seconds. */ function getIpfsUpdatePeriod() external view returns (uint256) { return _IPFS_UPDATE_PERIOD_; } /** * @notice Get the rewards formula parameters. * * @return Max rewards distributed per epoch as market maker incentives. * @return Max rewards distributed per epoch as trader incentives. * @return The alpha parameter between 0 and 1, in units out of 10^18. */ function getRewardsParameters() external view returns (uint256, uint256, uint256) { return ( _MARKET_MAKER_REWARDS_AMOUNT_, _TRADER_REWARDS_AMOUNT_, _TRADER_SCORE_ALPHA_ ); } /** * @notice Get the parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (MD1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice Get the active Merkle root and associated parameters. * * @return merkleRoot The active Merkle root. * @return epoch The epoch number corresponding to this Merkle tree. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function getActiveRoot() external view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid) { merkleRoot = _ACTIVE_ROOT_.merkleRoot; epoch = _ACTIVE_ROOT_.epoch; ipfsCid = _ACTIVE_ROOT_.ipfsCid; } /** * @notice Get the proposed Merkle root and associated parameters. * * @return merkleRoot The active Merkle root. * @return epoch The epoch number corresponding to this Merkle tree. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function getProposedRoot() external view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid) { merkleRoot = _PROPOSED_ROOT_.merkleRoot; epoch = _PROPOSED_ROOT_.epoch; ipfsCid = _PROPOSED_ROOT_.ipfsCid; } /** * @notice Get the time at which the proposed root may become active. * * @return The time at which the proposed root may become active, in epoch seconds. */ function getWaitingPeriodEnd() external view returns (uint256) { return _WAITING_PERIOD_END_; } /** * @notice Check whether root updates are currently paused. * * @return Boolean `true` if root updates are currently paused, otherwise, `false`. */ function getAreRootUpdatesPaused() external view returns (bool) { return _ARE_ROOT_UPDATES_PAUSED_; } /** * @notice Get the tokens claimed so far by a given user. * * @param user The address of the user. * * @return The tokens claimed so far by that user. */ function getClaimed(address user) external view returns (uint256) { return _CLAIMED_[user]; } /** * @notice Check whether the user opted into allowing anyone to trigger a claim on their behalf. * * @param user The address of the user. * * @return Boolean `true` if any address may trigger claims for the user, otherwise `false`. */ function getAlwaysAllowClaimsFor(address user) external view returns (bool) { return _ALWAYS_ALLOW_CLAIMS_FOR_[user]; } } // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../dependencies/open-zeppelin/SafeMath.sol'; import { Ownable } from '../../dependencies/open-zeppelin/Ownable.sol'; import { MerkleProof } from '../../dependencies/open-zeppelin/MerkleProof.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { IRewardsOracle } from '../../interfaces/IRewardsOracle.sol'; import { MD1Claims } from './impl/MD1Claims.sol'; import { MD1RootUpdates } from './impl/MD1RootUpdates.sol'; import { MD1Configuration } from './impl/MD1Configuration.sol'; import { MD1Getters } from './impl/MD1Getters.sol'; /** * @title MerkleDistributorV1 * @author dYdX * * @notice Distributes DYDX token rewards according to a Merkle tree of balances. The tree can be * updated periodially with each user's cumulative rewards balance, allowing new rewards to be * distributed to users over time. * * An update is performed by setting the proposed Merkle root to the latest value returned by * the oracle contract. The proposed Merkle root can be made active after a waiting period has * elapsed. During the waiting period, dYdX governance has the opportunity to freeze the Merkle * root, in case the proposed root is incorrect or malicious. */ contract MerkleDistributorV1 is MD1RootUpdates, MD1Claims, MD1Configuration, MD1Getters { // ============ Constructor ============ constructor( address rewardsToken, address rewardsTreasury ) MD1Claims(rewardsToken, rewardsTreasury) {} // ============ External Functions ============ function initialize( address rewardsOracle, string calldata ipnsName, uint256 ipfsUpdatePeriod, uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha, uint256 epochInterval, uint256 epochOffset ) external initializer { __MD1Roles_init(); __MD1Configuration_init( rewardsOracle, ipnsName, ipfsUpdatePeriod, marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); __MD1EpochSchedule_init(epochInterval, epochOffset); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. Used by VersionedInitializable. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MerkleProof } from '../../../dependencies/open-zeppelin/MerkleProof.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Roles } from './MD1Roles.sol'; /** * @title MD1Claims * @author dYdX * * @notice Allows rewards to be claimed by providing a Merkle proof of the rewards amount. */ abstract contract MD1Claims is MD1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The token distributed as rewards. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; // ============ Events ============ /// @notice Emitted when a user claims rewards. event RewardsClaimed( address account, uint256 amount ); /// @notice Emitted when a user opts into or out of the claim-for allowlist. event AlwaysAllowClaimForUpdated( address user, bool allow ); // ============ Constructor ============ constructor( address rewardsToken, address rewardsTreasury ) { REWARDS_TOKEN = IERC20(rewardsToken); REWARDS_TREASURY = rewardsTreasury; } // ============ External Functions ============ /** * @notice Claim the remaining unclaimed rewards for the sender. * * Reverts if the provided Merkle proof is invalid. * * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function claimRewards( uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external nonReentrant returns (uint256) { return _claimRewards(msg.sender, cumulativeAmount, merkleProof); } /** * @notice Claim the remaining unclaimed rewards for a user, and send them to that user. * * The caller must be authorized with CLAIM_OPERATOR_ROLE unless the specified user has opted * into the claim-for allowlist. In any case, rewards are transfered to the original user * specified in the Merkle tree. * * Reverts if the provided Merkle proof is invalid. * * @param user Address of the user on whose behalf to trigger a claim. * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address user, uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external nonReentrant returns (uint256) { require( ( hasRole(CLAIM_OPERATOR_ROLE, msg.sender) || _ALWAYS_ALLOW_CLAIMS_FOR_[user] ), 'MD1Claims: Do not have permission to claim for this user' ); return _claimRewards(user, cumulativeAmount, merkleProof); } /** * @notice Opt into allowing anyone to claim on the sender's behalf. * * Note that this does not affect who receives the funds. The user specified in the Merkle tree * receives those rewards regardless of who issues the claim. * * Note that addresses with the CLAIM_OPERATOR_ROLE ignore this allowlist when triggering claims. * * @param allow Whether or not to allow claims on the sender's behalf. */ function setAlwaysAllowClaimsFor( bool allow ) external nonReentrant { _ALWAYS_ALLOW_CLAIMS_FOR_[msg.sender] = allow; emit AlwaysAllowClaimForUpdated(msg.sender, allow); } // ============ Internal Functions ============ /** * @notice Claim the remaining unclaimed rewards for a user, and send them to that user. * * Reverts if the provided Merkle proof is invalid. * * @param user Address of the user. * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, uint256 cumulativeAmount, bytes32[] calldata merkleProof ) internal returns (uint256) { // Get the active Merkle root. bytes32 merkleRoot = _ACTIVE_ROOT_.merkleRoot; // Verify the Merkle proof. bytes32 node = keccak256(abi.encodePacked(user, cumulativeAmount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MD1Claims: Invalid Merkle proof'); // Get the claimable amount. // // Note: If this reverts, then there was an error in the Merkle tree, since the cumulative // amount for a given user should never decrease over time. uint256 claimable = cumulativeAmount.sub(_CLAIMED_[user]); if (claimable == 0) { return 0; } // Mark the user as having claimed the full amount. _CLAIMED_[user] = cumulativeAmount; // Send the user the claimable amount. REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, user, claimable); emit RewardsClaimed(user, claimable); return claimable; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MerkleProof } from '../../../dependencies/open-zeppelin/MerkleProof.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Pausable } from './MD1Pausable.sol'; /** * @title MD1RootUpdates * @author dYdX * * @notice Handles updates to the Merkle root. */ abstract contract MD1RootUpdates is MD1Pausable { using SafeMath for uint256; // ============ Constants ============ /// @notice The waiting period before a proposed Merkle root can become active, in seconds. uint256 public constant WAITING_PERIOD = 7 days; // ============ Events ============ /// @notice Emitted when a new Merkle root is proposed and the waiting period begins. event RootProposed( bytes32 merkleRoot, uint256 epoch, bytes ipfsCid, uint256 waitingPeriodEnd ); /// @notice Emitted when a new Merkle root becomes active. event RootUpdated( bytes32 merkleRoot, uint256 epoch, bytes ipfsCid ); // ============ External Functions ============ /** * @notice Set the proposed root parameters to the values returned by the oracle, and start the * waiting period. Anyone may call this function. * * Reverts if the oracle root is bytes32(0). * Reverts if the oracle root parameters are equal to the proposed root parameters. * Reverts if the oracle root epoch is not equal to the next root epoch. */ function proposeRoot() external nonReentrant { // Read the latest values from the oracle. ( bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid ) = _REWARDS_ORACLE_.read(); require(merkleRoot != bytes32(0), 'MD1RootUpdates: Oracle root is zero (unset)'); require( ( merkleRoot != _PROPOSED_ROOT_.merkleRoot || epoch != _PROPOSED_ROOT_.epoch || keccak256(ipfsCid) != keccak256(_PROPOSED_ROOT_.ipfsCid) ), 'MD1RootUpdates: Oracle root was already proposed' ); require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Oracle epoch is not next root epoch'); // Set the proposed root and the waiting period for the proposed root to become active. _PROPOSED_ROOT_ = MD1Types.MerkleRoot({ merkleRoot: merkleRoot, epoch: epoch, ipfsCid: ipfsCid }); uint256 waitingPeriodEnd = block.timestamp.add(WAITING_PERIOD); _WAITING_PERIOD_END_ = waitingPeriodEnd; emit RootProposed(merkleRoot, epoch, ipfsCid, waitingPeriodEnd); } /** * @notice Set the active root parameters to the proposed root parameters. * * Reverts if root updates are paused. * Reverts if the proposed root is bytes32(0). * Reverts if the proposed root epoch is not equal to the next root epoch. * Reverts if the waiting period for the proposed root has not elapsed. */ function updateRoot() external nonReentrant whenNotPaused { // Get the proposed root parameters. bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot; uint256 epoch = _PROPOSED_ROOT_.epoch; bytes memory ipfsCid = _PROPOSED_ROOT_.ipfsCid; require(merkleRoot != bytes32(0), 'MD1RootUpdates: Proposed root is zero (unset)'); require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Proposed epoch is not next root epoch'); require( block.timestamp >= _WAITING_PERIOD_END_, 'MD1RootUpdates: Waiting period has not elapsed' ); // Set the active root. _ACTIVE_ROOT_.merkleRoot = merkleRoot; _ACTIVE_ROOT_.epoch = epoch; _ACTIVE_ROOT_.ipfsCid = ipfsCid; emit RootUpdated(merkleRoot, epoch, ipfsCid); } /** * @notice Returns true if there is a proposed root waiting to become active, the waiting period * for that root has elapsed, and root updates are not paused. * * @return Boolean `true` if the active root can be updated to the proposed root, else `false`. */ function canUpdateRoot() external view returns (bool) { return ( hasPendingRoot() && block.timestamp >= _WAITING_PERIOD_END_ && !_ARE_ROOT_UPDATES_PAUSED_ ); } // ============ Public Functions ============ /** * @notice Returns true if there is a proposed root waiting to become active. This is the case if * and only if the proposed root is not zero and the proposed root epoch is equal to the next * root epoch. */ function hasPendingRoot() public view returns (bool) { // Get the proposed parameters. bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot; uint256 epoch = _PROPOSED_ROOT_.epoch; if (merkleRoot == bytes32(0)) { return false; } return epoch == getNextRootEpoch(); } /** * @notice Get the next root epoch. If the active root is zero, then the next root epoch is zero, * otherwise, it is equal to the active root epoch plus one. */ function getNextRootEpoch() public view returns (uint256) { bytes32 merkleRoot = _ACTIVE_ROOT_.merkleRoot; if (merkleRoot == bytes32(0)) { return 0; } return _ACTIVE_ROOT_.epoch.add(1); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { MD1EpochSchedule } from './MD1EpochSchedule.sol'; import { MD1Roles } from './MD1Roles.sol'; import { MD1Types } from '../lib/MD1Types.sol'; /** * @title MD1Configuration * @author dYdX * * @notice Functions for modifying the Merkle distributor rewards configuration. * * The more sensitive configuration values, which potentially give full control over the contents * of the Merkle tree, may only be updated by the OWNER_ROLE. Other values may be configured by * the CONFIG_UPDATER_ROLE. * * Note that these configuration values are made available externally but are not used internally * within this contract, with the exception of the IPFS update period which is used by * the getIpfsEpoch() function. */ abstract contract MD1Configuration is MD1EpochSchedule, MD1Roles { // ============ Constants ============ uint256 public constant TRADER_SCORE_ALPHA_BASE = 10 ** 18; // ============ Events ============ event RewardsOracleChanged( address rewardsOracle ); event IpnsNameUpdated( string ipnsName ); event IpfsUpdatePeriodUpdated( uint256 ipfsUpdatePeriod ); event RewardsParametersUpdated( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ); // ============ Initializer ============ function __MD1Configuration_init( address rewardsOracle, string calldata ipnsName, uint256 ipfsUpdatePeriod, uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) internal { _setRewardsOracle(rewardsOracle); _setIpnsName(ipnsName); _setIpfsUpdatePeriod(ipfsUpdatePeriod); _setRewardsParameters( marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); } // ============ External Functions ============ /** * @notice Set the address of the oracle which provides Merkle root updates. * * @param rewardsOracle The new oracle address. */ function setRewardsOracle( address rewardsOracle ) external onlyRole(OWNER_ROLE) nonReentrant { _setRewardsOracle(rewardsOracle); } /** * @notice Set the IPNS name to which trader and market maker exchange statistics are published. * * @param ipnsName The new IPNS name. */ function setIpnsName( string calldata ipnsName ) external onlyRole(OWNER_ROLE) nonReentrant { _setIpnsName(ipnsName); } /** * @notice Set the period of time after the epoch end after which the new epoch exchange * statistics should be available on IPFS via the IPNS name. * * This can be used as a trigger for “keepers” who are incentivized to call the proposeRoot() * and updateRoot() functions as needed. * * @param ipfsUpdatePeriod The new IPFS update period, in seconds. */ function setIpfsUpdatePeriod( uint256 ipfsUpdatePeriod ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setIpfsUpdatePeriod(ipfsUpdatePeriod); } /** * @notice Set the rewards formula parameters. * * @param marketMakerRewardsAmount Max rewards distributed per epoch as market maker incentives. * @param traderRewardsAmount Max rewards distributed per epoch as trader incentives. * @param traderScoreAlpha The alpha parameter between 0 and 1, in units out of 10^18. */ function setRewardsParameters( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setRewardsParameters(marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha); } /** * @notice Set the parameters defining the function from timestamp to epoch number. * * @param interval The length of an epoch, in seconds. * @param offset The start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setEpochParameters(interval, offset); } // ============ Internal Functions ============ function _setRewardsOracle( address rewardsOracle ) internal { _REWARDS_ORACLE_ = IRewardsOracle(rewardsOracle); emit RewardsOracleChanged(rewardsOracle); } function _setIpnsName( string calldata ipnsName ) internal { _IPNS_NAME_ = ipnsName; emit IpnsNameUpdated(ipnsName); } function _setIpfsUpdatePeriod( uint256 ipfsUpdatePeriod ) internal { _IPFS_UPDATE_PERIOD_ = ipfsUpdatePeriod; emit IpfsUpdatePeriodUpdated(ipfsUpdatePeriod); } function _setRewardsParameters( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) internal { require( traderScoreAlpha <= TRADER_SCORE_ALPHA_BASE, 'MD1Configuration: Invalid traderScoreAlpha' ); _MARKET_MAKER_REWARDS_AMOUNT_ = marketMakerRewardsAmount; _TRADER_REWARDS_AMOUNT_ = traderRewardsAmount; _TRADER_SCORE_ALPHA_ = traderScoreAlpha; emit RewardsParametersUpdated( marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1Roles * @author dYdX * * @notice Defines roles used in the MerkleDistributorV1 contract. The hierarchy of roles and * powers of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the below roles it manages. * | -> May update the rewards oracle address. * | -> May update the IPNS name. * | * +-- CONFIG_UPDATER_ROLE * | -> May update parameters affecting the formulae used to calculate rewards. * | -> May update the epoch schedule. * | -> May update the IPFS update period. * | * +-- PAUSER_ROLE * | -> May pause updates to the Merkle root. * | * +-- UNPAUSER_ROLE * | -> May unpause updates to the Merkle root. * | * +-- CLAIM_OPERATOR_ROLE * -> May trigger a claim on behalf of a user (but the recipient is always the user). */ abstract contract MD1Roles is MD1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant CONFIG_UPDATER_ROLE = keccak256('CONFIG_UPDATER_ROLE'); bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE'); bytes32 public constant UNPAUSER_ROLE = keccak256('UNPAUSER_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); function __MD1Roles_init() internal { // Assign the OWNER_ROLE to the sender. _setupRole(OWNER_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(CONFIG_UPDATER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(UNPAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { MD1Roles } from './MD1Roles.sol'; /** * @title MD1Pausable * @author dYdX * * @notice Allows authorized addresses to pause updates to the Merkle root. * * For the Merkle root to be updated, the root must first be set on the oracle contract, then * proposed on this contract, at which point the waiting period begins. During the waiting period, * the root should be verified, and updates should be paused by the PAUSER_ROLE if the root is * found to be incorrect. */ abstract contract MD1Pausable is MD1Roles { // ============ Events ============ /// @notice Emitted when root updates are paused. event RootUpdatesPaused(); /// @notice Emitted when root updates are unpaused. event RootUpdatesUnpaused(); // ============ Modifiers ============ /** * @dev Enforce that a function may be called only while root updates are not paused. */ modifier whenNotPaused() { require(!_ARE_ROOT_UPDATES_PAUSED_, 'MD1Pausable: Updates paused'); _; } /** * @dev Enforce that a function may be called only while root updates are paused. */ modifier whenPaused() { require(_ARE_ROOT_UPDATES_PAUSED_, 'MD1Pausable: Updates not paused'); _; } // ============ External Functions ============ /** * @dev Called by PAUSER_ROLE to prevent proposed Merkle roots from becoming active. */ function pauseRootUpdates() onlyRole(PAUSER_ROLE) whenNotPaused nonReentrant external { _ARE_ROOT_UPDATES_PAUSED_ = true; emit RootUpdatesPaused(); } /** * @dev Called by UNPAUSER_ROLE to resume allowing proposed Merkle roots to become active. */ function unpauseRootUpdates() onlyRole(UNPAUSER_ROLE) whenPaused nonReentrant external { _ARE_ROOT_UPDATES_PAUSED_ = false; emit RootUpdatesUnpaused(); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * Note that the current and IPFS epoch numbers are made available externally but are not used * internally within this contract. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) */ abstract contract MD1EpochSchedule is MD1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochScheduleUpdated( MD1Types.EpochParameters epochParameters ); // ============ Initializer ============ function __MD1EpochSchedule_init( uint256 interval, uint256 offset ) internal { _setEpochParameters(interval, offset); } // ============ External Functions ============ /** * @notice Get the epoch at the current block timestamp. * * Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() external view returns (uint256) { return _getEpochAtTimestamp( block.timestamp, 'MD1EpochSchedule: Epoch zero has not started' ); } /** * @notice Get the latest epoch number for which we expect to have data available on IPFS. * This is equal to the current epoch number, delayed by the IPFS update period. * * Reverts if epoch zero did not begin at least `_IPFS_UPDATE_PERIOD_` seconds ago. * * @return The latest epoch number for which we expect to have data available on IPFS. */ function getIpfsEpoch() external view returns (uint256) { return _getEpochAtTimestamp( block.timestamp.sub(_IPFS_UPDATE_PERIOD_), 'MD1EpochSchedule: IPFS epoch zero has not started' ); } // ============ Internal Functions ============ function _getEpochAtTimestamp( uint256 timestamp, string memory revertReason ) internal view returns (uint256) { MD1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require(timestamp >= offset, revertReason); return timestamp.sub(offset).div(interval); } function _setEpochParameters( uint256 interval, uint256 offset ) internal { require(interval != 0, 'MD1EpochSchedule: Interval cannot be zero'); MD1Types.EpochParameters memory epochParameters = MD1Types.EpochParameters({ interval: interval.toUint128(), offset: offset.toUint128() }); _EPOCH_PARAMETERS_ = epochParameters; emit EpochScheduleUpdated(epochParameters); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128(uint256 a) internal pure returns (uint128) { uint128 b = uint128(a); require(uint256(b) == a, 'SafeCast: toUint128 overflow'); return b; } }
Get the period of time after the epoch end after which the new epoch exchange statistics should be available on IPFS via the IPNS name. return The IPFS update period, in seconds./
function getIpfsUpdatePeriod() external view returns (uint256) { return _IPFS_UPDATE_PERIOD_; }
1,681,898
./full_match/11155111/0x3Be6088eE6F02F5522E6bd80bAE6533874f9D92a/sources/project_/contracts/Property.sol
set new owner reset status for the next sale
function _transferOwnership(address _to) private { grantRole(PROPERTY_OWNER_ROLE, _to); offerAccepted = false; tokenAcceptedForClosing = address(0); }
3,821,560
pragma solidity ^0.4.15; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* * Contract that is working with ERC223 tokens * This is an implementation of ContractReceiver provided here: * https://github.com/Dexaran/ERC223-token-standard/blob/Recommended/Receiver_Interface.sol */ contract ContractReceiver { function tokenFallback(address _from, uint _value, bytes _data); } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController { controller = _newController; } } /// @title SpecToken - Crowdfunding code for the Spectre.ai Token Sale /// @author Parthasarathy Ramanujam contract SpectreSubscriberToken is StandardToken, Pausable, TokenController { using SafeMath for uint; string public constant name = "SPECTRE SUBSCRIBER TOKEN"; string public constant symbol = "SXS"; uint256 public constant decimals = 18; uint256 constant public TOKENS_AVAILABLE = 240000000 * 10**decimals; uint256 constant public BONUS_SLAB = 100000000 * 10**decimals; uint256 constant public MIN_CAP = 5000000 * 10**decimals; uint256 constant public MIN_FUND_AMOUNT = 1 ether; uint256 constant public TOKEN_PRICE = 0.0005 ether; uint256 constant public WHITELIST_PERIOD = 3 days; address public specWallet; address public specDWallet; address public specUWallet; bool public refundable = false; bool public configured = false; bool public tokenAddressesSet = false; //presale start and end blocks uint256 public presaleStart; uint256 public presaleEnd; //main sale start and end blocks uint256 public saleStart; uint256 public saleEnd; //discount end block for main sale uint256 public discountSaleEnd; //whitelisting mapping(address => uint256) public whitelist; uint256 constant D160 = 0x0010000000000000000000000000000000000000000; //bonus earned mapping(address => uint256) public bonus; event Refund(address indexed _to, uint256 _value); event ContractFunded(address indexed _from, uint256 _value, uint256 _total); event Refundable(); event WhiteListSet(address indexed _subscriber, uint256 _value); event OwnerTransfer(address indexed _from, address indexed _to, uint256 _value); modifier isRefundable() { require(refundable); _; } modifier isNotRefundable() { require(!refundable); _; } modifier isTransferable() { require(tokenAddressesSet); require(getNow() > saleEnd); require(totalSupply >= MIN_CAP); _; } modifier onlyWalletOrOwner() { require(msg.sender == owner || msg.sender == specWallet); _; } //@notice function to initilaize the token contract //@notice _specWallet - The wallet that receives the proceeds from the token sale //@notice _specDWallet - Wallet that would receive tokens chosen for dividend //@notice _specUWallet - Wallet that would receive tokens chosen for utility function SpectreSubscriberToken(address _specWallet) { require(_specWallet != address(0)); specWallet = _specWallet; pause(); } //@notice Fallback function that accepts the ether and allocates tokens to //the msg.sender corresponding to msg.value function() payable whenNotPaused public { require(msg.value >= MIN_FUND_AMOUNT); if(getNow() >= presaleStart && getNow() <= presaleEnd) { purchasePresale(); } else if (getNow() >= saleStart && getNow() <= saleEnd) { purchase(); } else { revert(); } } //@notice function to be used for presale purchase function purchasePresale() internal { //Only check whitelist for the first 3 days of presale if (getNow() < (presaleStart + WHITELIST_PERIOD)) { require(whitelist[msg.sender] > 0); //Accept if the subsciber 95% to 120% of whitelisted amount uint256 minAllowed = whitelist[msg.sender].mul(95).div(100); uint256 maxAllowed = whitelist[msg.sender].mul(120).div(100); require(msg.value >= minAllowed && msg.value <= maxAllowed); //remove the address from whitelist whitelist[msg.sender] = 0; } uint256 numTokens = msg.value.mul(10**decimals).div(TOKEN_PRICE); uint256 bonusTokens = 0; if(totalSupply < BONUS_SLAB) { //Any portion of tokens less than BONUS_SLAB are eligable for 33% bonus, otherwise 22% bonus uint256 remainingBonusSlabTokens = SafeMath.sub(BONUS_SLAB, totalSupply); uint256 bonusSlabTokens = Math.min256(remainingBonusSlabTokens, numTokens); uint256 nonBonusSlabTokens = SafeMath.sub(numTokens, bonusSlabTokens); bonusTokens = bonusSlabTokens.mul(33).div(100); bonusTokens = bonusTokens.add(nonBonusSlabTokens.mul(22).div(100)); } else { //calculate 22% bonus for tokens purchased on presale bonusTokens = numTokens.mul(22).div(100); } // numTokens = numTokens.add(bonusTokens); bonus[msg.sender] = bonus[msg.sender].add(bonusTokens); //transfer money to Spectre MultisigWallet (could be msg.value) specWallet.transfer(msg.value); totalSupply = totalSupply.add(numTokens); require(totalSupply <= TOKENS_AVAILABLE); balances[msg.sender] = balances[msg.sender].add(numTokens); //fire the event notifying the transfer of tokens Transfer(0, msg.sender, numTokens); } //@notice function to be used for mainsale purchase function purchase() internal { uint256 numTokens = msg.value.mul(10**decimals).div(TOKEN_PRICE); uint256 bonusTokens = 0; if(getNow() <= discountSaleEnd) { //calculate 11% bonus for tokens purchased on discount period bonusTokens = numTokens.mul(11).div(100); } numTokens = numTokens.add(bonusTokens); bonus[msg.sender] = bonus[msg.sender].add(bonusTokens); //transfer money to Spectre MultisigWallet specWallet.transfer(msg.value); totalSupply = totalSupply.add(numTokens); require(totalSupply <= TOKENS_AVAILABLE); balances[msg.sender] = balances[msg.sender].add(numTokens); //fire the event notifying the transfer of tokens Transfer(0, msg.sender, numTokens); } //@notice Function reports the number of tokens available for sale function numberOfTokensLeft() constant returns (uint256) { return TOKENS_AVAILABLE.sub(totalSupply); } //Override unpause function to only allow once configured function unpause() onlyOwner whenPaused public { require(configured); paused = false; Unpause(); } //@notice Function to configure contract addresses //@param `_specUWallet` - address of Utility contract //@param `_specDWallet` - address of Dividend contract function setTokenAddresses(address _specUWallet, address _specDWallet) onlyOwner public { require(!tokenAddressesSet); require(_specDWallet != address(0)); require(_specUWallet != address(0)); require(isContract(_specDWallet)); require(isContract(_specUWallet)); specUWallet = _specUWallet; specDWallet = _specDWallet; tokenAddressesSet = true; if (configured) { unpause(); } } //@notice Function to configure contract parameters //@param `_startPresaleBlock` - block from when presale begins. //@param `_endPresaleBlock` - block from when presale ends. //@param `_saleStart` - block from when main sale begins. //@param `_saleEnd` - block from when main sale ends. //@param `_discountEnd` - block from when the discounts would end. //@notice Can be called only when funding is not active and only by the owner function configure(uint256 _presaleStart, uint256 _presaleEnd, uint256 _saleStart, uint256 _saleEnd, uint256 _discountSaleEnd) onlyOwner public { require(!configured); require(_presaleStart > getNow()); require(_presaleEnd > _presaleStart); require(_saleStart > _presaleEnd); require(_saleEnd > _saleStart); require(_discountSaleEnd > _saleStart && _discountSaleEnd <= _saleEnd); presaleStart = _presaleStart; presaleEnd = _presaleEnd; saleStart = _saleStart; saleEnd = _saleEnd; discountSaleEnd = _discountSaleEnd; configured = true; if (tokenAddressesSet) { unpause(); } } //@notice Function that can be called by purchasers to refund //@notice Used only in case the ICO isn't successful. function refund() isRefundable public { require(balances[msg.sender] > 0); uint256 tokenValue = balances[msg.sender].sub(bonus[msg.sender]); balances[msg.sender] = 0; tokenValue = tokenValue.mul(TOKEN_PRICE).div(10**decimals); //transfer to the requesters wallet msg.sender.transfer(tokenValue); Refund(msg.sender, tokenValue); } function withdrawEther() public isNotRefundable onlyOwner { //In case ether is sent, even though not refundable msg.sender.transfer(this.balance); } //@notice Function used for funding in case of refund. //@notice Can be called only by the Owner or Wallet function fundContract() public payable onlyWalletOrOwner { //does nothing just accepts and stores the ether ContractFunded(msg.sender, msg.value, this.balance); } function setRefundable() onlyOwner { require(this.balance > 0); require(getNow() > saleEnd); require(totalSupply < MIN_CAP); Refundable(); refundable = true; } //@notice Standard function transfer similar to ERC20 transfer with no _data . //@notice Added due to backwards compatibility reasons . function transfer(address _to, uint256 _value) isTransferable returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons require(_to == specDWallet || _to == specUWallet); require(isContract(_to)); bytes memory empty; return transferToContract(msg.sender, _to, _value, empty); } //@notice assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) { uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } //@notice function that is called when transaction target is a contract function transferToContract(address _from, address _to, uint256 _value, bytes _data) internal returns (bool success) { require(balanceOf(_from) >= _value); balances[_from] = balanceOf(_from).sub(_value); balances[_to] = balanceOf(_to).add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(_from, _value, _data); Transfer(_from, _to, _value); return true; } /** * @dev Transfer tokens from one address to another - needed for owner transfers * @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 isTransferable returns (bool) { require(_to == specDWallet || _to == specUWallet); require(isContract(_to)); //owner can transfer tokens on behalf of users after 28 days if (msg.sender == owner && getNow() > saleEnd + 28 days) { OwnerTransfer(_from, _to, _value); } else { uint256 _allowance = allowed[_from][msg.sender]; allowed[_from][msg.sender] = _allowance.sub(_value); } //Now make the transfer bytes memory empty; return transferToContract(_from, _to, _value, empty); } //@notice function that is used for whitelisting an address function setWhiteList(address _subscriber, uint256 _amount) public onlyOwner { require(_subscriber != address(0)); require(_amount != 0); whitelist[_subscriber] = _amount; WhiteListSet(_subscriber, _amount); } // data is an array of uint256s. Each uint256 represents a address and amount. // The 160 LSB is the address that wants to be added // The 96 MSB is the amount of to be set for the whitelist for that address function multiSetWhiteList(uint256[] data) public onlyOwner { for (uint256 i = 0; i < data.length; i++) { address addr = address(data[i] & (D160 - 1)); uint256 amount = data[i] / D160; setWhiteList(addr, amount); } } ///////////////// // TokenController interface ///////////////// /// @notice `proxyPayment()` returns false, meaning ether is not accepted at /// the token address, only the address of FiinuCrowdSale /// @param _owner The address that will hold the newly created tokens function proxyPayment(address _owner) payable returns(bool) { return false; } /// @notice Notifies the controller about a transfer, for this Campaign all /// transfers are allowed by default and no extra notifications are needed /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool) { return true; } /// @notice Notifies the controller about an approval, for this Campaign all /// approvals are allowed by default and no extra notifications are needed /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool) { return true; } function getNow() constant internal returns (uint256) { return now; } }
Function that can be called by purchasers to refund Used only in case the ICO isn't successful.transfer to the requesters wallet
function refund() isRefundable public { require(balances[msg.sender] > 0); uint256 tokenValue = balances[msg.sender].sub(bonus[msg.sender]); balances[msg.sender] = 0; tokenValue = tokenValue.mul(TOKEN_PRICE).div(10**decimals); msg.sender.transfer(tokenValue); Refund(msg.sender, tokenValue); }
6,478,097
./partial_match/1/0x20DCe75255b077a1A93d5a74e1588a355517E265/sources/SD.sol
Notifies the controller about an approval, for this Campaign all approvals are allowed by default and no extra notifications are needed _owner The address that calls `approve()` _spender The spender in the `approve()` call _amount The amount in the `approve()` call return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public returns(bool) { return true; }
15,640,015
./partial_match/1/0x7b394334b1ba26fD8432D9E3a33Ddf0cb3357d9F/sources/contracts/utils/SpigotLib.sol
see Spigot.claimOwnerTokens /
function claimOwnerTokens(SpigotState storage self, address token) external returns (uint256 claimed) { if (msg.sender != self.owner) { revert CallerAccessDenied(); } claimed = self.ownerTokens[token]; if (claimed == 0) { revert ClaimFailed(); } LineLib.sendOutTokenOrETH(token, self.owner, claimed); emit ClaimOwnerTokens(token, claimed, self.owner); return claimed; }
9,361,118
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract IERC20 { function balanceOf(address _to) public constant returns (uint256); function transfer(address to, uint256 value) public; function transferFrom(address from, address to, uint256 value) public; function approve(address spender, uint256 value) public; function allowance(address owner, address spender) public constant returns(uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is IERC20{ using SafeMath for uint256; // Balances for each account mapping (address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping (address => mapping(address => uint256)) allowed; // What is the balance of a particular account? // @param who The address of the particular account // @return the balanace the particular account function balanceOf(address _to) public constant returns (uint256) { return balances[_to]; } // @notice send `value` token to `to` from `msg.sender` // @param to The address of the recipient // @param value The amount of token to be transferred // @return the transaction address and send the event as Transfer function transfer(address to, uint256 value) public { require ( balances[msg.sender] >= value && value > 0 ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); } // @notice send `value` token to `to` from `from` // @param from The address of the sender // @param to The address of the recipient // @param value The amount of token to be transferred // @return the transaction address and send the event as Transfer function transferFrom(address from, address to, uint256 value) public { require ( allowed[from][msg.sender] >= value && balances[from] >= value && value > 0 ); 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); } // Allow spender to withdraw from your account, multiple times, up to the value amount. // If this function is called again it overwrites the current allowance with value. // @param spender The address of the sender // @param value The amount to be approved // @return the transaction address and send the event as Approval function approve(address spender, uint256 value) public { require ( balances[msg.sender] >= value && value > 0 ); allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); } // Check the allowed value for the spender to withdraw from owner // @param owner The address of the owner // @param spender The address of the spender // @return the amount which spender is still allowed to withdraw from owner function allowance(address _owner, address spender) public constant returns (uint256) { return allowed[_owner][spender]; } } contract TLC is StandardToken { using SafeMath for uint256; string public constant name = "Toplancer"; string public constant symbol = "TLC"; uint256 public constant decimals = 18; uint256 public constant totalSupply = 400000000e18; } contract TLCMarketCrowdsale is TLC { uint256 public minContribAmount = 0.1 ether; // 0.1 ether uint256 public presaleCap = 20000000e18; // 5% uint256 public soldTokenInPresale; uint256 public publicSaleCap = 320000000e18; // 80% uint256 public soldTokenInPublicsale; uint256 public distributionSupply = 60000000e18; // 15% uint256 public softCap = 5000 ether; uint256 public hardCap = 60000 ether; // amount of raised money in wei uint256 public weiRaised = 0; // Wallet Address of Token address public multisig; // Owner of Token address public owner; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // how many token units a buyer gets per wei uint256 public rate = 3500 ; // 1 ether = 3500 TLC // How much ETH each address has invested to this publicsale mapping (address => uint256) public investedAmountOf; // How many distinct addresses have invested uint256 public investorCount; // fund raised during public sale uint256 public fundRaisedDuringPublicSale = 0; // How much wei we have returned back to the contract after a failed crowdfund. uint256 public loadedRefund = 0; // How much wei we have given back to investors. uint256 public weiRefunded = 0; enum Stage {PRESALE, PUBLICSALE, SUCCESS, FAILURE, REFUNDING, CLOSED} Stage public stage; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // Refund was processed for a contributor event Refund(address investor, uint256 weiAmount); function TLCMarketCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet) { require( _endTime >= _startTime && _wallet != 0x0); startTime = _startTime; endTime = _endTime; multisig = _wallet; owner=msg.sender; balances[multisig] = totalSupply; stage = Stage.PRESALE; } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); weiRaised = weiRaised.add(weiAmount); uint256 timebasedBonus = tokens.mul(getTimebasedBonusRate()).div(100); tokens = tokens.add(timebasedBonus); forwardFunds(); if (stage == Stage.PRESALE) { assert (soldTokenInPresale + tokens <= presaleCap); soldTokenInPresale = soldTokenInPresale.add(tokens); } else { assert (soldTokenInPublicsale + tokens <= publicSaleCap); if(investedAmountOf[beneficiary] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[beneficiary] = investedAmountOf[beneficiary].add(weiAmount); fundRaisedDuringPublicSale = fundRaisedDuringPublicSale.add(weiAmount); soldTokenInPublicsale = soldTokenInPublicsale.add(tokens); } balances[multisig] = balances[multisig].sub(tokens); balances[beneficiary] = balances[beneficiary].add(tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { multisig.transfer(msg.value); } // Payable method // @notice Anyone can buy the tokens on tokensale by paying ether function () public payable { buyTokens(msg.sender); } // modifier to allow only owner has full control on the function modifier onlyOwner { require(msg.sender == owner); _; } modifier isRefunding { require (stage == Stage.REFUNDING); _; } modifier isFailure { require (stage == Stage.FAILURE); _; } // @return true if crowdsale current lot event has ended function hasEnded() public constant returns (bool) { return getNow() > endTime; } // @return current time function getNow() public constant returns (uint256) { return (now * 1000); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = getNow() >= startTime && getNow() <= endTime; bool nonZeroPurchase = msg.value != 0; bool minContribution = minContribAmount <= msg.value; return withinPeriod && nonZeroPurchase && minContribution; } // Get the time-based bonus rate function getTimebasedBonusRate() internal constant returns (uint256) { uint256 bonusRate = 0; if (stage == Stage.PRESALE) { bonusRate = 50; } else { uint256 nowTime = getNow(); uint256 bonusFirstWeek = startTime + (7 days * 1000); uint256 bonusSecondWeek = bonusFirstWeek + (7 days * 1000); uint256 bonusThirdWeek = bonusSecondWeek + (7 days * 1000); uint256 bonusFourthWeek = bonusThirdWeek + (7 days * 1000); if (nowTime <= bonusFirstWeek) { bonusRate = 25; } else if (nowTime <= bonusSecondWeek) { bonusRate = 20; } else if (nowTime <= bonusThirdWeek) { bonusRate = 10; } else if (nowTime <= bonusFourthWeek) { bonusRate = 5; } } return bonusRate; } // Start public sale function startPublicsale(uint256 _startTime, uint256 _endTime, uint256 _tokenPrice) public onlyOwner { require(hasEnded() && stage == Stage.PRESALE && _endTime >= _startTime && _tokenPrice > 0); stage = Stage.PUBLICSALE; startTime = _startTime; endTime = _endTime; rate = _tokenPrice; } // @return true if the crowdsale has raised enough money to be successful. function isMaximumGoalReached() public constant returns (bool reached) { return weiRaised >= hardCap; } // Validate and update the crowdsale stage function updateICOStatus() public onlyOwner { require(hasEnded() && stage == Stage.PUBLICSALE); if (hasEnded() && weiRaised >= softCap) { stage = Stage.SUCCESS; } else if (hasEnded()) { stage = Stage.FAILURE; } } // Allow load refunds back on the contract for the refunding. The team can transfer the funds back on the smart contract in the case the minimum goal was not reached. function loadRefund() public payable isFailure{ require(msg.value != 0); loadedRefund = loadedRefund.add(msg.value); if (loadedRefund <= fundRaisedDuringPublicSale) { stage = Stage.REFUNDING; } } // Investors can claim refund. // Note that any refunds from indirect buyers should be handled separately, and not through this contract. function refund() public isRefunding { uint256 weiValue = investedAmountOf[msg.sender]; require (weiValue != 0); investedAmountOf[msg.sender] = 0; balances[msg.sender] = 0; weiRefunded = weiRefunded.add(weiValue); Refund(msg.sender, weiValue); msg.sender.transfer(weiValue); if (weiRefunded <= fundRaisedDuringPublicSale) { stage = Stage.CLOSED; } } // Set/change Multi-signature wallet address function changeMultiSignatureWallet (address _multisig)public onlyOwner{ multisig = _multisig; } // Change Minimum contribution function changeMinContribution(uint256 _minContribAmount)public onlyOwner { minContribAmount = _minContribAmount; } //Change Presale Publicsale end time function changeEndTime(uint256 _endTime) public onlyOwner { require(endTime > startTime); endTime = _endTime; } // Token distribution to Founder, Key Employee Allocation // _founderAndTeamCap = 10000000e18; 10% function sendFounderAndTeamToken(address to, uint256 value) public onlyOwner{ require ( to != 0x0 && value > 0 && distributionSupply >= value ); balances[multisig] = balances[multisig].sub(value); balances[to] = balances[to].add(value); distributionSupply = distributionSupply.sub(value); Transfer(multisig, to, value); } }
Get the time-based bonus rate
function getTimebasedBonusRate() internal constant returns (uint256) { uint256 bonusRate = 0; if (stage == Stage.PRESALE) { bonusRate = 50; uint256 nowTime = getNow(); uint256 bonusFirstWeek = startTime + (7 days * 1000); uint256 bonusSecondWeek = bonusFirstWeek + (7 days * 1000); uint256 bonusThirdWeek = bonusSecondWeek + (7 days * 1000); uint256 bonusFourthWeek = bonusThirdWeek + (7 days * 1000); if (nowTime <= bonusFirstWeek) { bonusRate = 25; bonusRate = 20; bonusRate = 10; bonusRate = 5; } } return bonusRate; }
14,051,218
pragma solidity ^0.4.25; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./FlightSuretyData.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract FlightSuretyData private flightSuretyData; /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor ( address dataContract ) public { contractOwner = msg.sender; require(dataContract != address(0), 'dataContract is empty'); flightSuretyData = FlightSuretyData(dataContract); fundFeePerAirline = flightSuretyData.FUND_FEE_AIRLINE(); require(fundFeePerAirline >= (1 ether), 'please increase the airline fund'); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // region modifier // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(isOperational(), "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "registered airline" account to be the function caller */ modifier requireRegisteredAirline() { require(flightSuretyData.isRegisteredAirline(msg.sender), "Caller is not registered airline"); _; } /** * @dev Modifier that requires the "registered and funded airline" account to be the function caller */ modifier requireFundedAirline() { require(flightSuretyData.isFundedAirline(msg.sender), "Caller airline is not registered or not funded"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { bool dataContractIsOperational = flightSuretyData.isOperational(); return dataContractIsOperational; // Modify to call data contract's status } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ // endregion // region AIRLINE MANAGEMENT /***************************************************************** * the following variales are airline related ****************************************************************/ uint8 public constant MP_AIRLINE_COUNT = 4; // the 5th airline need to be approved by 50+ existing airline uint8 public constant MP_AIRLINE_APPROVE_PERCENT = 50; // need 50% of the existing airlines to approve // 0: unknown, 1: agree, 2: disagree, (others we don't care for now.) uint8 public constant MP_AIRLINE_APPROVE_CODE_AGREE = 1; uint256 public fundFeePerAirline; // Fee to be paid to make one airline effective/funded // struct to store the multi-party consensus request info struct ApproveResponse { address stakeholder; // the airline who send the approval response uint8 code; // the code that the approval airline send out } struct AirlineRequest { bool isOpen; // the request is still valid address airline; // the airline to be approved string name; // name of the airline uint256 time; // blockhash time of the new airline request ApproveResponse[] approvalResult; // the result of the approvals, use uint8 for future reasonCode extension } AirlineRequest private airlineRequest; // the need-approval airline (to simply the case, only 1 airline is allowed to wait here) event AirlineApproveRequest(address airline, address registrant, string name); // the event to request other airlines to approve a new airline event AirlineApproveResponse(address airline, address approval, uint code); // the event to tell one airlines has approved a new airline event AirlineRegistered(address airline, address registrant, string name); // the event to tell a new airline has been registered /** * @dev Add an airline to the registration queue * */ function registerAirline ( address airline, string name ) external requireIsOperational requireFundedAirline returns(bool success, uint256 votes) { require(airline != address(0), 'bad airline address'); require(bytes(name).length > 0, 'airline name is empty'); require(!flightSuretyData.isRegisteredAirline(airline), 'the airline is already registered'); uint count = flightSuretyData.countOfAirlines(); if (count < MP_AIRLINE_COUNT) { success = flightSuretyData.registerAirline(airline, name); votes = 1; if (success) { emit AirlineRegistered(airline, msg.sender, name); } } else { require(!airlineRequest.isOpen, 'Another airline is waiting for approval, please wait'); // add it into the request list airlineRequest.isOpen = true; airlineRequest.airline = airline; airlineRequest.name = name; airlineRequest.time = now; airlineRequest.approvalResult.length = 0; // clear existing votes, if any airlineRequest.approvalResult.push(ApproveResponse({ stakeholder: msg.sender, code: MP_AIRLINE_APPROVE_CODE_AGREE })); votes = 1; success = false; // notify the other existing airlines to approve emit AirlineApproveRequest(airline, msg.sender, name); } return (success, votes); } /** * @dev Add an airline to the registration queue * * param(code): 0: unknown, 1: agree, 2: disagree, (others we don't care for now.) */ function approveAirline ( address airline, uint8 code ) external requireIsOperational requireFundedAirline returns(bool success, uint256 votes) { require(!flightSuretyData.isRegisteredAirline(airline), 'the airline is already registered'); require(airlineRequest.isOpen && (airlineRequest.airline == airline), 'the airline is not in the waiting list'); // 1. check status uint voteSameCode = 1; // the caller itself counts ApproveResponse[] storage responses = airlineRequest.approvalResult; for (uint i=0; i<responses.length; i++) { // check if the msg.sender has alread voted before require(responses[i].stakeholder != msg.sender, "Caller has already approved."); // check current response list for its status if (responses[i].code == code) { voteSameCode ++; } } success = false; votes = responses.length + 1; // 2. add the vote response of the approval airline // store the response data, as the approval history airlineRequest.approvalResult.push(ApproveResponse({ stakeholder: msg.sender, code: code })); emit AirlineApproveResponse(airline, msg.sender, code); // 3. check if we already have a consensus uint countOfAirlines = flightSuretyData.countOfAirlines(); uint percent = voteSameCode.mul(100).div(countOfAirlines); if (percent >= MP_AIRLINE_APPROVE_PERCENT) { // if the consensus is "agree", add it to the registered airline list if (code == MP_AIRLINE_APPROVE_CODE_AGREE) { success = flightSuretyData.registerAirline(airline, airlineRequest.name); if (success) { // for multi-party consensus, we use the first element first and fall back to use msg.sender if not present address registrant = airlineRequest.approvalResult[0].stakeholder; emit AirlineRegistered(airline, registrant, airlineRequest.name); } } // close the vote, as we already have a consensus airlineRequest.isOpen = false; airlineRequest.airline = address(0); airlineRequest.name = ''; airlineRequest.time = 0; airlineRequest.approvalResult.length = 0; // clear existing votes, if any } return (success, votes); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * * Can only be called from FlightSuretyApp contract */ function fundAirline ( address airline ) external payable requireIsOperational requireRegisteredAirline { require(airline != address(0), 'invalid airline'); require(msg.value >= fundFeePerAirline, 'Not paied enough to fund the airline'); flightSuretyData.fundAirline.value(msg.value)(airline); } /** * @dev Get the Information of one particular airline */ function getAirlinePendingRequest ( ) external view requireIsOperational returns(uint8 count, address airline, string name, uint256 votes, uint256 agree) { if (airlineRequest.isOpen) { votes = airlineRequest.approvalResult.length; agree = 0; for (uint i=0; i<votes; i++) { if (airlineRequest.approvalResult[i].code == MP_AIRLINE_APPROVE_CODE_AGREE) { agree ++; } } return (1, airlineRequest.airline, airlineRequest.name, votes, agree); } else { return (0, address(0), '', 0, 0); } } /** * @dev Get the Information of one particular airline */ function getAirlineInfoByIndex ( uint32 index ) external view requireIsOperational returns(address airline, string name, bool isFunded) { return flightSuretyData.getAirlineInfoByIndex(index); } /** * @dev Retrieve the count of all airline */ function countOfAirlines ( ) external view requireIsOperational returns(uint32) { return flightSuretyData.countOfAirlines(); } // endregion // region FLIGHT MANAGEMENT /***************************************************************** * the following variales are flight related ****************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; // NOTE: only 20 is interesting in this lesson uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; struct Flight { bool isOpen; address airline; string flight; uint256 flightTimestamp; // the flight timestamp, specified as the number of seconds since the Unix epoch uint8 statusCode; } mapping(bytes32 => Flight) private flights; bytes32[] private flightIdArray; /** * Utils function to caculate flight key */ function _getFlightKey ( address airline, string flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Register a future flight for insuring. * */ function registerFlight ( address airline, string flight, uint256 flightTimestamp ) external requireIsOperational requireFundedAirline { require(flightSuretyData.isRegisteredAirline(airline), 'the airline does not exist'); require(bytes(flight).length > 0, 'no flight info '); bytes32 flightId = _getFlightKey(airline, flight, flightTimestamp); require(!flights[flightId].isOpen, 'the flight already exists'); flights[flightId] = Flight({ isOpen: true, airline: airline, flight: flight, flightTimestamp: flightTimestamp, statusCode: STATUS_CODE_UNKNOWN }); flightIdArray.push(flightId); } /** * the total count of the active flight */ function getFlightCount() external view returns(uint256) { return flightIdArray.length; } /** * retrieve info of the index-th active flight */ function getFlightInfoByIndex(uint256 index) external view returns( address airline, string flight, uint256 flightTimestamp, uint8 statusCode) { require(index < flightIdArray.length, 'no more flight'); bytes32 flightId = flightIdArray[index]; Flight storage flightInfo = flights[flightId]; require(flightInfo.isOpen, 'the flight is not open to insure'); Flight storage result = flights[flightId]; return (result.airline, result.flight, result.flightTimestamp, result.statusCode); } /** * @dev Called after oracle has updated flight status * */ function _processFlightStatus ( address airline, string memory flight, uint256 timestamp, uint8 statusCode ) internal { bytes32 flightId = _getFlightKey(airline, flight, timestamp); require(flights[flightId].isOpen, 'the flight does not exists'); flights[flightId].statusCode = statusCode; // NOTE: we don't proactively refund the insuree, since the count of insuree probably be very large // and we will exhaust our gas limit to handle it } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string flight, uint256 timestamp ) external requireIsOperational { bytes32 flightId = _getFlightKey(airline, flight, timestamp); require(flights[flightId].isOpen, 'the flight does not exists'); require(flights[flightId].statusCode == STATUS_CODE_UNKNOWN, 'the flight already has a status'); uint8 index = _getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } // endregion // region Insurance MANAGEMENT uint256 public constant INSURANCE_FEE_MAX = 1 ether; // Max fee to be paid for one single insurance event PassengerBuyInsurance(address passenger, address airline, string flight, uint256 timestamp); event InsurancePaidbackCredit(address passenger, address airline, string flight, uint256 timestamp); event PassengerWithdraw(address passenger); // Generate a request for oracles to fetch flight information function buyInsurance ( address passenger, address airline, string flight, uint256 timestamp ) external payable requireIsOperational { require(passenger != address(0), 'invalid passenger'); require((msg.value > 0) && (msg.value <= INSURANCE_FEE_MAX), 'invalid payment for the flight insurance'); // validate it is a valid flight bytes32 flightId = _getFlightKey(airline, flight, timestamp); require(flights[flightId].isOpen, 'the flight does not exists'); // calculate payback money and finish buying the insurance uint256 insurancePayback = msg.value; insurancePayback = insurancePayback.mul(3).div(2); flightSuretyData.buyInsurance.value(msg.value)(passenger, airline, flight, timestamp, insurancePayback); emit PassengerBuyInsurance(passenger, airline, flight, timestamp); } // Generate a request for oracles to fetch flight information function claimInsurancePayback ( address passenger, address airline, string flight, uint256 timestamp ) external requireIsOperational { require(passenger != address(0), 'invalid passenger'); // validate it is a valid flight bytes32 flightId = _getFlightKey(airline, flight, timestamp); require(flights[flightId].isOpen, 'the flight does not exists'); // check flight status require(flights[flightId].statusCode == STATUS_CODE_LATE_AIRLINE, 'flight is not delayed, no pay back'); flightSuretyData.creditInsurees(passenger, airline, flight, timestamp); emit InsurancePaidbackCredit(passenger, airline, flight, timestamp); } /** * get the passender's current balance */ function getPassengerInsurances ( ) external view requireIsOperational returns (uint8 count, uint256 balance) { return flightSuretyData.getPassengerInsurances(msg.sender); } /** * get the passender's insurance info */ function getPassengerInsuranceByIndex ( uint8 index ) external view requireIsOperational returns ( address airline, string flight, uint256 flightTimestamp, uint256 insuranceFund, uint256 insurancePayback ) { return flightSuretyData.getPassengerInsuranceByIndex(msg.sender, index); } // passenger withdraw function passengerWithdraw ( uint256 amount ) external requireIsOperational { require(amount > 0, 'please specify the amount to withdraw'); flightSuretyData.payWithdraw(msg.sender, amount); emit PassengerWithdraw(msg.sender); } // endregion // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant ORACLE_REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant ORACLE_MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles mapping(address => bool) oracles; // Remember the oracles which has responsed } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); /** * @dev Modifier that requires the caller is a valid registered oracle */ modifier requireIsOracleRegistered() { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); _; } // Register an oracle with the contract function registerOracle ( ) external payable requireIsOperational { // Require registration fee require(msg.value >= ORACLE_REGISTRATION_FEE, 'Registration fee is required'); if (!oracles[msg.sender].isRegistered) { uint8[3] memory indexes = _generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } } function getMyIndexes ( ) view external requireIsOracleRegistered returns(uint8[3]) { return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode ) external requireIsOperational requireIsOracleRegistered { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); require(!oracleResponses[key].oracles[msg.sender], 'the oracle already responsed before'); // remember the vote result oracleResponses[key].responses[statusCode].push(msg.sender); oracleResponses[key].oracles[msg.sender] = true; // Information isn't considered verified until at least ORACLE_MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); // check the vote result if (oracleResponses[key].responses[statusCode].length >= ORACLE_MIN_RESPONSES) { // Handle flight status as appropriate _processFlightStatus(airline, flight, timestamp, statusCode); emit FlightStatusInfo(airline, flight, timestamp, statusCode); } } // Returns array of three non-duplicating integers from 0-9 function _generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = _getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = _getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = _getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function _getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
Utils function to caculate flight key/
function _getFlightKey ( address airline, string flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); }
7,318,171
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; pragma experimental ABIEncoderV2; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev 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); } } 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; } } /** * @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); } } } } /** * @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; } /** * @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; } } /** * @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); } /** * @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; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) internal _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract BillionaireDoge is ERC721URIStorage, Ownable { using Counters for Counters.Counter; using Strings for uint256; event WithdrawEth(address indexed _operator, uint256 _ethWei); event SetMaxMintingPerTime(uint8 maxMintingPerTime); event BatchMint(address indexed _whoDone, uint256 _howMany); uint256 public immutable totalSupply; uint8 public maxMintingPerTime; string private _baseTokenURI; uint public nftCost = 40*10**15; // unit is 0.001 ETH Counters.Counter private _tokenIds; constructor() ERC721("The Billionaire Doge Club", "BDC") { totalSupply = 10000; setMaxMintingPerTime(10); setBaseURI("https://cloudflare-ipfs.com/ipns/k2k4r8mbprrc636ix7mslbd8osu3ceqwwggtoi5a7qiid2f71337res0/"); } function decimals() public view virtual returns (uint8) { return 0; } receive() external virtual payable { } fallback() external virtual payable { } /* withdraw all eth from owner */ function withdrawAll() public onlyOwner { uint256 _amount = address(this).balance; payable(_msgSender()).transfer(_amount); emit WithdrawEth(_msgSender(), _amount); } modifier canMint(uint8 _number) { require(_number <= maxMintingPerTime, "exceed the max minting limit per time"); require (_tokenIds.current() + _number <= totalSupply, "exceed the max supply limit"); _; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function currentMinted() external view returns(uint) { return _tokenIds.current(); } /* rewrite tokenURI function */ function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721URIStorage: URI query for nonexistent token"); if (bytes(_tokenURIs[_tokenId]).length > 0) { return string(abi.encodePacked("ipfs://", _tokenURIs[_tokenId])); } else if (bytes(_baseTokenURI).length > 0) { return string(abi.encodePacked(_baseTokenURI, _tokenId.toString())); } else { return super.tokenURI(_tokenId); } } /* Allow the owner set how max minting per time */ function setMaxMintingPerTime(uint8 _maxMintingPerTime) public onlyOwner { maxMintingPerTime = _maxMintingPerTime; emit SetMaxMintingPerTime(maxMintingPerTime); } /* Allow the owner set the base token uri */ function setBaseURI(string memory _baseTokenURI_) public onlyOwner { _baseTokenURI = _baseTokenURI_; } /* The owner can set tokenURI if it's error */ function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner { super._setTokenURI(_tokenId, _tokenURI); } // when _howManyMEth = 1, it's 0.001 ETH function setNftCost(uint256 _howManyMEth) external onlyOwner { nftCost = _howManyMEth * 10 ** 15; } /* Mint to users address, everyone can do, minting number cannot exceed 255 */ function mint(uint8 _number) external payable canMint(_number) returns (bool) { require(msg.value >= (nftCost * _number), "Low Price"); for (uint8 i= 0; i < _number; i++) { uint256 tokenID = _tokenIds.current(); _safeMint(_msgSender(), tokenID); _tokenIds.increment(); } return true; } /* Mint to the special address, only the owner can do, minting number cannot exceed 255 */ function mintByOwner(address _addr, uint8 _number) external onlyOwner returns (bool) { require(_number <= 255, "exceed the max minting limit per time"); require (_tokenIds.current() + _number <= totalSupply, "exceed the max supply limit"); for (uint8 i= 0; i < _number; i++) { uint256 tokenID = _tokenIds.current(); _safeMint(_addr, tokenID); _tokenIds.increment(); } return true; } /* Batch Mint to different address in one time, NOTE: The max address count cannot excced 255, Only owner can do this */ function batchMintByOwner(address[] memory _addrs) external onlyOwner { uint8 _number = uint8(_addrs.length); require(_number <= 255, "exceed the max minting limit per time"); for (uint8 i = 0; i < _addrs.length; i++) { uint256 tokenID = _tokenIds.current(); _safeMint(_addrs[i], tokenID); _tokenIds.increment(); } emit BatchMint(_msgSender(), _addrs.length); } }
when _howManyMEth = 1, it's 0.001 ETH
function setNftCost(uint256 _howManyMEth) external onlyOwner { nftCost = _howManyMEth * 10 ** 15; } minting number cannot exceed 255
1,119,984
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/math/FixedPoint.sol"; import "../../lib/helpers/InputHelpers.sol"; import "../../lib/helpers/TemporarilyPausable.sol"; import "../../lib/openzeppelin/ERC20.sol"; import "./WeightedMath.sol"; import "./WeightedOracleMath.sol"; import "./WeightedPool2TokensMiscData.sol"; import "./WeightedPoolUserDataHelpers.sol"; import "../BalancerPoolToken.sol"; import "../BasePoolAuthorization.sol"; import "../oracle/PoolPriceOracle.sol"; import "../oracle/Buffer.sol"; import "../../vault/interfaces/IMinimalSwapInfoPool.sol"; import "../IPriceOracle.sol"; contract WeightedPool2Tokens is IMinimalSwapInfoPool, IPriceOracle, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable, PoolPriceOracle, WeightedMath, WeightedOracleMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; using WeightedPool2TokensMiscData for bytes32; uint256 private constant _MINIMUM_BPT = 1e6; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% // The swap fee is internally stored using 64 bits, which is enough to represent _MAX_SWAP_FEE_PERCENTAGE. bytes32 internal _miscData; uint256 private _lastInvariant; IVault private immutable _vault; bytes32 private immutable _poolId; IERC20 internal immutable _token0; IERC20 internal immutable _token1; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 private immutable _maxWeightTokenIndex; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; event OracleEnabledChanged(bool enabled); event SwapFeePercentageChanged(uint256 swapFeePercentage); modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } struct NewPoolParams { IVault vault; string name; string symbol; IERC20 token0; IERC20 token1; uint256 normalizedWeight0; uint256 normalizedWeight1; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; bool oracleEnabled; address owner; } constructor(NewPoolParams memory params) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(params.name, params.symbol) BasePoolAuthorization(params.owner) TemporarilyPausable(params.pauseWindowDuration, params.bufferPeriodDuration) { _setOracleEnabled(params.oracleEnabled); _setSwapFeePercentage(params.swapFeePercentage); bytes32 poolId = params.vault.registerPool(IVault.PoolSpecialization.TWO_TOKEN); // Pass in zero addresses for Asset Managers IERC20[] memory tokens = new IERC20[](2); tokens[0] = params.token0; tokens[1] = params.token1; params.vault.registerTokens(poolId, tokens, new address[](2)); // Set immutable state variables - these cannot be read from during construction _vault = params.vault; _poolId = poolId; _token0 = params.token0; _token1 = params.token1; _scalingFactor0 = _computeScalingFactor(params.token0); _scalingFactor1 = _computeScalingFactor(params.token1); // Ensure each normalized weight is above them minimum and find the token index of the maximum weight _require(params.normalizedWeight0 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); _require(params.normalizedWeight1 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); // Ensure that the normalized weights sum to ONE uint256 normalizedSum = params.normalizedWeight0.add(params.normalizedWeight1); _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _normalizedWeight0 = params.normalizedWeight0; _normalizedWeight1 = params.normalizedWeight1; _maxWeightTokenIndex = params.normalizedWeight0 >= params.normalizedWeight1 ? 0 : 1; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function getMiscData() external view returns ( int256 logInvariant, int256 logTotalSupply, uint256 oracleSampleCreationTimestamp, uint256 oracleIndex, bool oracleEnabled, uint256 swapFeePercentage ) { bytes32 miscData = _miscData; logInvariant = miscData.logInvariant(); logTotalSupply = miscData.logTotalSupply(); oracleSampleCreationTimestamp = miscData.oracleSampleCreationTimestamp(); oracleIndex = miscData.oracleIndex(); oracleEnabled = miscData.oracleEnabled(); swapFeePercentage = miscData.swapFeePercentage(); } function getSwapFeePercentage() public view returns (uint256) { return _miscData.swapFeePercentage(); } // Caller must be approved by the Vault's Authorizer function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.setSwapFeePercentage(swapFeePercentage); emit SwapFeePercentageChanged(swapFeePercentage); } /** * @dev Balancer Governance can always enable the Oracle, even if it was originally not enabled. This allows for * Pools that unexpectedly drive much more volume and liquidity than expected to serve as Price Oracles. * * Note that the Oracle can only be enabled - it can never be disabled. */ function enableOracle() external whenNotPaused authenticate { _setOracleEnabled(true); // Cache log invariant and supply only if the pool was initialized if (totalSupply() > 0) { _cacheInvariantAndSupply(); } } function _setOracleEnabled(bool enabled) internal { _miscData = _miscData.setOracleEnabled(enabled); emit OracleEnabledChanged(enabled); } // Caller must be approved by the Vault's Authorizer function setPaused(bool paused) external authenticate { _setPaused(paused); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256[] memory normalizedWeights = new uint256[](2); normalizedWeights[0] = _normalizedWeights(true); normalizedWeights[1] = _normalizedWeights(false); return normalizedWeights; } function _normalizedWeights(bool token0) internal view virtual returns (uint256) { return token0 ? _normalizedWeight0 : _normalizedWeight1; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) { bool tokenInIsToken0 = request.tokenIn == _token0; uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0); uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0); uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0); uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); // Update price oracle with the pre-swap balances _updateOracle( request.lastChangeBlock, tokenInIsToken0 ? balanceTokenIn : balanceTokenOut, tokenInIsToken0 ? balanceTokenOut : balanceTokenIn ); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. // This is amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage()); request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. // This is amount + fee amount, so we round up (favoring a higher fee amount). return amountIn.divUp(getSwapFeePercentage().complement()); } } function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } // Join Hook function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) whenNotPaused returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) { // All joins, including initializations, are disabled while the contract is paused. uint256 bptAmountOut; if (totalSupply() == 0) { (bptAmountOut, amountsIn) = _onInitializePool(poolId, sender, recipient, userData); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn); // There are no due protocol fee amounts during initialization dueProtocolFeeAmounts = new uint256[](2); } else { _upscaleArray(balances); // Update price oracle with the pre-join balances _updateOracle(lastChangeBlock, balances[0], balances[1]); (bptAmountOut, amountsIn, dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts); } // Update cached total supply and invariant using the results after the join that will be used for future // oracle updates. _cacheInvariantAndSupply(); } /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32, address, address, bytes memory userData ) private returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, 2); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256, uint256[] memory, uint256[] memory ) { uint256[] memory normalizedWeights = _normalizedWeights(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _mutateAmounts(balances, amountsIn, FixedPoint.add); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); if (kind == WeightedPool.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); } else if (kind == WeightedPool.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), getSwapFeePercentage() ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](2); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), getSwapFeePercentage() ); return (bptAmountOut, amountsIn); } // Exit Hook function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { _upscaleArray(balances); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut); _downscaleDownArray(dueProtocolFeeAmounts); // Update cached total supply and invariant using the results after the exit that will be used for future // oracle updates, only if the pool was not paused (to minimize code paths taken while paused). if (_isNotPaused()) { _cacheInvariantAndSupply(); } return (amountsOut, dueProtocolFeeAmounts); } /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { // Update price oracle with the pre-exit balances _updateOracle(lastChangeBlock, balances[0], balances[1]); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged and the oracle is not updated // to avoid extra calculations and reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](2); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _mutateAmounts(balances, amountsOut, FixedPoint.sub); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { WeightedPool.ExitKind kind = userData.exitKind(); if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else { // ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](2); // And then assign the result to the selected token amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), getSwapFeePercentage() ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, 2); _upscaleArray(amountsOut); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), getSwapFeePercentage() ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Oracle functions function getLargestSafeQueryWindow() external pure override returns (uint256) { return 34 hours; } function getLatest(Variable variable) external view override returns (uint256) { int256 instantValue = _getInstantValue(variable, _miscData.oracleIndex()); return _fromLowResLog(instantValue); } function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view override returns (uint256[] memory results) { results = new uint256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAverageQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; _require(query.secs != 0, Errors.ORACLE_BAD_SECS); int256 beginAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago + query.secs); int256 endAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago); results[i] = _fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs)); } } function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view override returns (int256[] memory results) { results = new int256[](queries.length); uint256 oracleIndex = _miscData.oracleIndex(); OracleAccumulatorQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; results[i] = _getPastAccumulator(query.variable, oracleIndex, query.ago); } } /** * @dev Updates the Price Oracle based on the Pool's current state (balances, BPT supply and invariant). Must be * called on *all* state-changing functions with the balances *before* the state change happens, and with * `lastChangeBlock` as the number of the block in which any of the balances last changed. */ function _updateOracle( uint256 lastChangeBlock, uint256 balanceToken0, uint256 balanceToken1 ) internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled() && block.number > lastChangeBlock) { int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice( _normalizedWeight0, balanceToken0, _normalizedWeight1, balanceToken1 ); int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice( _normalizedWeight0, balanceToken0, miscData.logTotalSupply() ); uint256 oracleCurrentIndex = miscData.oracleIndex(); uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp(); uint256 oracleUpdatedIndex = _processPriceData( oracleCurrentSampleInitialTimestamp, oracleCurrentIndex, logSpotPrice, logBPTPrice, miscData.logInvariant() ); if (oracleCurrentIndex != oracleUpdatedIndex) { // solhint-disable not-rely-on-time miscData = miscData.setOracleIndex(oracleUpdatedIndex); miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp); _miscData = miscData; } } } /** * @dev Stores the logarithm of the invariant and BPT total supply, to be later used in each oracle update. Because * it is stored in miscData, which is read in all operations (including swaps), this saves gas by not requiring to * compute or read these values when updating the oracle. * * This function must be called by all actions that update the invariant and BPT supply (joins and exits). Swaps * also alter the invariant due to collected swap fees, but this growth is considered negligible and not accounted * for. */ function _cacheInvariantAndSupply() internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled()) { miscData = miscData.setLogInvariant(WeightedOracleMath._toLowResLog(_lastInvariant)); miscData = miscData.setLogTotalSupply(WeightedOracleMath._toLowResLog(totalSupply())); _miscData = miscData; } } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](2); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private pure { toMutate[0] = mutation(toMutate[0], arguments[0]); toMutate[1] = mutation(toMutate[1], arguments[1]); } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), 2).divDown(totalSupply()); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(bool token0) internal view returns (uint256) { return token0 ? _scalingFactor0 : _scalingFactor1; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array (of two elements). This function does not return anything, but * instead *mutates* the `amounts` array. */ function _upscaleArray(uint256[] memory amounts) internal view { amounts[0] = Math.mul(amounts[0], _scalingFactor(true)); amounts[1] = Math.mul(amounts[1], _scalingFactor(false)); } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array (of two elements). This function does not return anything, * but instead *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts) internal view { amounts[0] = Math.divDown(amounts[0], _scalingFactor(true)); amounts[1] = Math.divDown(amounts[1], _scalingFactor(false)); } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array (of two elements). This function does not return anything, * but instead *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts) internal view { amounts[0] = Math.divUp(amounts[0], _scalingFactor(true)); amounts[1] = Math.divUp(amounts[1], _scalingFactor(false)); } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; import "../../vault/interfaces/IAsset.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IAsset[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.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), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_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), Errors.ERC20_MINT_TO_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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE); _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), Errors.ERC20_APPROVE_FROM_ZERO_ADDRESS); _require(spender != address(0), Errors.ERC20_APPROVE_TO_ZERO_ADDRESS); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/math/FixedPoint.sol"; import "../../lib/math/Math.sol"; import "../../lib/helpers/InputHelpers.sol"; /* solhint-disable private-vars-leading-underscore */ contract WeightedMath { using FixedPoint for uint256; // A minimum normalized weight imposes a maximum weight ratio. We need this due to limitations in the // implementation of the power function, as these ratios are often exponents. uint256 internal constant _MIN_WEIGHT = 0.01e18; // Having a minimum normalized weight imposes a limit on the maximum number of tokens; // i.e., the largest possible pool is one where all tokens have exactly the minimum weight. uint256 internal constant _MAX_WEIGHTED_TOKENS = 100; // Pool limits that arise from limitations in the fixed point power function (and the imposed 1:100 maximum weight // ratio). // Swap limits: amounts swapped may not be larger than this percentage of total balance. uint256 internal constant _MAX_IN_RATIO = 0.3e18; uint256 internal constant _MAX_OUT_RATIO = 0.3e18; // Invariant growth limit: non-proportional joins cannot cause the invariant to increase by more than this ratio. uint256 internal constant _MAX_INVARIANT_RATIO = 3e18; // Invariant shrink limit: non-proportional exits cannot cause the invariant to decrease by less than this ratio. uint256 internal constant _MIN_INVARIANT_RATIO = 0.7e18; // Invariant is used to collect protocol swap fees by comparing its value between two times. // So we can round always to the same direction. It is also used to initiate the BPT amount // and, because there is a minimum BPT, we round down the invariant. function _calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances) internal pure returns (uint256 invariant) { /********************************************************************************************** // invariant _____ // // wi = weight index i | | wi // // bi = balance index i | | bi ^ = i // // i = invariant // **********************************************************************************************/ invariant = FixedPoint.ONE; for (uint256 i = 0; i < normalizedWeights.length; i++) { invariant = invariant.mulDown(balances[i].powDown(normalizedWeights[i])); } _require(invariant > 0, Errors.ZERO_INVARIANT); } // Computes how many tokens can be taken out of a pool if `amountIn` are sent, given the // current balances and weights. function _calcOutGivenIn( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountIn ) internal pure returns (uint256) { /********************************************************************************************** // outGivenIn // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bI \ (wI / wO) \ // // aI = amountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = weightIn \ \ ( bI + aI ) / / // // wO = weightOut // **********************************************************************************************/ // Amount out, so we round down overall. // The multiplication rounds down, and the subtrahend (power) rounds up (so the base rounds up too). // Because bI / (bI + aI) <= 1, the exponent rounds down. // Cannot exceed maximum in ratio _require(amountIn <= balanceIn.mulDown(_MAX_IN_RATIO), Errors.MAX_IN_RATIO); uint256 denominator = balanceIn.add(amountIn); uint256 base = balanceIn.divUp(denominator); uint256 exponent = weightIn.divDown(weightOut); uint256 power = base.powUp(exponent); return balanceOut.mulDown(power.complement()); } // Computes how many tokens must be sent to a pool in order to take `amountOut`, given the // current balances and weights. function _calcInGivenOut( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountOut ) internal pure returns (uint256) { /********************************************************************************************** // inGivenOut // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bO \ (wO / wI) \ // // aI = amountIn aI = bI * | | -------------------------- | ^ - 1 | // // wI = weightIn \ \ ( bO - aO ) / / // // wO = weightOut // **********************************************************************************************/ // Amount in, so we round up overall. // The multiplication rounds up, and the power rounds up (so the base rounds up too). // Because b0 / (b0 - a0) >= 1, the exponent rounds up. // Cannot exceed maximum out ratio _require(amountOut <= balanceOut.mulDown(_MAX_OUT_RATIO), Errors.MAX_OUT_RATIO); uint256 base = balanceOut.divUp(balanceOut.sub(amountOut)); uint256 exponent = weightOut.divUp(weightIn); uint256 power = base.powUp(exponent); // Because the base is larger than one (and the power rounds up), the power should always be larger than one, so // the following subtraction should never revert. uint256 ratio = power.sub(FixedPoint.ONE); return balanceIn.mulUp(ratio); } function _calcBptOutGivenExactTokensIn( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { // BPT out, so we round down overall. uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length); uint256 invariantRatioWithFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]); invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(normalizedWeights[i])); } uint256 invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { uint256 amountInWithoutFee; if (balanceRatiosWithFee[i] > invariantRatioWithFees) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE)); uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount); amountInWithoutFee = nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE.sub(swapFee))); } else { amountInWithoutFee = amountsIn[i]; } uint256 balanceRatio = balances[i].add(amountInWithoutFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } if (invariantRatio >= FixedPoint.ONE) { return bptTotalSupply.mulDown(invariantRatio.sub(FixedPoint.ONE)); } else { return 0; } } function _calcTokenInGivenExactBptOut( uint256 balance, uint256 normalizedWeight, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { /****************************************************************************************** // tokenInForExactBPTOut // // a = amountIn // // b = balance / / totalBPT + bptOut \ (1 / w) \ // // bptOut = bptAmountOut a = b * | | -------------------------- | ^ - 1 | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // ******************************************************************************************/ // Token in, so we round up overall. // Calculate the factor by which the invariant will increase after minting BPTAmountOut uint256 invariantRatio = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply); _require(invariantRatio <= _MAX_INVARIANT_RATIO, Errors.MAX_OUT_BPT_FOR_TOKEN_IN); // Calculate by how much the token balance has to increase to match the invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divUp(normalizedWeight)); uint256 amountInWithoutFee = balance.mulUp(balanceRatio.sub(FixedPoint.ONE)); // We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees // accordingly. uint256 taxablePercentage = normalizedWeight.complement(); uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount); return nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } function _calcBptInGivenExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { // BPT in, so we round up overall. uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length); uint256 invariantRatioWithoutFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]); invariantRatioWithoutFees = invariantRatioWithoutFees.add( balanceRatiosWithoutFee[i].mulUp(normalizedWeights[i]) ); } uint256 invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to // 'token out'. This results in slightly larger price impact. uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } else { amountOutWithFee = amountsOut[i]; } uint256 balanceRatio = balances[i].sub(amountOutWithFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } return bptTotalSupply.mulUp(invariantRatio.complement()); } function _calcTokenOutGivenExactBptIn( uint256 balance, uint256 normalizedWeight, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { /***************************************************************************************** // exactBPTInForTokenOut // // a = amountOut // // b = balance / / totalBPT - bptIn \ (1 / w) \ // // bptIn = bptAmountIn a = b * | 1 - | -------------------------- | ^ | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // *****************************************************************************************/ // Token out, so we round down overall. The multiplication rounds down, but the power rounds up (so the base // rounds up). Because (totalBPT - bptIn) / totalBPT <= 1, the exponent rounds down. // Calculate the factor by which the invariant will decrease after burning BPTAmountIn uint256 invariantRatio = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply); _require(invariantRatio >= _MIN_INVARIANT_RATIO, Errors.MIN_BPT_IN_FOR_TOKEN_OUT); // Calculate by how much the token balance has to decrease to match invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divDown(normalizedWeight)); // Because of rounding up, balanceRatio can be greater than one. Using complement prevents reverts. uint256 amountOutWithoutFee = balance.mulDown(balanceRatio.complement()); // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result // in swap fees. uint256 taxablePercentage = normalizedWeight.complement(); // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it // to 'token out'. This results in slightly larger price impact. Fees are rounded up. uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount); return nonTaxableAmount.add(taxableAmount.mulDown(swapFee.complement())); } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 totalBPT ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = amountOut / bptIn \ // // b = balance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ totalBPT / // // bpt = totalBPT // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(totalBPT); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amountsOut[i] = balances[i].mulDown(bptRatio); } return amountsOut; } function _calcDueTokenProtocolSwapFeeAmount( uint256 balance, uint256 normalizedWeight, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) internal pure returns (uint256) { /********************************************************************************* /* protocolSwapFeePercentage * balanceToken * ( 1 - (previousInvariant / currentInvariant) ^ (1 / weightToken)) *********************************************************************************/ if (currentInvariant <= previousInvariant) { // This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool // from entering a locked state in which joins and exits revert while computing accumulated swap fees. return 0; } // We round down to prevent issues in the Pool's accounting, even if it means paying slightly less in protocol // fees to the Vault. // Fee percentage and balance multiplications round down, while the subtrahend (power) rounds up (as does the // base). Because previousInvariant / currentInvariant <= 1, the exponent rounds down. uint256 base = previousInvariant.divUp(currentInvariant); uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight); // Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this // value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than // 1 / min exponent) the Pool will pay less in protocol fees than it should. base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT); uint256 power = base.powUp(exponent); uint256 tokenAccruedFees = balance.mulDown(power.complement()); return tokenAccruedFees.mulDown(protocolSwapFeePercentage); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/math//LogExpMath.sol"; import "../../lib/math/FixedPoint.sol"; import "../../lib/math/Math.sol"; import "../../lib/helpers/InputHelpers.sol"; /* solhint-disable private-vars-leading-underscore */ contract WeightedOracleMath { using FixedPoint for uint256; int256 private constant _LOG_COMPRESSION_FACTOR = 1e14; int256 private constant _HALF_LOG_COMPRESSION_FACTOR = 0.5e14; /** * @dev Calculates the logarithm of the spot price of token B in token A. * * The return value is a 4 decimal fixed-point number: use `_fromLowResLog` to recover the original value. */ function _calcLogSpotPrice( uint256 normalizedWeightA, uint256 balanceA, uint256 normalizedWeightB, uint256 balanceB ) internal pure returns (int256) { // Max balances are 2^112 and min weights are 0.01, so the division never overflows. // The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log // space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A // result of zero is therefore only possible with zero balances, which are prevented via other means. uint256 spotPrice = balanceA.divUp(normalizedWeightA).divUp(balanceB.divUp(normalizedWeightB)); return _toLowResLog(spotPrice); } /** * @dev Calculates the price of BPT in a token. `logBptTotalSupply` should be the result of calling `_toLowResLog` * with the current BPT supply. * * The return value is a 4 decimal fixed-point number: use `_fromLowResLog` to recover the original value. */ function _calcLogBPTPrice( uint256 normalizedWeight, uint256 balance, int256 logBptTotalSupply ) internal pure returns (int256) { // BPT price = (balance / weight) / total supply // Since we already have ln(total supply) and want to compute ln(BPT price), we perform the computation in log // space directly: ln(BPT price) = ln(balance / weight) - ln(total supply) // The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log // space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A // result of zero is therefore only possible with zero balances, which are prevented via other means. int256 logBalanceOverWeight = _toLowResLog(balance.divUp(normalizedWeight)); // Because we're subtracting two values in log space, this value has a larger error (+-0.0001 instead of // +-0.00005), which results in a final larger relative error of around 0.1%. return logBalanceOverWeight - logBptTotalSupply; } /** * @dev Returns the natural logarithm of `value`, dropping most of the decimal places to arrive at a value that, * when passed to `_fromLowResLog`, will have a maximum relative error of ~0.05% compared to `value`. * * Values returned from this function should not be mixed with other fixed-point values (as they have a different * number of digits), but can be added or subtracted. Use `_fromLowResLog` to undo this process and return to an * 18 decimal places fixed point value. * * Because so much precision is lost, the logarithmic values can be stored using much fewer bits than the original * value required. */ function _toLowResLog(uint256 value) internal pure returns (int256) { int256 ln = LogExpMath.ln(int256(value)); // Rounding division for signed numerator return (ln > 0 ? ln + _HALF_LOG_COMPRESSION_FACTOR : ln - _HALF_LOG_COMPRESSION_FACTOR) / _LOG_COMPRESSION_FACTOR; } /** * @dev Restores `value` from logarithmic space. `value` is expected to be the result of a call to `_toLowResLog`, * any other function that returns 4 decimals fixed point logarithms, or the sum of such values. */ function _fromLowResLog(int256 value) internal pure returns (uint256) { return uint256(LogExpMath.exp(value * _LOG_COMPRESSION_FACTOR)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/helpers/WordCodec.sol"; /** * @dev This module provides an interface to store seemingly unrelated pieces of information, in particular used by * Weighted Pools of 2 tokens with a price oracle. * * These pieces of information are all kept together in a single storage slot to reduce the number of storage reads. In * particular, we not only store configuration values (such as the swap fee percentage), but also cache * reduced-precision versions of the total BPT supply and invariant, which lets us not access nor compute these values * when producing oracle updates during a swap. * * Data is stored with the following structure: * * [ swap fee pct | oracle enabled | oracle index | oracle sample initial timestamp | log supply | log invariant ] * [ uint64 | bool | uint10 | uint31 | int22 | int22 ] * * Note that we are not using the most-significant 106 bits. */ library WeightedPool2TokensMiscData { using WordCodec for bytes32; using WordCodec for uint256; uint256 private constant _LOG_INVARIANT_OFFSET = 0; uint256 private constant _LOG_TOTAL_SUPPLY_OFFSET = 22; uint256 private constant _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET = 44; uint256 private constant _ORACLE_INDEX_OFFSET = 75; uint256 private constant _ORACLE_ENABLED_OFFSET = 85; uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 86; /** * @dev Returns the cached logarithm of the invariant. */ function logInvariant(bytes32 data) internal pure returns (int256) { return data.decodeInt22(_LOG_INVARIANT_OFFSET); } /** * @dev Returns the cached logarithm of the total supply. */ function logTotalSupply(bytes32 data) internal pure returns (int256) { return data.decodeInt22(_LOG_TOTAL_SUPPLY_OFFSET); } /** * @dev Returns the timestamp of the creation of the oracle's latest sample. */ function oracleSampleCreationTimestamp(bytes32 data) internal pure returns (uint256) { return data.decodeUint31(_ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET); } /** * @dev Returns the index of the oracle's latest sample. */ function oracleIndex(bytes32 data) internal pure returns (uint256) { return data.decodeUint10(_ORACLE_INDEX_OFFSET); } /** * @dev Returns true if the oracle is enabled. */ function oracleEnabled(bytes32 data) internal pure returns (bool) { return data.decodeBool(_ORACLE_ENABLED_OFFSET); } /** * @dev Returns the swap fee percentage. */ function swapFeePercentage(bytes32 data) internal pure returns (uint256) { return data.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET); } /** * @dev Sets the logarithm of the invariant in `data`, returning the updated value. */ function setLogInvariant(bytes32 data, int256 _logInvariant) internal pure returns (bytes32) { return data.insertInt22(_logInvariant, _LOG_INVARIANT_OFFSET); } /** * @dev Sets the logarithm of the total supply in `data`, returning the updated value. */ function setLogTotalSupply(bytes32 data, int256 _logTotalSupply) internal pure returns (bytes32) { return data.insertInt22(_logTotalSupply, _LOG_TOTAL_SUPPLY_OFFSET); } /** * @dev Sets the timestamp of the creation of the oracle's latest sample in `data`, returning the updated value. */ function setOracleSampleCreationTimestamp(bytes32 data, uint256 _initialTimestamp) internal pure returns (bytes32) { return data.insertUint31(_initialTimestamp, _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET); } /** * @dev Sets the index of the oracle's latest sample in `data`, returning the updated value. */ function setOracleIndex(bytes32 data, uint256 _oracleIndex) internal pure returns (bytes32) { return data.insertUint10(_oracleIndex, _ORACLE_INDEX_OFFSET); } /** * @dev Enables or disables the oracle in `data`, returning the updated value. */ function setOracleEnabled(bytes32 data, bool _oracleEnabled) internal pure returns (bytes32) { return data.insertBoolean(_oracleEnabled, _ORACLE_ENABLED_OFFSET); } /** * @dev Sets the swap fee percentage in `data`, returning the updated value. */ function setSwapFeePercentage(bytes32 data, uint256 _swapFeePercentage) internal pure returns (bytes32) { return data.insertUint64(_swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; import "./WeightedPool.sol"; library WeightedPoolUserDataHelpers { function joinKind(bytes memory self) internal pure returns (WeightedPool.JoinKind) { return abi.decode(self, (WeightedPool.JoinKind)); } function exitKind(bytes memory self) internal pure returns (WeightedPool.ExitKind) { return abi.decode(self, (WeightedPool.ExitKind)); } // Joins function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) { (, amountsIn) = abi.decode(self, (WeightedPool.JoinKind, uint256[])); } function exactTokensInForBptOut(bytes memory self) internal pure returns (uint256[] memory amountsIn, uint256 minBPTAmountOut) { (, amountsIn, minBPTAmountOut) = abi.decode(self, (WeightedPool.JoinKind, uint256[], uint256)); } function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) { (, bptAmountOut, tokenIndex) = abi.decode(self, (WeightedPool.JoinKind, uint256, uint256)); } // Exits function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) { (, bptAmountIn, tokenIndex) = abi.decode(self, (WeightedPool.ExitKind, uint256, uint256)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256)); } function bptInForExactTokensOut(bytes memory self) internal pure returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn) { (, amountsOut, maxBPTAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../lib/math/Math.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/IERC20Permit.sol"; import "../lib/openzeppelin/EIP712.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` */ contract BalancerPoolToken is IERC20, IERC20Permit, EIP712 { using Math for uint256; // State variables uint8 private constant _DECIMALS = 18; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) private _allowance; uint256 private _totalSupply; string private _name; string private _symbol; mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPE_HASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // Function declarations constructor(string memory tokenName, string memory tokenSymbol) EIP712(tokenName, "1") { _name = tokenName; _symbol = tokenSymbol; } // External functions function allowance(address owner, address spender) external view override returns (uint256) { return _allowance[owner][spender]; } function balanceOf(address account) external view override returns (uint256) { return _balance[account]; } function approve(address spender, uint256 amount) external override returns (bool) { _setAllowance(msg.sender, spender, amount); return true; } function increaseApproval(address spender, uint256 amount) external returns (bool) { _setAllowance(msg.sender, spender, _allowance[msg.sender][spender].add(amount)); return true; } function decreaseApproval(address spender, uint256 amount) external returns (bool) { uint256 currentAllowance = _allowance[msg.sender][spender]; if (amount >= currentAllowance) { _setAllowance(msg.sender, spender, 0); } else { _setAllowance(msg.sender, spender, currentAllowance.sub(amount)); } return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { _move(msg.sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { uint256 currentAllowance = _allowance[sender][msg.sender]; _require(msg.sender == sender || currentAllowance >= amount, Errors.INSUFFICIENT_ALLOWANCE); _move(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _setAllowance(sender, msg.sender, currentAllowance - amount); } return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _setAllowance(owner, spender, value); } // Public functions function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _DECIMALS; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function nonces(address owner) external view override returns (uint256) { return _nonces[owner]; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _balance[recipient] = _balance[recipient].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { uint256 currentBalance = _balance[sender]; _require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE); _balance[sender] = currentBalance - amount; _totalSupply = _totalSupply.sub(amount); emit Transfer(sender, address(0), amount); } function _move( address sender, address recipient, uint256 amount ) internal { uint256 currentBalance = _balance[sender]; _require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE); // Prohibit transfers to the zero address to avoid confusion with the // Transfer event emitted by `_burnPoolTokens` _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _balance[sender] = currentBalance - amount; _balance[recipient] = _balance[recipient].add(amount); emit Transfer(sender, recipient, amount); } // Private functions function _setAllowance( address owner, address spender, uint256 amount ) private { _allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../lib/helpers/Authentication.sol"; import "../vault/interfaces/IAuthorizer.sol"; import "./BasePool.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) private view returns (bool) { // This implementation hardcodes the setSwapFeePercentage action identifier. return actionId == getActionId(BasePool.setSwapFeePercentage.selector); } function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./Buffer.sol"; import "./Samples.sol"; import "../../lib/helpers/BalancerErrors.sol"; import "./IWeightedPoolPriceOracle.sol"; import "../IPriceOracle.sol"; /** * @dev This module allows Pools to access historical pricing information. * * It uses a 1024 long circular buffer to store past data, where the data within each sample is the result of * accumulating live data for no more than two minutes. Therefore, assuming the worst case scenario where new data is * updated in every single block, the oldest samples in the buffer (and therefore largest queryable period) will * be slightly over 34 hours old. * * Usage of this module requires the caller to keep track of two variables: the latest circular buffer index, and the * timestamp when the index last changed. */ contract PoolPriceOracle is IWeightedPoolPriceOracle { using Buffer for uint256; using Samples for bytes32; // Each sample in the buffer accumulates information for up to 2 minutes. This is simply to reduce the size of the // buffer: small time deviations will not have any significant effect. // solhint-disable not-rely-on-time uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes; // We use a mapping to simulate an array: the buffer won't grow or shrink, and since we will always use valid // indexes using a mapping saves gas by skipping the bounds checks. mapping(uint256 => bytes32) internal _samples; function getSample(uint256 index) external view override returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 timestamp ) { _require(index < Buffer.SIZE, Errors.ORACLE_INVALID_INDEX); bytes32 sample = _getSample(index); return sample.unpack(); } function getTotalSamples() external pure override returns (uint256) { return Buffer.SIZE; } /** * @dev Processes new price and invariant data, updating the latest sample or creating a new one. * * Receives the new logarithms of values to store: `logPairPrice`, `logBptPrice` and `logInvariant`, as well the * index of the latest sample and the timestamp of its creation. * * Returns the index of the latest sample. If different from `latestIndex`, the caller should also store the * timestamp, and pass it on future calls to this function. */ function _processPriceData( uint256 latestSampleCreationTimestamp, uint256 latestIndex, int256 logPairPrice, int256 logBptPrice, int256 logInvariant ) internal returns (uint256) { // Read latest sample, and compute the next one by updating it with the newly received data. bytes32 sample = _getSample(latestIndex).update(logPairPrice, logBptPrice, logInvariant, block.timestamp); // We create a new sample if more than _MAX_SAMPLE_DURATION seconds have elapsed since the creation of the // latest one. In other words, no sample accumulates data over a period larger than _MAX_SAMPLE_DURATION. bool newSample = block.timestamp - latestSampleCreationTimestamp >= _MAX_SAMPLE_DURATION; latestIndex = newSample ? latestIndex.next() : latestIndex; // Store the updated or new sample. _samples[latestIndex] = sample; return latestIndex; } /** * @dev Returns the instant value for `variable` in the sample pointed to by `index`. */ function _getInstantValue(IPriceOracle.Variable variable, uint256 index) internal view returns (int256) { bytes32 sample = _getSample(index); _require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED); return sample.instant(variable); } /** * @dev Returns the value of the accumulator for `variable` `ago` seconds ago. `latestIndex` must be the index of * the latest sample in the buffer. * * Reverts under the following conditions: * - if the buffer is empty. * - if querying past information and the buffer has not been fully initialized. * - if querying older information than available in the buffer. Note that a full buffer guarantees queries for the * past 34 hours will not revert. * * If requesting information for a timestamp later than the latest one, it is extrapolated using the latest * available data. * * When no exact information is available for the requested past timestamp (as usually happens, since at most one * timestamp is stored every two minutes), it is estimated by performing linear interpolation using the closest * values. This process is guaranteed to complete performing at most 10 storage reads. */ function _getPastAccumulator( IPriceOracle.Variable variable, uint256 latestIndex, uint256 ago ) internal view returns (int256) { // `ago` must not be before the epoch. _require(block.timestamp >= ago, Errors.ORACLE_INVALID_SECONDS_QUERY); uint256 lookUpTime = block.timestamp - ago; bytes32 latestSample = _getSample(latestIndex); uint256 latestTimestamp = latestSample.timestamp(); // The latest sample only has a non-zero timestamp if no data was ever processed and stored in the buffer. _require(latestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED); if (latestTimestamp <= lookUpTime) { // The accumulator at times ahead of the latest one are computed by extrapolating the latest data. This is // equivalent to the instant value not changing between the last timestamp and the look up time. // We can use unchecked arithmetic since the accumulator can be represented in 53 bits, timestamps in 31 // bits, and the instant value in 22 bits. uint256 elapsed = lookUpTime - latestTimestamp; return latestSample.accumulator(variable) + (latestSample.instant(variable) * int256(elapsed)); } else { // The look up time is before the latest sample, but we need to make sure that it is not before the oldest // sample as well. // Since we use a circular buffer, the oldest sample is simply the next one. uint256 oldestIndex = latestIndex.next(); { // Local scope used to prevent stack-too-deep errors. bytes32 oldestSample = _getSample(oldestIndex); uint256 oldestTimestamp = oldestSample.timestamp(); // For simplicity's sake, we only perform past queries if the buffer has been fully initialized. This // means the oldest sample must have a non-zero timestamp. _require(oldestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED); // The only remaining condition to check is for the look up time to be between the oldest and latest // timestamps. _require(oldestTimestamp <= lookUpTime, Errors.ORACLE_QUERY_TOO_OLD); } // Perform binary search to find nearest samples to the desired timestamp. (bytes32 prev, bytes32 next) = _findNearestSample(lookUpTime, oldestIndex); // `next`'s timestamp is guaranteed to be larger than `prev`'s, so we can skip checked arithmetic. uint256 samplesTimeDiff = next.timestamp() - prev.timestamp(); if (samplesTimeDiff > 0) { // We estimate the accumulator at the requested look up time by interpolating linearly between the // previous and next accumulators. // We can use unchecked arithmetic since the accumulators can be represented in 53 bits, and timestamps // in 31 bits. int256 samplesAccDiff = next.accumulator(variable) - prev.accumulator(variable); uint256 elapsed = lookUpTime - prev.timestamp(); return prev.accumulator(variable) + ((samplesAccDiff * int256(elapsed)) / int256(samplesTimeDiff)); } else { // Rarely, one of the samples will have the exact requested look up time, which is indicated by `prev` // and `next` being the same. In this case, we simply return the accumulator at that point in time. return prev.accumulator(variable); } } } /** * @dev Finds the two samples with timestamps before and after `lookUpDate`. If one of the samples matches exactly, * both `prev` and `next` will be it. `offset` is the index of the oldest sample in the buffer. * * Assumes `lookUpDate` is greater or equal than the timestamp of the oldest sample, and less or equal than the * timestamp of the latest sample. */ function _findNearestSample(uint256 lookUpDate, uint256 offset) internal view returns (bytes32 prev, bytes32 next) { // We're going to perform a binary search in the circular buffer, which requires it to be sorted. To achieve // this, we offset all buffer accesses by `offset`, making the first element the oldest one. // Auxiliary variables in a typical binary search: we will look at some value `mid` between `low` and `high`, // periodically increasing `low` or decreasing `high` until we either find a match or determine the element is // not in the array. uint256 low = 0; uint256 high = Buffer.SIZE - 1; uint256 mid; // If the search fails and no sample has a timestamp of `lookUpDate` (as is the most common scenario), `sample` // will be either the sample with the largest timestamp smaller than `lookUpDate`, or the one with the smallest // timestamp larger than `lookUpDate`. bytes32 sample; uint256 sampleTimestamp; while (low <= high) { // Mid is the floor of the average. uint256 midWithoutOffset = (high + low) / 2; // Recall that the buffer is not actually sorted: we need to apply the offset to access it in a sorted way. mid = midWithoutOffset.add(offset); sample = _getSample(mid); sampleTimestamp = sample.timestamp(); if (sampleTimestamp < lookUpDate) { // If the mid sample is bellow the look up date, then increase the low index to start from there. low = midWithoutOffset + 1; } else if (sampleTimestamp > lookUpDate) { // If the mid sample is above the look up date, then decrease the high index to start from there. // We can skip checked arithmetic: it is impossible for `high` to ever be 0, as a scenario where `low` // equals 0 and `high` equals 1 would result in `low` increasing to 1 in the previous `if` clause. high = midWithoutOffset - 1; } else { // sampleTimestamp == lookUpDate // If we have an exact match, return the sample as both `prev` and `next`. return (sample, sample); } } // In case we reach here, it means we didn't find exactly the sample we where looking for. return sampleTimestamp < lookUpDate ? (sample, _getSample(mid.next())) : (_getSample(mid.prev()), sample); } /** * @dev Returns the sample that corresponds to a given `index`. * * Using this function instead of accessing storage directly results in denser bytecode (since the storage slot is * only computed here). */ function _getSample(uint256 index) internal view returns (bytes32) { return _samples[index]; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; library Buffer { // The buffer is a circular storage structure with 1024 slots. // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant SIZE = 1024; /** * @dev Returns the index of the element before the one pointed by `index`. */ function prev(uint256 index) internal pure returns (uint256) { return sub(index, 1); } /** * @dev Returns the index of the element after the one pointed by `index`. */ function next(uint256 index) internal pure returns (uint256) { return add(index, 1); } /** * @dev Returns the index of an element `offset` slots after the one pointed by `index`. */ function add(uint256 index, uint256 offset) internal pure returns (uint256) { return (index + offset) % SIZE; } /** * @dev Returns the index of an element `offset` slots before the one pointed by `index`. */ function sub(uint256 index, uint256 offset) internal pure returns (uint256) { return (index + SIZE - offset) % SIZE; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Interface for querying historical data from a Pool that can be used as a Price Oracle. * * This lets third parties retrieve average prices of tokens held by a Pool over a given period of time, as well as the * price of the Pool share token (BPT) and invariant. Since the invariant is a sensible measure of Pool liquidity, it * can be used to compare two different price sources, and choose the most liquid one. * * Once the oracle is fully initialized, all queries are guaranteed to succeed as long as they require no data that * is not older than the largest safe query window. */ interface IPriceOracle { // The three values that can be queried: // // - PAIR_PRICE: the price of the tokens in the Pool, expressed as the price of the second token in units of the // first token. For example, if token A is worth $2, and token B is worth $4, the pair price will be 2.0. // Note that the price is computed *including* the tokens decimals. This means that the pair price of a Pool with // DAI and USDC will be close to 1.0, despite DAI having 18 decimals and USDC 6. // // - BPT_PRICE: the price of the Pool share token (BPT), in units of the first token. // Note that the price is computed *including* the tokens decimals. This means that the BPT price of a Pool with // USDC in which BPT is worth $5 will be 5.0, despite the BPT having 18 decimals and USDC 6. // // - INVARIANT: the value of the Pool's invariant, which serves as a measure of its liquidity. enum Variable { PAIR_PRICE, BPT_PRICE, INVARIANT } /** * @dev Returns the time average weighted price corresponding to each of `queries`. Prices are represented as 18 * decimal fixed point values. */ function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view returns (uint256[] memory results); /** * @dev Returns latest sample of `variable`. Prices are represented as 18 decimal fixed point values. */ function getLatest(Variable variable) external view returns (uint256); /** * @dev Information for a Time Weighted Average query. * * Each query computes the average over a window of duration `secs` seconds that ended `ago` seconds ago. For * example, the average over the past 30 minutes is computed by settings secs to 1800 and ago to 0. If secs is 1800 * and ago is 1800 as well, the average between 60 and 30 minutes ago is computed instead. */ struct OracleAverageQuery { Variable variable; uint256 secs; uint256 ago; } /** * @dev Returns largest time window that can be safely queried, where 'safely' means the Oracle is guaranteed to be * able to produce a result and not revert. * * If a query has a non-zero `ago` value, then `secs + ago` (the oldest point in time) must be smaller than this * value for 'safe' queries. */ function getLargestSafeQueryWindow() external view returns (uint256); /** * @dev Returns the accumulators corresponding to each of `queries`. */ function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view returns (int256[] memory results); /** * @dev Information for an Accumulator query. * * Each query estimates the accumulator at a time `ago` seconds ago. */ struct OracleAccumulatorQuery { Variable variable; uint256 ago; } } // SPDX-License-Identifier: MIT // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the “Software”), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library */ library Math { /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. */ library WordCodec { // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, // or to insert a new one replacing the old. uint256 private constant _MASK_1 = 2**(1) - 1; uint256 private constant _MASK_10 = 2**(10) - 1; uint256 private constant _MASK_22 = 2**(22) - 1; uint256 private constant _MASK_31 = 2**(31) - 1; uint256 private constant _MASK_53 = 2**(53) - 1; uint256 private constant _MASK_64 = 2**(64) - 1; // Largest positive values that can be represented as N bits signed integers. int256 private constant _MAX_INT_22 = 2**(21) - 1; int256 private constant _MAX_INT_53 = 2**(52) - 1; // In-place insertion /** * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new * word. */ function insertBoolean( bytes32 word, bool value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset)); return clearedWord | bytes32(uint256(value ? 1 : 0) << offset); } // Unsigned /** * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 10 bits. */ function insertUint10( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 31 bits. */ function insertUint31( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 64 bits. */ function insertUint64( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset)); return clearedWord | bytes32(value << offset); } // Signed /** * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 22 bits. */ function insertInt22( bytes32 word, int256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & _MASK_22) << offset); } // Encoding // Unsigned /** * @dev Encodes a 31 bit unsigned integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeUint31(uint256 value, uint256 offset) internal pure returns (bytes32) { return bytes32(value << offset); } // Signed /** * @dev Encodes a 22 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_22) << offset); } /** * @dev Encodes a 53 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_53) << offset); } // Decoding /** * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. */ function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) { return (uint256(word >> offset) & _MASK_1) == 1; } // Unsigned /** * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_10; } /** * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_31; } /** * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_64; } // Signed /** * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; } /** * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_53); // In case the decoded value is greater than the max positive integer that can be represented with 53 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/math/FixedPoint.sol"; import "../../lib/helpers/InputHelpers.sol"; import "../BaseMinimalSwapInfoPool.sol"; import "./WeightedMath.sol"; import "./WeightedPoolUserDataHelpers.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus total // count, resulting in a large number of state variables. contract WeightedPool is BaseMinimalSwapInfoPool, WeightedMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 private immutable _maxWeightTokenIndex; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; uint256 private immutable _normalizedWeight2; uint256 private immutable _normalizedWeight3; uint256 private immutable _normalizedWeight4; uint256 private immutable _normalizedWeight5; uint256 private immutable _normalizedWeight6; uint256 private immutable _normalizedWeight7; uint256 private _lastInvariant; enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory normalizedWeights, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BaseMinimalSwapInfoPool( vault, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); // Ensure each normalized weight is above them minimum and find the token index of the maximum weight uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights.length > 0 ? normalizedWeights[0] : 0; _normalizedWeight1 = normalizedWeights.length > 1 ? normalizedWeights[1] : 0; _normalizedWeight2 = normalizedWeights.length > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = normalizedWeights.length > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = normalizedWeights.length > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = normalizedWeights.length > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = normalizedWeights.length > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = normalizedWeights.length > 7 ? normalizedWeights[7] : 0; } function _normalizedWeight(IERC20 token) internal view virtual returns (uint256) { // prettier-ignore if (token == _token0) { return _normalizedWeight0; } else if (token == _token1) { return _normalizedWeight1; } else if (token == _token2) { return _normalizedWeight2; } else if (token == _token3) { return _normalizedWeight3; } else if (token == _token4) { return _normalizedWeight4; } else if (token == _token5) { return _normalizedWeight5; } else if (token == _token6) { return _normalizedWeight6; } else if (token == _token7) { return _normalizedWeight7; } else { _revert(Errors.INVALID_TOKEN); } } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { normalizedWeights[0] = _normalizedWeight0; } else { return normalizedWeights; } if (totalTokens > 1) { normalizedWeights[1] = _normalizedWeight1; } else { return normalizedWeights; } if (totalTokens > 2) { normalizedWeights[2] = _normalizedWeight2; } else { return normalizedWeights; } if (totalTokens > 3) { normalizedWeights[3] = _normalizedWeight3; } else { return normalizedWeights; } if (totalTokens > 4) { normalizedWeights[4] = _normalizedWeight4; } else { return normalizedWeights; } if (totalTokens > 5) { normalizedWeights[5] = _normalizedWeight5; } else { return normalizedWeights; } if (totalTokens > 6) { normalizedWeights[6] = _normalizedWeight6; } else { return normalizedWeights; } if (totalTokens > 7) { normalizedWeights[7] = _normalizedWeight7; } else { return normalizedWeights; } } return normalizedWeights; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } // Base Pool handlers // Swap function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } // Initialize function _onInitializePool( bytes32, address, address, bytes memory userData ) internal virtual override whenNotPaused returns (uint256, uint256[] memory) { // It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent // initialization in this case. WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens()); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } // Join function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override whenNotPaused returns ( uint256, uint256[] memory, uint256[] memory ) { // All joins are disabled while the contract is paused. uint256[] memory normalizedWeights = _normalizedWeights(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { JoinKind kind = userData.joinKind(); if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); } else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), _swapFeePercentage ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](_getTotalTokens()); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), _swapFeePercentage ); return (bptAmountOut, amountsIn); } // Exit function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and // reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else { // ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](_getTotalTokens()); // And then assign the result to the selected token amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), _swapFeePercentage ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, _scalingFactors()); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), _swapFeePercentage ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Returns the value of the invariant given `balances`, assuming they are increased by `amountsIn`. All * amounts are expected to be upscaled. */ function _invariantAfterJoin( uint256[] memory balances, uint256[] memory amountsIn, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsIn, FixedPoint.add); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function _invariantAfterExit( uint256[] memory balances, uint256[] memory amountsOut, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsOut, FixedPoint.sub); return WeightedMath._calculateInvariant(normalizedWeights, balances); } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply()); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "../vault/interfaces/IMinimalSwapInfoPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`. * * Derived contracts must implement `_onSwapGivenIn` and `_onSwapGivenOut` along with `BasePool`'s virtual functions. */ abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool { constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.MINIMAL_SWAP_INFO, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // solhint-disable-previous-line no-empty-blocks } // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external view virtual override returns (uint256) { uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn); uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. request.amount = _subtractSwapFeeAmount(request.amount); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. return _addSwapFeeAmount(amountIn); } } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already * been deducted from `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/FixedPoint.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/TemporarilyPausable.sol"; import "../lib/openzeppelin/ERC20.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; import "../vault/interfaces/IVault.sol"; import "../vault/interfaces/IBasePool.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus a total // count, resulting in a large number of state variables. // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with an immutable set * of registered tokens, no Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _MAX_TOKENS = 8; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% uint256 private constant _MINIMUM_BPT = 1e6; uint256 internal _swapFeePercentage; IVault private immutable _vault; bytes32 private immutable _poolId; uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; IERC20 internal immutable _token4; IERC20 internal immutable _token5; IERC20 internal immutable _token6; IERC20 internal immutable _token7; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; uint256 internal immutable _scalingFactor2; uint256 internal immutable _scalingFactor3; uint256 internal immutable _scalingFactor4; uint256 internal immutable _scalingFactor5; uint256 internal immutable _scalingFactor6; uint256 internal immutable _scalingFactor7; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _MAX_TOKENS, Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); // Pass in zero addresses for Asset Managers vault.registerTokens(poolId, tokens, new address[](tokens.length)); // Set immutable state variables - these cannot be read from during construction _vault = vault; _poolId = poolId; _totalTokens = tokens.length; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = tokens.length > 0 ? tokens[0] : IERC20(0); _token1 = tokens.length > 1 ? tokens[1] : IERC20(0); _token2 = tokens.length > 2 ? tokens[2] : IERC20(0); _token3 = tokens.length > 3 ? tokens[3] : IERC20(0); _token4 = tokens.length > 4 ? tokens[4] : IERC20(0); _token5 = tokens.length > 5 ? tokens[5] : IERC20(0); _token6 = tokens.length > 6 ? tokens[6] : IERC20(0); _token7 = tokens.length > 7 ? tokens[7] : IERC20(0); _scalingFactor0 = tokens.length > 0 ? _computeScalingFactor(tokens[0]) : 0; _scalingFactor1 = tokens.length > 1 ? _computeScalingFactor(tokens[1]) : 0; _scalingFactor2 = tokens.length > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = tokens.length > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = tokens.length > 4 ? _computeScalingFactor(tokens[4]) : 0; _scalingFactor5 = tokens.length > 5 ? _computeScalingFactor(tokens[5]) : 0; _scalingFactor6 = tokens.length > 6 ? _computeScalingFactor(tokens[6]) : 0; _scalingFactor7 = tokens.length > 7 ? _computeScalingFactor(tokens[7]) : 0; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function _getTotalTokens() internal view returns (uint256) { return _totalTokens; } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } // Caller must be approved by the Vault's Authorizer function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _swapFeePercentage = swapFeePercentage; emit SwapFeePercentageChanged(swapFeePercentage); } // Caller must be approved by the Vault's Authorizer function setPaused(bool paused) external authenticate { _setPaused(paused); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(poolId, sender, recipient, userData); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(_swapFeePercentage.complement()); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(_swapFeePercentage); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(IERC20 token) internal view returns (uint256) { // prettier-ignore if (token == _token0) { return _scalingFactor0; } else if (token == _token1) { return _scalingFactor1; } else if (token == _token2) { return _scalingFactor2; } else if (token == _token3) { return _scalingFactor3; } else if (token == _token4) { return _scalingFactor4; } else if (token == _token5) { return _scalingFactor5; } else if (token == _token6) { return _scalingFactor6; } else if (token == _token7) { return _scalingFactor7; } else { _revert(Errors.INVALID_TOKEN); } } /** * @dev Returns all the scaling factors in the same order as the registered tokens. The Vault will always * pass balances in this order when calling any of the Pool hooks */ function _scalingFactors() internal view returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; } if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; } if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; } if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; } if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; } if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; } if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; } } return scalingFactors; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.mul(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "../ProtocolFeesCollector.sol"; import "../../lib/helpers/ISignaturesValidator.sol"; import "../../lib/helpers/ITemporarilyPausable.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (ProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; /** * @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support * sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals. */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "../../lib/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/openzeppelin/IERC20.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/Authentication.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IAuthorizer.sol"; /** * @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the * Vault performs to reduce its overall bytecode size. * * The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are * sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated * to the Vault's own authorizer. */ contract ProtocolFeesCollector is Authentication, ReentrancyGuard { using SafeERC20 for IERC20; // Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%). uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50% uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1% IVault public immutable vault; // All fee percentages are 18-decimal fixed point numbers. // The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not // actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due // when users join and exit them. uint256 private _swapFeePercentage; // The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent. uint256 private _flashLoanFeePercentage; event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); constructor(IVault _vault) // The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action // identifiers. Authentication(bytes32(uint256(address(this)))) { vault = _vault; } function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external nonReentrant authenticate { InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 amount = amounts[i]; token.safeTransfer(recipient, amount); } } function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate { _require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH); _swapFeePercentage = newSwapFeePercentage; emit SwapFeePercentageChanged(newSwapFeePercentage); } function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate { _require( newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE, Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH ); _flashLoanFeePercentage = newFlashLoanFeePercentage; emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage); } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } function getFlashLoanFeePercentage() external view returns (uint256) { return _flashLoanFeePercentage; } function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) { feeAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { feeAmounts[i] = tokens[i].balanceOf(address(this)); } } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { return _getAuthorizer().canPerform(actionId, account, address(this)); } function _getAuthorizer() internal view returns (IAuthorizer) { return vault.getAuthorizer(); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // 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 // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce gas costs. // The `safeTransfer` and `safeTransferFrom` functions assume that `token` is a contract (an account with code), and // work differently from the OpenZeppelin version if it is not. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.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 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @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). * * WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert. */ function _callOptionalReturn(address 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. (bool success, bytes memory returndata) = token.call(data); // If the low-level call didn't succeed we return whatever was returned from it. assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } // Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs _require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/helpers/WordCodec.sol"; import "../IPriceOracle.sol"; /** * @dev This library provides functions to help manipulating samples for Pool Price Oracles. It handles updates, * encoding, and decoding of samples. * * Each sample holds the timestamp of its last update, plus information about three pieces of data: the price pair, the * price of BPT (the associated Pool token), and the invariant. * * Prices and invariant are not stored directly: instead, we store their logarithm. These are known as the 'instant' * values: the exact value at that timestamp. * * Additionally, for each value we keep an accumulator with the sum of all past values, each weighted by the time * elapsed since the previous update. This lets us later subtract accumulators at different points in time and divide by * the time elapsed between them, arriving at the geometric mean of the values (also known as log-average). * * All samples are stored in a single 256 bit word with the following structure: * * [ log pair price | bpt price | invariant ] * [ instant | accumulator | instant | accumulator | instant | accumulator | timestamp ] * [ int22 | int53 | int22 | int53 | int22 | int53 | uint31 ] * MSB LSB * * Assuming the timestamp doesn't overflow (which holds until the year 2038), the largest elapsed time is 2^31, which * means the largest possible accumulator value is 2^21 * 2^31, which can be represented using a signed 53 bit integer. */ library Samples { using WordCodec for int256; using WordCodec for uint256; using WordCodec for bytes32; uint256 internal constant _TIMESTAMP_OFFSET = 0; uint256 internal constant _ACC_LOG_INVARIANT_OFFSET = 31; uint256 internal constant _INST_LOG_INVARIANT_OFFSET = 84; uint256 internal constant _ACC_LOG_BPT_PRICE_OFFSET = 106; uint256 internal constant _INST_LOG_BPT_PRICE_OFFSET = 159; uint256 internal constant _ACC_LOG_PAIR_PRICE_OFFSET = 181; uint256 internal constant _INST_LOG_PAIR_PRICE_OFFSET = 234; /** * @dev Updates a sample, accumulating the new data based on the elapsed time since the previous update. Returns the * updated sample. * * IMPORTANT: This function does not perform any arithmetic checks. In particular, it assumes the caller will never * pass values that cannot be represented as 22 bit signed integers. Additionally, it also assumes * `currentTimestamp` is greater than `sample`'s timestamp. */ function update( bytes32 sample, int256 instLogPairPrice, int256 instLogBptPrice, int256 instLogInvariant, uint256 currentTimestamp ) internal pure returns (bytes32) { // Because elapsed can be represented as a 31 bit unsigned integer, and the received values can be represented // as 22 bit signed integers, we don't need to perform checked arithmetic. int256 elapsed = int256(currentTimestamp - timestamp(sample)); int256 accLogPairPrice = _accLogPairPrice(sample) + instLogPairPrice * elapsed; int256 accLogBptPrice = _accLogBptPrice(sample) + instLogBptPrice * elapsed; int256 accLogInvariant = _accLogInvariant(sample) + instLogInvariant * elapsed; return pack( instLogPairPrice, accLogPairPrice, instLogBptPrice, accLogBptPrice, instLogInvariant, accLogInvariant, currentTimestamp ); } /** * @dev Returns the instant value stored in `sample` for `variable`. */ function instant(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) { if (variable == IPriceOracle.Variable.PAIR_PRICE) { return _instLogPairPrice(sample); } else if (variable == IPriceOracle.Variable.BPT_PRICE) { return _instLogBptPrice(sample); } else { // variable == IPriceOracle.Variable.INVARIANT return _instLogInvariant(sample); } } /** * @dev Returns the accumulator value stored in `sample` for `variable`. */ function accumulator(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) { if (variable == IPriceOracle.Variable.PAIR_PRICE) { return _accLogPairPrice(sample); } else if (variable == IPriceOracle.Variable.BPT_PRICE) { return _accLogBptPrice(sample); } else { // variable == IPriceOracle.Variable.INVARIANT return _accLogInvariant(sample); } } /** * @dev Returns `sample`'s timestamp. */ function timestamp(bytes32 sample) internal pure returns (uint256) { return sample.decodeUint31(_TIMESTAMP_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the pair price. */ function _instLogPairPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_PAIR_PRICE_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the pair price. */ function _accLogPairPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the BPT price. */ function _instLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_BPT_PRICE_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the BPT price. */ function _accLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_BPT_PRICE_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the invariant. */ function _instLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_INVARIANT_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the invariant. */ function _accLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_INVARIANT_OFFSET); } /** * @dev Returns a sample created by packing together its components. */ function pack( int256 instLogPairPrice, int256 accLogPairPrice, int256 instLogBptPrice, int256 accLogBptPrice, int256 instLogInvariant, int256 accLogInvariant, uint256 _timestamp ) internal pure returns (bytes32) { return instLogPairPrice.encodeInt22(_INST_LOG_PAIR_PRICE_OFFSET) | accLogPairPrice.encodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET) | instLogBptPrice.encodeInt22(_INST_LOG_BPT_PRICE_OFFSET) | accLogBptPrice.encodeInt53(_ACC_LOG_BPT_PRICE_OFFSET) | instLogInvariant.encodeInt22(_INST_LOG_INVARIANT_OFFSET) | accLogInvariant.encodeInt53(_ACC_LOG_INVARIANT_OFFSET) | _timestamp.encodeUint31(_TIMESTAMP_OFFSET); } /** * @dev Unpacks a sample into its components. */ function unpack(bytes32 sample) internal pure returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 _timestamp ) { logPairPrice = _instLogPairPrice(sample); accLogPairPrice = _accLogPairPrice(sample); logBptPrice = _instLogBptPrice(sample); accLogBptPrice = _accLogBptPrice(sample); logInvariant = _instLogInvariant(sample); accLogInvariant = _accLogInvariant(sample); _timestamp = timestamp(sample); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IWeightedPoolPriceOracle { /** * @dev Returns the raw data of the sample at `index`. */ function getSample(uint256 index) external view returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 timestamp ); /** * @dev Returns the total number of samples. */ function getTotalSamples() external view returns (uint256); }
Returns true if `account` can perform the action described by `actionId` in the contract `where`./ SPDX-License-Identifier: GPL-3.0-or-later This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http:www.gnu.org/licenses/>.
interface IAuthentication { function getActionId(bytes4 selector) external view returns (bytes32); }
67,879
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./interfaces/IVoucherSets.sol"; import "./interfaces/IVouchers.sol"; import "./interfaces/IVoucherKernel.sol"; import {PaymentMethod, VoucherState, VoucherStatus, isStateCommitted, isStateRedemptionSigned, isStateRefunded, isStateExpired, isStatus, determineStatus} from "./UsingHelpers.sol"; //preparing for ERC-1066, ERC-1444, EIP-838 /** * @title VoucherKernel contract controls the core business logic * @dev Notes: * - The usage of block.timestamp is honored since vouchers are defined currently with day-precision. * See: https://ethereum.stackexchange.com/questions/5924/how-do-ethereum-mining-nodes-maintain-a-time-consistent-with-the-network/5931#5931 */ // solhint-disable-next-line contract VoucherKernel is IVoucherKernel, Ownable, Pausable, ReentrancyGuard { using Address for address; using SafeMath for uint256; //ERC1155 contract representing voucher sets address private voucherSetTokenAddress; //ERC721 contract representing vouchers; address private voucherTokenAddress; //promise for an asset could be reusable, but simplified here for brevity struct Promise { bytes32 promiseId; uint256 nonce; //the asset that is offered address seller; //the seller who created the promise //we simplify the value for the demoapp, otherwise voucher details would be packed in one bytes32 field value uint256 validFrom; uint256 validTo; uint256 price; uint256 depositSe; uint256 depositBu; uint256 idx; } struct VoucherPaymentMethod { PaymentMethod paymentMethod; address addressTokenPrice; address addressTokenDeposits; } address private bosonRouterAddress; //address of the Boson Router contract address private cashierAddress; //address of the Cashier contract mapping(bytes32 => Promise) private promises; //promises to deliver goods or services mapping(address => uint256) private tokenNonces; //mapping between seller address and its own nonces. Every time seller creates supply ID it gets incremented. Used to avoid duplicate ID's mapping(uint256 => VoucherPaymentMethod) private paymentDetails; // tokenSupplyId to VoucherPaymentMethod bytes32[] private promiseKeys; mapping(uint256 => bytes32) private ordersPromise; //mapping between an order (supply a.k.a. VoucherSet) and a promise mapping(uint256 => VoucherStatus) private vouchersStatus; //recording the vouchers evolution //ID reqs mapping(uint256 => uint256) private typeCounters; //counter for ID of a particular type of NFT uint256 private constant MASK_TYPE = uint256(uint128(~0)) << 128; //the type mask in the upper 128 bits //1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 uint256 private constant MASK_NF_INDEX = uint128(~0); //the non-fungible index mask in the lower 128 //0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 uint256 private constant TYPE_NF_BIT = 1 << 255; //the first bit represents an NFT type //1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 uint256 private typeId; //base token type ... 127-bits cover 1.701411835*10^38 types (not differentiating between FTs and NFTs) /* Token IDs: Fungibles: 0, followed by 127-bit FT type ID, in the upper 128 bits, followed by 0 in lower 128-bits <0><uint127: base token id><uint128: 0> Non-fungible VoucherSets (supply tokens): 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by 0 in lower 128-bits <1><uint127: base token id><uint128: 0 Non-fungible vouchers: 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by a 1-based index of an NFT token ID. <1><uint127: base token id><uint128: index of non-fungible> */ uint256 private complainPeriod; uint256 private cancelFaultPeriod; event LogPromiseCreated( bytes32 indexed _promiseId, uint256 indexed _nonce, address indexed _seller, uint256 _validFrom, uint256 _validTo, uint256 _idx ); event LogVoucherCommitted( uint256 indexed _tokenIdSupply, uint256 _tokenIdVoucher, address _issuer, address _holder, bytes32 _promiseId ); event LogVoucherRedeemed( uint256 _tokenIdVoucher, address _holder, bytes32 _promiseId ); event LogVoucherRefunded(uint256 _tokenIdVoucher); event LogVoucherComplain(uint256 _tokenIdVoucher); event LogVoucherFaultCancel(uint256 _tokenIdVoucher); event LogExpirationTriggered(uint256 _tokenIdVoucher, address _triggeredBy); event LogFinalizeVoucher(uint256 _tokenIdVoucher, address _triggeredBy); event LogBosonRouterSet(address _newBosonRouter, address _triggeredBy); event LogCashierSet(address _newCashier, address _triggeredBy); event LogVoucherTokenContractSet(address _newTokenContract, address _triggeredBy); event LogVoucherSetTokenContractSet(address _newTokenContract, address _triggeredBy); event LogComplainPeriodChanged( uint256 _newComplainPeriod, address _triggeredBy ); event LogCancelFaultPeriodChanged( uint256 _newCancelFaultPeriod, address _triggeredBy ); event LogVoucherSetFaultCancel(uint256 _tokenIdSupply, address _issuer); event LogFundsReleased( uint256 _tokenIdVoucher, uint8 _type //0 .. payment, 1 .. deposits ); /** * @notice Checks that only the BosonRouter contract can call a function */ modifier onlyFromRouter() { require(msg.sender == bosonRouterAddress, "UNAUTHORIZED_BR"); _; } /** * @notice Checks that only the Cashier contract can call a function */ modifier onlyFromCashier() { require(msg.sender == cashierAddress, "UNAUTHORIZED_C"); _; } /** * @notice Checks that only the owver of the specified voucher can call a function */ modifier onlyVoucherOwner(uint256 _tokenIdVoucher, address _sender) { //check authorization require( IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher) == _sender, "UNAUTHORIZED_V" ); _; } modifier notZeroAddress(address _addressToCheck) { require(_addressToCheck != address(0), "0A"); _; } /** * @notice Construct and initialze the contract. Iniialises associated contract addresses, the complain period, and the cancel or fault period * @param _bosonRouterAddress address of the associated BosonRouter contract * @param _cashierAddress address of the associated Cashier contract * @param _voucherSetTokenAddress address of the associated ERC1155 contract instance * @param _voucherTokenAddress address of the associated ERC721 contract instance */ constructor(address _bosonRouterAddress, address _cashierAddress, address _voucherSetTokenAddress, address _voucherTokenAddress) notZeroAddress(_bosonRouterAddress) notZeroAddress(_cashierAddress) notZeroAddress(_voucherSetTokenAddress) notZeroAddress(_voucherTokenAddress) { bosonRouterAddress = _bosonRouterAddress; cashierAddress = _cashierAddress; voucherSetTokenAddress = _voucherSetTokenAddress; voucherTokenAddress = _voucherTokenAddress; complainPeriod = 7 * 1 days; cancelFaultPeriod = 7 * 1 days; } /** * @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency. * Only BR contract is in control of this function. */ function pause() external override onlyFromRouter { _pause(); } /** * @notice Unpause the process of interaction with voucherID's (ERC-721). * Only BR contract is in control of this function. */ function unpause() external override onlyFromRouter { _unpause(); } /** * @notice Creating a new promise for goods or services. * Can be reused, e.g. for making different batches of these (in the future). * @param _seller seller of the promise * @param _validFrom Start of valid period * @param _validTo End of valid period * @param _price Price (payment amount) * @param _depositSe Seller's deposit * @param _depositBu Buyer's deposit */ function createTokenSupplyId( address _seller, uint256 _validFrom, uint256 _validTo, uint256 _price, uint256 _depositSe, uint256 _depositBu, uint256 _quantity ) external override nonReentrant onlyFromRouter returns (uint256) { require(_quantity > 0, "INVALID_QUANTITY"); // solhint-disable-next-line not-rely-on-time require(_validTo >= block.timestamp + 5 minutes, "INVALID_VALIDITY_TO"); require(_validTo >= _validFrom.add(5 minutes), "VALID_FROM_MUST_BE_AT_LEAST_5_MINUTES_LESS_THAN_VALID_TO"); bytes32 key; key = keccak256( abi.encodePacked(_seller, tokenNonces[_seller]++, _validFrom, _validTo, address(this)) ); if (promiseKeys.length > 0) { require( promiseKeys[promises[key].idx] != key, "PROMISE_ALREADY_EXISTS" ); } promises[key] = Promise({ promiseId: key, nonce: tokenNonces[_seller], seller: _seller, validFrom: _validFrom, validTo: _validTo, price: _price, depositSe: _depositSe, depositBu: _depositBu, idx: promiseKeys.length }); promiseKeys.push(key); emit LogPromiseCreated( key, tokenNonces[_seller], _seller, _validFrom, _validTo, promiseKeys.length - 1 ); return createOrder(_seller, key, _quantity); } /** * @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set. * @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to * @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN * @param _tokenPrice token address which will hold the funds for the price of the voucher * @param _tokenDeposits token address which will hold the funds for the deposits of the voucher */ function createPaymentMethod( uint256 _tokenIdSupply, PaymentMethod _paymentMethod, address _tokenPrice, address _tokenDeposits ) external override onlyFromRouter { paymentDetails[_tokenIdSupply] = VoucherPaymentMethod({ paymentMethod: _paymentMethod, addressTokenPrice: _tokenPrice, addressTokenDeposits: _tokenDeposits }); } /** * @notice Create an order for offering a certain quantity of an asset * This creates a listing in a marketplace, technically as an ERC-1155 non-fungible token with supply. * @param _seller seller of the promise * @param _promiseId ID of a promise (simplified into asset for demo) * @param _quantity Quantity of assets on offer */ function createOrder( address _seller, bytes32 _promiseId, uint256 _quantity ) private returns (uint256) { //create & assign a new non-fungible type typeId++; uint256 tokenIdSupply = TYPE_NF_BIT | (typeId << 128); //upper bit is 1, followed by sequence, leaving lower 128-bits as 0; ordersPromise[tokenIdSupply] = _promiseId; IVoucherSets(voucherSetTokenAddress).mint( _seller, tokenIdSupply, _quantity, "" ); return tokenIdSupply; } /** * @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder * @param _tokenIdSupply ID of the supply token (ERC-1155) * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) * @param _paymentMethod method being used for that particular order that needs to be fulfilled */ function fillOrder( uint256 _tokenIdSupply, address _issuer, address _holder, PaymentMethod _paymentMethod ) external override onlyFromRouter nonReentrant { require(_doERC721HolderCheck(_issuer, _holder, _tokenIdSupply), "UNSUPPORTED_ERC721_RECEIVED"); PaymentMethod paymentMethod = getVoucherPaymentMethod(_tokenIdSupply); //checks require(paymentMethod == _paymentMethod, "Incorrect Payment Method"); checkOrderFillable(_tokenIdSupply, _issuer, _holder); //close order uint256 voucherTokenId = extract721(_issuer, _holder, _tokenIdSupply); emit LogVoucherCommitted( _tokenIdSupply, voucherTokenId, _issuer, _holder, getPromiseIdFromVoucherId(voucherTokenId) ); } /** * @notice Check if holder is a contract that supports ERC721 * @dev ERC-721 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0-rc.0/contracts/token/ERC721/ERC721.sol * @param _from Address of sender * @param _to Address of recipient * @param _tokenId ID of the token */ function _doERC721HolderCheck( address _from, address _to, uint256 _tokenId ) internal returns (bool) { if (_to.isContract()) { try IERC721Receiver(_to).onERC721Received(_msgSender(), _from, _tokenId, "") returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("UNSUPPORTED_ERC721_RECEIVED"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @notice Check order is fillable * @dev Will throw if checks don't pass * @param _tokenIdSupply ID of the supply token * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) */ function checkOrderFillable( uint256 _tokenIdSupply, address _issuer, address _holder ) internal view notZeroAddress(_holder) { require(_tokenIdSupply != 0, "UNSPECIFIED_ID"); require( IVoucherSets(voucherSetTokenAddress).balanceOf(_issuer, _tokenIdSupply) > 0, "OFFER_EMPTY" ); bytes32 promiseKey = ordersPromise[_tokenIdSupply]; require( promises[promiseKey].validTo >= block.timestamp, "OFFER_EXPIRED" ); } /** * @notice Extract a standard non-fungible token ERC-721 from a supply stored in ERC-1155 * @dev Token ID is derived following the same principles for both ERC-1155 and ERC-721 * @param _issuer The address of the token issuer * @param _to The address of the token holder * @param _tokenIdSupply ID of the token type * @return ID of the voucher token */ function extract721( address _issuer, address _to, uint256 _tokenIdSupply ) internal returns (uint256) { IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, 1); // This is hardcoded as 1 on purpose //calculate tokenId uint256 voucherTokenId = _tokenIdSupply | ++typeCounters[_tokenIdSupply]; //set status vouchersStatus[voucherTokenId].status = determineStatus( vouchersStatus[voucherTokenId].status, VoucherState.COMMIT ); vouchersStatus[voucherTokenId].isPaymentReleased = false; vouchersStatus[voucherTokenId].isDepositsReleased = false; //mint voucher NFT as ERC-721 IVouchers(voucherTokenAddress).mint(_to, voucherTokenId); return voucherTokenId; } /* solhint-disable */ /** * @notice Redemption of the vouchers promise * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function redeem(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { //check status require( isStateCommitted(vouchersStatus[_tokenIdVoucher].status), "ALREADY_PROCESSED" ); //check validity period isInValidityPeriod(_tokenIdVoucher); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp; vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.REDEEM ); emit LogVoucherRedeemed( _tokenIdVoucher, _messageSender, tPromise.promiseId ); } // // // // // // // // // UNHAPPY PATH // // // // // // // // /** * @notice Refunding a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function refund(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { require( isStateCommitted(vouchersStatus[_tokenIdVoucher].status), "INAPPLICABLE_STATUS" ); //check validity period isInValidityPeriod(_tokenIdVoucher); vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp; vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.REFUND ); emit LogVoucherRefunded(_tokenIdVoucher); } /** * @notice Issue a complaint for a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function complain(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.COMPLAIN); } /** * @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender) external override onlyFromRouter whenNotPaused { uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher); require( getSupplyHolder(tokenIdSupply) == _messageSender, "UNAUTHORIZED_COF" ); checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.CANCEL_FAULT); } /** * @notice Check if voucher status can be changed into desired new status. If yes, the waiting period is resetted, depending on what new status is. * @param _tokenIdVoucher ID of the voucher * @param _newStatus desired new status, can be {COF, COMPLAIN} */ function checkIfApplicableAndResetPeriod(uint256 _tokenIdVoucher, VoucherState _newStatus) internal { uint8 tStatus = vouchersStatus[_tokenIdVoucher].status; require( !isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED" ); string memory revertReasonAlready; string memory revertReasonExpired; if (_newStatus == VoucherState.COMPLAIN) { revertReasonAlready = "ALREADY_COMPLAINED"; revertReasonExpired = "COMPLAINPERIOD_EXPIRED"; } else { revertReasonAlready = "ALREADY_CANCELFAULT"; revertReasonExpired = "COFPERIOD_EXPIRED"; } require( !isStatus(tStatus, _newStatus), revertReasonAlready ); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; if ( isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus) ) { require( block.timestamp <= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod + cancelFaultPeriod, revertReasonExpired ); } else if (isStateExpired(tStatus)) { //if redeemed or refunded require( block.timestamp <= tPromise.validTo + complainPeriod + cancelFaultPeriod, revertReasonExpired ); } else if ( //if the opposite of what is the desired new state. When doing COMPLAIN we need to check if already in COF (and vice versa), since the waiting periods are different. // VoucherState.COMPLAIN has enum index value 2, while VoucherState.CANCEL_FAULT has enum index value 1. To check the opposite status we use transformation "% 2 + 1" which maps 2 to 1 and 1 to 2 isStatus(vouchersStatus[_tokenIdVoucher].status, VoucherState((uint8(_newStatus) % 2 + 1))) // making it VoucherState.COMPLAIN or VoucherState.CANCEL_FAULT (opposite to new status) ) { uint256 waitPeriod = _newStatus == VoucherState.COMPLAIN ? vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod : vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod; require( block.timestamp <= waitPeriod, revertReasonExpired ); } else if (_newStatus != VoucherState.COMPLAIN && isStateCommitted(tStatus)) { //if committed only (applicable only in COF) require( block.timestamp <= tPromise.validTo + complainPeriod + cancelFaultPeriod, "COFPERIOD_EXPIRED" ); } else { revert("INAPPLICABLE_STATUS"); } vouchersStatus[_tokenIdVoucher].status = determineStatus( tStatus, _newStatus ); if (_newStatus == VoucherState.COMPLAIN) { if (!isStatus(tStatus, VoucherState.CANCEL_FAULT)) { vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart = block .timestamp; //COF period starts } emit LogVoucherComplain(_tokenIdVoucher); } else { if (!isStatus(tStatus, VoucherState.COMPLAIN)) { vouchersStatus[_tokenIdVoucher].complainPeriodStart = block .timestamp; //complain period starts } emit LogVoucherFaultCancel(_tokenIdVoucher); } } /** * @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange. * @param _tokenIdSupply ID of the voucher set * @param _issuer owner of the voucher */ function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer) external override onlyFromRouter nonReentrant whenNotPaused returns (uint256) { require(getSupplyHolder(_tokenIdSupply) == _issuer, "UNAUTHORIZED_COF"); uint256 remQty = getRemQtyForSupply(_tokenIdSupply, _issuer); require(remQty > 0, "OFFER_EMPTY"); IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, remQty); emit LogVoucherSetFaultCancel(_tokenIdSupply, _issuer); return remQty; } // // // // // // // // // BACK-END PROCESS // // // // // // // // /** * @notice Mark voucher token that the payment was released * @param _tokenIdVoucher ID of the voucher token */ function setPaymentReleased(uint256 _tokenIdVoucher) external override onlyFromCashier { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); vouchersStatus[_tokenIdVoucher].isPaymentReleased = true; emit LogFundsReleased(_tokenIdVoucher, 0); } /** * @notice Mark voucher token that the deposits were released * @param _tokenIdVoucher ID of the voucher token */ function setDepositsReleased(uint256 _tokenIdVoucher) external override onlyFromCashier { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); vouchersStatus[_tokenIdVoucher].isDepositsReleased = true; emit LogFundsReleased(_tokenIdVoucher, 1); } /** * @notice Mark voucher token as expired * @param _tokenIdVoucher ID of the voucher token */ function triggerExpiration(uint256 _tokenIdVoucher) external override { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; require(tPromise.validTo < block.timestamp && isStateCommitted(vouchersStatus[_tokenIdVoucher].status),'INAPPLICABLE_STATUS'); vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.EXPIRE ); emit LogExpirationTriggered(_tokenIdVoucher, msg.sender); } /** * @notice Mark voucher token to the final status * @param _tokenIdVoucher ID of the voucher token */ function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external override { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); uint8 tStatus = vouchersStatus[_tokenIdVoucher].status; require(!isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED"); bool mark; Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; if (isStatus(tStatus, VoucherState.COMPLAIN)) { if (isStatus(tStatus, VoucherState.CANCEL_FAULT)) { //if COMPLAIN && COF: then final mark = true; } else if ( block.timestamp >= vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod ) { //if COMPLAIN: then final after cof period mark = true; } } else if ( isStatus(tStatus, VoucherState.CANCEL_FAULT) && block.timestamp >= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod ) { //if COF: then final after complain period mark = true; } else if ( isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus) ) { //if RDM/RFND NON_COMPLAIN: then final after complainPeriodStart + complainPeriod if ( block.timestamp >= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod ) { mark = true; } } else if (isStateExpired(tStatus)) { //if EXP NON_COMPLAIN: then final after validTo + complainPeriod if (block.timestamp >= tPromise.validTo + complainPeriod) { mark = true; } } require(mark, 'INAPPLICABLE_STATUS'); vouchersStatus[_tokenIdVoucher].status = determineStatus( tStatus, VoucherState.FINAL ); emit LogFinalizeVoucher(_tokenIdVoucher, msg.sender); } /* solhint-enable */ // // // // // // // // // UTILS // // // // // // // // /** * @notice Set the address of the new holder of a _tokenIdSupply on transfer * @param _tokenIdSupply _tokenIdSupply which will be transferred * @param _newSeller new holder of the supply */ function setSupplyHolderOnTransfer( uint256 _tokenIdSupply, address _newSeller ) external override onlyFromCashier { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; promises[promiseKey].seller = _newSeller; } /** * @notice Set the address of the Boson Router contract * @param _bosonRouterAddress The address of the BR contract */ function setBosonRouterAddress(address _bosonRouterAddress) external override onlyOwner whenPaused notZeroAddress(_bosonRouterAddress) { bosonRouterAddress = _bosonRouterAddress; emit LogBosonRouterSet(_bosonRouterAddress, msg.sender); } /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external override onlyOwner whenPaused notZeroAddress(_cashierAddress) { cashierAddress = _cashierAddress; emit LogCashierSet(_cashierAddress, msg.sender); } /** * @notice Set the address of the Vouchers token contract, an ERC721 contract * @param _voucherTokenAddress The address of the Vouchers token contract */ function setVoucherTokenAddress(address _voucherTokenAddress) external override onlyOwner notZeroAddress(_voucherTokenAddress) whenPaused { voucherTokenAddress = _voucherTokenAddress; emit LogVoucherTokenContractSet(_voucherTokenAddress, msg.sender); } /** * @notice Set the address of the Voucher Sets token contract, an ERC1155 contract * @param _voucherSetTokenAddress The address of the Vouchers token contract */ function setVoucherSetTokenAddress(address _voucherSetTokenAddress) external override onlyOwner notZeroAddress(_voucherSetTokenAddress) whenPaused { voucherSetTokenAddress = _voucherSetTokenAddress; emit LogVoucherSetTokenContractSet(_voucherSetTokenAddress, msg.sender); } /** * @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _complainPeriod the new value for complain period (in number of seconds) */ function setComplainPeriod(uint256 _complainPeriod) external override onlyOwner { complainPeriod = _complainPeriod; emit LogComplainPeriodChanged(_complainPeriod, msg.sender); } /** * @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds) */ function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external override onlyOwner { cancelFaultPeriod = _cancelFaultPeriod; emit LogCancelFaultPeriodChanged(_cancelFaultPeriod, msg.sender); } // // // // // // // // // GETTERS // // // // // // // // /** * @notice Get the promise ID at specific index * @param _idx Index in the array of promise keys * @return Promise ID */ function getPromiseKey(uint256 _idx) external view override returns (bytes32) { return promiseKeys[_idx]; } /** * @notice Get the supply token ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the supply token */ function getIdSupplyFromVoucher(uint256 _tokenIdVoucher) public pure override returns (uint256) { uint256 tokenIdSupply = _tokenIdVoucher & MASK_TYPE; require(tokenIdSupply !=0, "INEXISTENT_SUPPLY"); return tokenIdSupply; } /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher) public view override returns (bytes32) { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher); return promises[ordersPromise[tokenIdSupply]].promiseId; } /** * @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account * @param _tokenSupplyId Token supply ID * @param _tokenSupplyOwner holder of the Token Supply * @return remaining quantity */ function getRemQtyForSupply(uint256 _tokenSupplyId, address _tokenSupplyOwner) public view override returns (uint256) { return IVoucherSets(voucherSetTokenAddress).balanceOf(_tokenSupplyOwner, _tokenSupplyId); } /** * @notice Get all necessary funds for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit) */ function getOrderCosts(uint256 _tokenIdSupply) external view override returns ( uint256, uint256, uint256 ) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return ( promises[promiseKey].price, promises[promiseKey].depositSe, promises[promiseKey].depositBu ); } /** * @notice Get Buyer costs required to make an order for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Buyer's deposit) */ function getBuyerOrderCosts(uint256 _tokenIdSupply) external view override returns (uint256, uint256) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return (promises[promiseKey].price, promises[promiseKey].depositBu); } /** * @notice Get Seller deposit * @param _tokenIdSupply ID of the supply token * @return returns sellers deposit */ function getSellerDeposit(uint256 _tokenIdSupply) external view override returns (uint256) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return promises[promiseKey].depositSe; } /** * @notice Get the holder of a supply * @param _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise. * @return Address of the holder */ function getSupplyHolder(uint256 _tokenIdSupply) public view override returns (address) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return promises[promiseKey].seller; } /** * @notice Get promise data not retrieved by other accessor functions * @param _promiseKey ID of the promise * @return promise data not returned by other accessor methods */ function getPromiseData(bytes32 _promiseKey) external view override returns (bytes32, uint256, uint256, uint256, uint256 ) { Promise memory tPromise = promises[_promiseKey]; return (tPromise.promiseId, tPromise.nonce, tPromise.validFrom, tPromise.validTo, tPromise.idx); } /** * @notice Get the current status of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Status of the voucher (via enum) */ function getVoucherStatus(uint256 _tokenIdVoucher) external view override returns ( uint8, bool, bool, uint256, uint256 ) { return ( vouchersStatus[_tokenIdVoucher].status, vouchersStatus[_tokenIdVoucher].isPaymentReleased, vouchersStatus[_tokenIdVoucher].isDepositsReleased, vouchersStatus[_tokenIdVoucher].complainPeriodStart, vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart ); } /** * @notice Get the holder of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Address of the holder */ function getVoucherHolder(uint256 _tokenIdVoucher) external view override returns (address) { return IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher); } /** * @notice Get the address of the token where the price for the supply is held * @param _tokenIdSupply ID of the voucher supply token * @return Address of the token */ function getVoucherPriceToken(uint256 _tokenIdSupply) external view override returns (address) { return paymentDetails[_tokenIdSupply].addressTokenPrice; } /** * @notice Get the address of the token where the deposits for the supply are held * @param _tokenIdSupply ID of the voucher supply token * @return Address of the token */ function getVoucherDepositToken(uint256 _tokenIdSupply) external view override returns (address) { return paymentDetails[_tokenIdSupply].addressTokenDeposits; } /** * @notice Get the payment method for a particular _tokenIdSupply * @param _tokenIdSupply ID of the voucher supply token * @return payment method */ function getVoucherPaymentMethod(uint256 _tokenIdSupply) public view override returns (PaymentMethod) { return paymentDetails[_tokenIdSupply].paymentMethod; } /** * @notice Checks whether a voucher is in valid period for redemption (between start date and end date) * @param _tokenIdVoucher ID of the voucher token */ function isInValidityPeriod(uint256 _tokenIdVoucher) public view override returns (bool) { //check validity period Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; require(tPromise.validFrom <= block.timestamp, "INVALID_VALIDITY_FROM"); require(tPromise.validTo >= block.timestamp, "INVALID_VALIDITY_TO"); return true; } /** * @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred * @param _tokenIdVoucher ID of the voucher token */ function isVoucherTransferable(uint256 _tokenIdVoucher) external view override returns (bool) { return !(vouchersStatus[_tokenIdVoucher].isPaymentReleased || vouchersStatus[_tokenIdVoucher].isDepositsReleased); } /** * @notice Get address of the Boson Router to which this contract points * @return Address of the Boson Router contract */ function getBosonRouterAddress() external view override returns (address) { return bosonRouterAddress; } /** * @notice Get address of the Cashier contract to which this contract points * @return Address of the Cashier contract */ function getCashierAddress() external view override returns (address) { return cashierAddress; } /** * @notice Get the token nonce for a seller * @param _seller Address of the seller * @return The seller's nonce */ function getTokenNonce(address _seller) external view override returns (uint256) { return tokenNonces[_seller]; } /** * @notice Get the current type Id * @return type Id */ function getTypeId() external view override returns (uint256) { return typeId; } /** * @notice Get the complain period * @return complain period */ function getComplainPeriod() external view override returns (uint256) { return complainPeriod; } /** * @notice Get the cancel or fault period * @return cancel or fault period */ function getCancelFaultPeriod() external view override returns (uint256) { return cancelFaultPeriod; } /** * @notice Get the promise ID from a voucher set * @param _tokenIdSupply ID of the voucher token * @return ID of the promise */ function getPromiseIdFromSupplyId(uint256 _tokenIdSupply) external view override returns (bytes32) { return ordersPromise[_tokenIdSupply]; } /** * @notice Get the address of the Vouchers token contract, an ERC721 contract * @return Address of Vouchers contract */ function getVoucherTokenAddress() external view override returns (address) { return voucherTokenAddress; } /** * @notice Get the address of the VoucherSets token contract, an ERC155 contract * @return Address of VoucherSets contract */ function getVoucherSetTokenAddress() external view override returns (address) { return voucherSetTokenAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 () { _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.7.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.7.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol"; interface IVoucherSets is IERC1155, IERC1155MetadataURI { /** * @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency. * All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed. * There is special function for withdrawing funds if contract is paused. */ function pause() external; /** * @notice Unpause the Cashier && the Voucher Kernel contracts. * All functions related to creating new batch, requestVoucher or withdraw will be unpaused. */ function unpause() external; /** * @notice Mint an amount of a desired token * Currently no restrictions as to who is allowed to mint - so, it is external. * @dev ERC-1155 * @param _to owner of the minted token * @param _tokenId ID of the token to be minted * @param _value Amount of the token to be minted * @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract */ function mint( address _to, uint256 _tokenId, uint256 _value, bytes calldata _data ) external; /** * @notice Burn an amount of tokens with the given ID * @dev ERC-1155 * @param _account Account which owns the token * @param _tokenId ID of the token * @param _value Amount of the token */ function burn( address _account, uint256 _tokenId, uint256 _value ) external; /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the Voucher Kernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view returns (address); /** * @notice Get the address of Cashier contract * @return Address of Cashier address */ function getCashierAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol"; interface IVouchers is IERC721, IERC721Metadata { /** * @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency. * All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed. * There is special function for withdrawing funds if contract is paused. */ function pause() external; /** * @notice Unpause the Cashier && the Voucher Kernel contracts. * All functions related to creating new batch, requestVoucher or withdraw will be unpaused. */ function unpause() external; /** * @notice Function to mint tokens. * @dev ERC-721 * @param _to The address that will receive the minted tokens. * @param _tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _tokenId) external returns (bool); /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the Voucher Kernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view returns (address); /** * @notice Get the address of Cashier contract * @return Address of Cashier address */ function getCashierAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "./../UsingHelpers.sol"; interface IVoucherKernel { /** * @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency. * Only Cashier contract is in control of this function. */ function pause() external; /** * @notice Unpause the process of interaction with voucherID's (ERC-721). * Only Cashier contract is in control of this function. */ function unpause() external; /** * @notice Creating a new promise for goods or services. * Can be reused, e.g. for making different batches of these (but not in prototype). * @param _seller seller of the promise * @param _validFrom Start of valid period * @param _validTo End of valid period * @param _price Price (payment amount) * @param _depositSe Seller's deposit * @param _depositBu Buyer's deposit */ function createTokenSupplyId( address _seller, uint256 _validFrom, uint256 _validTo, uint256 _price, uint256 _depositSe, uint256 _depositBu, uint256 _quantity ) external returns (uint256); /** * @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set. * @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to * @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN * @param _tokenPrice token address which will hold the funds for the price of the voucher * @param _tokenDeposits token address which will hold the funds for the deposits of the voucher */ function createPaymentMethod( uint256 _tokenIdSupply, PaymentMethod _paymentMethod, address _tokenPrice, address _tokenDeposits ) external; /** * @notice Mark voucher token that the payment was released * @param _tokenIdVoucher ID of the voucher token */ function setPaymentReleased(uint256 _tokenIdVoucher) external; /** * @notice Mark voucher token that the deposits were released * @param _tokenIdVoucher ID of the voucher token */ function setDepositsReleased(uint256 _tokenIdVoucher) external; /** * @notice Redemption of the vouchers promise * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function redeem(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Refunding a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function refund(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Issue a complain for a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function complain(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher set (seller) */ function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange. * @param _tokenIdSupply ID of the voucher * @param _issuer owner of the voucher */ function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer) external returns (uint256); /** * @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder * @param _tokenIdSupply ID of the supply token (ERC-1155) * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) * @param _paymentMethod method being used for that particular order that needs to be fulfilled */ function fillOrder( uint256 _tokenIdSupply, address _issuer, address _holder, PaymentMethod _paymentMethod ) external; /** * @notice Mark voucher token as expired * @param _tokenIdVoucher ID of the voucher token */ function triggerExpiration(uint256 _tokenIdVoucher) external; /** * @notice Mark voucher token to the final status * @param _tokenIdVoucher ID of the voucher token */ function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external; /** * @notice Set the address of the new holder of a _tokenIdSupply on transfer * @param _tokenIdSupply _tokenIdSupply which will be transferred * @param _newSeller new holder of the supply */ function setSupplyHolderOnTransfer( uint256 _tokenIdSupply, address _newSeller ) external; /** * @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds) */ function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external; /** * @notice Set the address of the Boson Router contract * @param _bosonRouterAddress The address of the BR contract */ function setBosonRouterAddress(address _bosonRouterAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Set the address of the Vouchers token contract, an ERC721 contract * @param _voucherTokenAddress The address of the Vouchers token contract */ function setVoucherTokenAddress(address _voucherTokenAddress) external; /** * @notice Set the address of the Voucher Sets token contract, an ERC1155 contract * @param _voucherSetTokenAddress The address of the Voucher Sets token contract */ function setVoucherSetTokenAddress(address _voucherSetTokenAddress) external; /** * @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _complainPeriod the new value for complain period (in number of seconds) */ function setComplainPeriod(uint256 _complainPeriod) external; /** * @notice Get the promise ID at specific index * @param _idx Index in the array of promise keys * @return Promise ID */ function getPromiseKey(uint256 _idx) external view returns (bytes32); /** * @notice Get the address of the token where the price for the supply is held * @param _tokenIdSupply ID of the voucher token * @return Address of the token */ function getVoucherPriceToken(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get the address of the token where the deposits for the supply are held * @param _tokenIdSupply ID of the voucher token * @return Address of the token */ function getVoucherDepositToken(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get Buyer costs required to make an order for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Buyer's deposit) */ function getBuyerOrderCosts(uint256 _tokenIdSupply) external view returns (uint256, uint256); /** * @notice Get Seller deposit * @param _tokenIdSupply ID of the supply token * @return returns sellers deposit */ function getSellerDeposit(uint256 _tokenIdSupply) external view returns (uint256); /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getIdSupplyFromVoucher(uint256 _tokenIdVoucher) external pure returns (uint256); /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher) external view returns (bytes32); /** * @notice Get all necessary funds for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit) */ function getOrderCosts(uint256 _tokenIdSupply) external view returns ( uint256, uint256, uint256 ); /** * @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account * @param _tokenSupplyId Token supply ID * @param _owner holder of the Token Supply * @return remaining quantity */ function getRemQtyForSupply(uint256 _tokenSupplyId, address _owner) external view returns (uint256); /** * @notice Get the payment method for a particular _tokenIdSupply * @param _tokenIdSupply ID of the voucher supply token * @return payment method */ function getVoucherPaymentMethod(uint256 _tokenIdSupply) external view returns (PaymentMethod); /** * @notice Get the current status of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Status of the voucher (via enum) */ function getVoucherStatus(uint256 _tokenIdVoucher) external view returns ( uint8, bool, bool, uint256, uint256 ); /** * @notice Get the holder of a supply * @param _tokenIdSupply _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise. * @return Address of the holder */ function getSupplyHolder(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get the holder of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Address of the holder */ function getVoucherHolder(uint256 _tokenIdVoucher) external view returns (address); /** * @notice Checks whether a voucher is in valid period for redemption (between start date and end date) * @param _tokenIdVoucher ID of the voucher token */ function isInValidityPeriod(uint256 _tokenIdVoucher) external view returns (bool); /** * @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred * @param _tokenIdVoucher ID of the voucher token */ function isVoucherTransferable(uint256 _tokenIdVoucher) external view returns (bool); /** * @notice Get address of the Boson Router contract to which this contract points * @return Address of the Boson Router contract */ function getBosonRouterAddress() external view returns (address); /** * @notice Get address of the Cashier contract to which this contract points * @return Address of the Cashier contract */ function getCashierAddress() external view returns (address); /** * @notice Get the token nonce for a seller * @param _seller Address of the seller * @return The seller's */ function getTokenNonce(address _seller) external view returns (uint256); /** * @notice Get the current type Id * @return type Id */ function getTypeId() external view returns (uint256); /** * @notice Get the complain period * @return complain period */ function getComplainPeriod() external view returns (uint256); /** * @notice Get the cancel or fault period * @return cancel or fault period */ function getCancelFaultPeriod() external view returns (uint256); /** * @notice Get promise data not retrieved by other accessor functions * @param _promiseKey ID of the promise * @return promise data not returned by other accessor methods */ function getPromiseData(bytes32 _promiseKey) external view returns ( bytes32, uint256, uint256, uint256, uint256 ); /** * @notice Get the promise ID from a voucher set * @param _tokenIdSupply ID of the voucher token * @return ID of the promise */ function getPromiseIdFromSupplyId(uint256 _tokenIdSupply) external view returns (bytes32); /** * @notice Get the address of the Vouchers token contract, an ERC721 contract * @return Address of Vouchers contract */ function getVoucherTokenAddress() external view returns (address); /** * @notice Get the address of the VoucherSets token contract, an ERC155 contract * @return Address of VoucherSets contract */ function getVoucherSetTokenAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; // Those are the payment methods we are using throughout the system. // Depending on how to user choose to interact with it's funds we store the method, so we could distribute its tokens afterwise enum PaymentMethod { ETHETH, ETHTKN, TKNETH, TKNTKN } enum VoucherState {FINAL, CANCEL_FAULT, COMPLAIN, EXPIRE, REFUND, REDEEM, COMMIT} /* Status of the voucher in 8 bits: [6:COMMITTED] [5:REDEEMED] [4:REFUNDED] [3:EXPIRED] [2:COMPLAINED] [1:CANCELORFAULT] [0:FINAL] */ uint8 constant ONE = 1; struct VoucherDetails { uint256 tokenIdSupply; uint256 tokenIdVoucher; address issuer; address holder; uint256 price; uint256 depositSe; uint256 depositBu; uint256 price2pool; uint256 deposit2pool; uint256 price2issuer; uint256 deposit2issuer; uint256 price2holder; uint256 deposit2holder; PaymentMethod paymentMethod; VoucherStatus currStatus; } struct VoucherStatus { uint8 status; bool isPaymentReleased; bool isDepositsReleased; uint256 complainPeriodStart; uint256 cancelFaultPeriodStart; } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state. * @param _status current status of a voucher. */ function isStateCommitted(uint8 _status) pure returns (bool) { return _status == determineStatus(0, VoucherState.COMMIT); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in RedemptionSigned state. * @param _status current status of a voucher. */ function isStateRedemptionSigned(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REDEEM); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Refunded state. * @param _status current status of a voucher. */ function isStateRefunded(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REFUND); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Expired state. * @param _status current status of a voucher. */ function isStateExpired(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.EXPIRE); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks the current status a voucher is at. * @param _status current status of a voucher. * @param _idx status to compare. */ function isStatus(uint8 _status, VoucherState _idx) pure returns (bool) { return (_status >> uint8(_idx)) & ONE == 1; } /** * @notice Set voucher status. * @param _status previous status. * @param _changeIdx next status. */ function determineStatus(uint8 _status, VoucherState _changeIdx) pure returns (uint8) { return _status | (ONE << uint8(_changeIdx)); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); }
Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder _tokenIdSupply ID of the supply token (ERC-1155) _issuer Address of the token's issuer _holder Address of the recipient of the voucher (ERC-721) _paymentMethod method being used for that particular order that needs to be fulfilled/checksclose order
function fillOrder( uint256 _tokenIdSupply, address _issuer, address _holder, PaymentMethod _paymentMethod ) external override onlyFromRouter nonReentrant { require(_doERC721HolderCheck(_issuer, _holder, _tokenIdSupply), "UNSUPPORTED_ERC721_RECEIVED"); PaymentMethod paymentMethod = getVoucherPaymentMethod(_tokenIdSupply); require(paymentMethod == _paymentMethod, "Incorrect Payment Method"); checkOrderFillable(_tokenIdSupply, _issuer, _holder); uint256 voucherTokenId = extract721(_issuer, _holder, _tokenIdSupply); emit LogVoucherCommitted( _tokenIdSupply, voucherTokenId, _issuer, _holder, getPromiseIdFromVoucherId(voucherTokenId) ); }
40,203
./full_match/42220/0xDE44cF472465C8402c9C2d64439574d0407496C3/sources/contracts/EternalPool.sol
Transfer reward tokens. EMERGENCY ONLY. return Success./
function emergencyTransfer(address _to) external onlyOwner returns (bool) { if (DINO == REWARD) { return REWARD.transfer(_to, REWARD.balanceOf(address(this)) - stakedDinos); return REWARD.transfer(_to, REWARD.balanceOf(address(this))); } }
16,333,974
./full_match/1/0x401253BD4333014C73D81A308166AdE05d954c2F/sources/LosMuertosClub.sol
fetch the api endpoint
function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; }
16,582,019
./partial_match/3/0xB205ed9d4822C48748194e2Aa8EdCf53d2eB6e84/sources/PPToken.sol
------------------------------------------------------------------------ Get the token balance for account tokenOwner ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; }
5,194,490
/** *Submitted for verification at Etherscan.io on 2020-12-24 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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); } abstract contract Context { function _msgSender() internal view returns (address) { return msg.sender; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string public name; string public symbol; uint8 public decimals; 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 override returns (bool) { _transfer(_msgSender(), 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) { require((allowance(_msgSender(), spender) == 0) || (amount == 0), "ERC20: change allowance use increaseAllowance or decreaseAllowance instead"); _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 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 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 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 { 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 { 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 { 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 { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @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 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 whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev Same structure as Pausable, solely for mint function; */ contract MintPausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event MintPaused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event MintUnpaused(address account); bool private _mintPaused; /** * @dev Initializes the contract in unpaused state. */ constructor() internal { _mintPaused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function mintPaused() public view returns (bool) { return _mintPaused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenMintNotPaused() { require(!_mintPaused, "MintPausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenMintPaused() { require(_mintPaused, "MintPausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _mintPause() internal whenMintNotPaused { _mintPaused = true; emit MintPaused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _mintUnpause() internal whenMintPaused { _mintPaused = false; emit MintUnpaused(_msgSender()); } } contract SperaxToken is ERC20, Pausable, MintPausable, Ownable { event BlockTransfer(address indexed account); event AllowTransfer(address indexed account); /** * @dev Emitted when an account is set mintabl */ event Mintable(address account); /** * @dev Emitted when an account is set unmintable */ event Unmintable(address account); modifier onlyMintableGroup() { require(mintableGroup[_msgSender()], "SPA: not in mintable group"); _; } struct TimeLock { uint256 releaseTime; uint256 amount; } mapping(address => TimeLock) private _timelock; // @dev mintable group mapping(address => bool) public mintableGroup; // @dev record mintable accounts address [] public mintableAccounts; /** * @dev Initialize the contract give all tokens to the deployer */ constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _initialSupply) public { name = _name; symbol = _symbol; decimals = _decimals; _mint(_msgSender(), _initialSupply * (10 ** uint256(_decimals))); } /** * @dev set or remove address to mintable group */ function setMintable(address account, bool allow) public onlyOwner { mintableGroup[account] = allow; mintableAccounts.push(account); if (allow) { emit Mintable(account); } else { emit Unmintable(account); } } /** * @dev remove all mintable account */ function revokeAllMintable() public onlyOwner { uint n = mintableAccounts.length; for (uint i=0;i<n;i++) { delete mintableGroup[mintableAccounts[i]]; } delete mintableAccounts; } /** * @dev mint SPA when USDs is burnt */ function mintForUSDs(address account, uint256 amount) whenMintNotPaused onlyMintableGroup external { _mint(account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _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 { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "SperaxToken: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev View `account` locked information */ function timelockOf(address account) public view returns(uint256 releaseTime, uint256 amount) { TimeLock memory timelock = _timelock[account]; return (timelock.releaseTime, timelock.amount); } /** * @dev Transfer to the "recipient" some specified 'amount' that is locked until "releaseTime" * @notice only Owner call */ function transferWithLock(address recipient, uint256 amount, uint256 releaseTime) public onlyOwner returns (bool) { require(recipient != address(0), "SperaxToken: transferWithLock to zero address"); require(releaseTime > block.timestamp, "SperaxToken: release time before lock time"); require(_timelock[recipient].releaseTime == 0, "SperaxToken: already locked"); TimeLock memory timelock = TimeLock({ releaseTime : releaseTime, amount : amount }); _timelock[recipient] = timelock; _transfer(_msgSender(), recipient, amount); return true; } /** * @dev Release the specified `amount` of locked amount * @notice only Owner call */ function release(address account, uint256 releaseAmount) public onlyOwner { require(account != address(0), "SperaxToken: release zero address"); TimeLock storage timelock = _timelock[account]; timelock.amount = timelock.amount.sub(releaseAmount); if(timelock.amount == 0) { timelock.releaseTime = 0; } } /** * @dev Triggers stopped state. * @notice only Owner call */ function pause() public onlyOwner { _pause(); } /** * @dev Returns to normal state. * @notice only Owner call */ function unpause() public onlyOwner { _unpause(); } /** * @dev Triggers stopped state of mint. * @notice only Owner call */ function mintPause() public onlyOwner { _mintPause(); } /** * @dev Returns to normal state of mint. * @notice only Owner call */ function mintUnpause() public onlyOwner { _mintUnpause(); } /** * @dev Batch transfer amount to recipient * @notice that excessive gas consumption causes transaction revert */ function batchTransfer(address[] memory recipients, uint256[] memory amounts) public { require(recipients.length > 0, "SperaxToken: least one recipient address"); require(recipients.length == amounts.length, "SperaxToken: number of recipient addresses does not match the number of tokens"); for(uint256 i = 0; i < recipients.length; ++i) { _transfer(_msgSender(), recipients[i], amounts[i]); } } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. * - accounts must not trigger the locked `amount` during the locked period. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { require(!paused(), "SperaxToken: token transfer while paused"); // Check whether the locked amount is triggered TimeLock storage timelock = _timelock[from]; if(timelock.releaseTime != 0 && balanceOf(from).sub(amount) < timelock.amount) { require(block.timestamp >= timelock.releaseTime, "SperaxToken: current time is before from account release time"); // Update the locked `amount` if the current time reaches the release time timelock.amount = balanceOf(from).sub(amount); if(timelock.amount == 0) { timelock.releaseTime = 0; } } super._beforeTokenTransfer(from, to, amount); } }
mint SPA when USDs is burnt/
function mintForUSDs(address account, uint256 amount) whenMintNotPaused onlyMintableGroup external { _mint(account, amount); }
430,887
./partial_match/1/0xdefac16715671b7b6aeeFE012125f1E19Ee4b7d7/sources/_PrimeToken.sol
Base method for transferring tokens./
function _transfer( address from, address to, uint256 value ) internal { expect(to != address(0), ERROR_INVALID_ADDRESS); expect(!isFrozen(from), ERROR_FROZEN); expect(!isFrozen(to), ERROR_FROZEN); _unlock(from); expect(value <= unlockedBalanceOf(from), ERROR_INSUFFICIENT_BALANCE); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); emit Transfer(from, to, value); }
2,630,711
//Address: 0x32ec2e6967687825123c5c0f30c18e2c47708df1 //Contract name: TokenCampaign //Balance: 0 Ether //Verification Date: 12/7/2017 //Transacion Count: 971 // CODE STARTS HERE // This is the code fot the smart contract // used for the Realisto ICO // // @author: Pavel Metelitsyn // September 2017 pragma solidity ^0.4.15; // import "./library.sol"; /** * @title SafeMath * @dev Math operations with safety checks that throw on error * * Source: Zeppelin Solidity */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function percent(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c / 100; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ /* from OpenZeppelin library */ /* https://github.com/OpenZeppelin/zeppelin-solidity */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } //import "./RealistoToken.sol"; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data); } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'MMT_0.1'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract RealistoToken is MiniMeToken { // we use this variable to store the number of the finalization block uint256 public checkpointBlock; // address which is allowed to trigger tokens generation address public mayGenerateAddr; // flag bool tokenGenerationEnabled; //<- added after first audit modifier mayGenerate() { require ( (msg.sender == mayGenerateAddr) && (tokenGenerationEnabled == true) ); //<- added after first audit _; } // Constructor function RealistoToken(address _tokenFactory) MiniMeToken( _tokenFactory, 0x0, 0, "Realisto Token", 18, // decimals "REA", // SHOULD TRANSFERS BE ENABLED? -- NO false){ tokenGenerationEnabled = true; controller = msg.sender; mayGenerateAddr = controller; } function setGenerateAddr(address _addr) onlyController{ // we can appoint an address to be allowed to generate tokens require( _addr != 0x0 ); mayGenerateAddr = _addr; } /// @notice this is default function called when ETH is send to this contract /// we use the campaign contract for selling tokens function () payable { revert(); } /// @notice This function is copy-paste of the generateTokens of the original MiniMi contract /// except it uses mayGenerate modifier (original uses onlyController) /// this is because we don't want the Sale campaign contract to be the controller function generate_token_for(address _addrTo, uint _amount) mayGenerate returns (bool) { //balances[_addr] += _amount; uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_addrTo); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_addrTo], previousBalanceTo + _amount); Transfer(0, _addrTo, _amount); return true; } // overwrites the original function function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { revert(); generate_token_for(_owner, _amount); } // permanently disables generation of new tokens function finalize() mayGenerate { tokenGenerationEnabled = false; //<- added after first audit checkpointBlock = block.number; } } //import "./LinearTokenVault.sol"; // simple time locked vault allows controlled extraction of tokens during a period of time // Controlled is implemented in MiniMeToken.sol contract TokenVault is Controlled { using SafeMath for uint256; //address campaignAddr; TokenCampaign campaign; //uint256 tUnlock = 0; uint256 tDuration; uint256 tLock = 12 * 30 * (1 days); // 12 months MiniMeToken token; uint256 extracted = 0; event Extract(address indexed _to, uint256 _amount); function TokenVault( address _tokenAddress, address _campaignAddress, uint256 _tDuration ) { require( _tDuration > 0); tDuration = _tDuration; //campaignAddr = _campaignAddress; token = RealistoToken(_tokenAddress); campaign = TokenCampaign(_campaignAddress); } /// WE DONT USE IT ANYMORE /// sale campaign calls this function to set the time lock /// @param _tUnlock - Unix timestamp of the first date /// on which tokens become available //function setTimeLock(uint256 _tUnlock){ // prevent change of the timestamp by anybody other than token sale contract // once unlock time is set it cannot be changed //require( (msg.sender == campaignAddr) && (tUnlock == 0)); // tUnlock = _tUnlock; //} /// @notice Send all available tokens to a given address function extract(address _to) onlyController { require (_to != 0x0); uint256 available = availableNow(); require( available > 0 ); extracted = extracted.add(available); assert( token.transfer(_to, available) ); Extract(_to, available); } // returns amount of tokens held in this vault function balance() returns (uint256){ return token.balanceOf(address(this)); } function get_unlock_time() returns (uint256){ return campaign.tFinalized() + tLock; } // returns amount of tokens available for extraction now function availableNow() returns (uint256){ uint256 tUnlock = get_unlock_time(); uint256 tNow = now; // if before unlock time or unlock time is not set => 0 is available if (tNow < tUnlock ) { return 0; } uint256 remaining = balance(); // if after longer than tDuration since unlock time => everything that is left is available if (tNow > tUnlock + tDuration) { return remaining; } // otherwise: // compute how many extractions remaining based on time // time delta uint256 t = (tNow.sub(tUnlock)).mul(remaining.add(extracted)); return (t.div(tDuration)).sub(extracted); } } contract rea_token_interface{ uint8 public decimals; function generate_token_for(address _addr,uint _amount) returns (bool); function finalize(); } // Controlled is implemented in MiniMeToken.sol contract TokenCampaign is Controlled{ using SafeMath for uint256; // this is our token rea_token_interface public token; TokenVault teamVault; /////////////////////////////////// // // constants related to token sale // after slae ends, additional tokens will be generated // according to the following rules, // where 100% correspond to the number of sold tokens // percent of tokens to be generated for the team uint256 public constant PRCT_TEAM = 10; // percent of tokens to be generated for bounty uint256 public constant PRCT_BOUNTY = 3; // we keep ETH in the contract until the sale is finalized // however a small part of every contribution goes to opperational costs // percent of ETH going to operational account uint256 public constant PRCT_ETH_OP = 10; uint8 public constant decimals = 18; uint256 public constant scale = (uint256(10) ** decimals); // how many tokens for one ETH // we may adjust this number before deployment based on the market conditions uint256 public constant baseRate = 330; //<-- unscaled // we want to limit the number of available tokens during the bonus stage // payments during the bonus stage will not be accepted after the TokenTreshold is reached or exceeded // we may adjust this number before deployment based on the market conditions uint256 public constant bonusTokenThreshold = 2000000 * scale ; //<--- new // minmal contribution, Wei uint256 public constant minContribution = (1 ether) / 100; // bonus structure, Wei uint256 public constant bonusMinContribution = (1 ether) /10; // uint256 public constant bonusAdd = 99; // + 30% <-- corrected uint256 public constant stage_1_add = 50;// + 15,15% <-- corrected uint256 public constant stage_2_add = 33;// + 10% uint256 public constant stage_3_add = 18;// + 5,45% //////////////////////////////////////////////////////// // // folowing addresses need to be set in the constructor // we also have setter functions which allow to change // an address if it is compromised or something happens // destination for team's share // this should point to an instance of TokenVault contract address public teamVaultAddr = 0x0; // destination for reward tokens address public bountyVaultAddr; // destination for collected Ether address public trusteeVaultAddr; // destination for operational costs account address public opVaultAddr; // adress of our token address public tokenAddr; // address of our bitcoin payment processing robot // the robot is allowed to generate tokens without // sending ether // we do it to have more granular rights controll address public robotAddr; ///////////////////////////////// // Realted to Campaign // @check ensure that state transitions are // only in one direction // 4 - passive, not accepting funds // 3 - is not used // 2 - active main sale, accepting funds // 1 - closed, not accepting funds // 0 - finalized, not accepting funds uint8 public campaignState = 4; bool public paused = false; // keeps track of tokens generated so far, scaled value uint256 public tokensGenerated = 0; // total Ether raised (= Ether paid into the contract) uint256 public amountRaised = 0; // this is the address where the funds // will be transfered after the sale ends // time in seconds since epoch // set to midnight of saturday January 1st, 4000 uint256 public tCampaignStart = 64060588800; uint256 public tBonusStageEnd = 7 * (1 days); uint256 public tRegSaleStart = 8 * (1 days); uint256 public t_1st_StageEnd = 15 * (1 days); uint256 public t_2nd_StageEnd = 22* (1 days); uint256 public t_3rd_StageEnd = 29 * (1 days); uint256 public tCampaignEnd = 38 * (1 days); uint256 public tFinalized = 64060588800; ////////////////////////////////////////////// // // Modifiers /// @notice The robot is allowed to generate tokens /// without sending ether /// We do it to have more granular rights controll modifier onlyRobot () { require(msg.sender == robotAddr); _; } ////////////////////////////////////////////// // // Events event CampaignOpen(uint256 time); event CampaignClosed(uint256 time); event CampaignPausd(uint256 time); event CampaignResumed(uint256 time); event TokenGranted(address indexed backer, uint amount, string ref); event TokenGranted(address indexed backer, uint amount); event TotalRaised(uint raised); event Finalized(uint256 time); event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); /// @notice Constructor /// @param _tokenAddress Our token's address /// @param _trusteeAddress Team share /// @param _opAddress Team share /// @param _bountyAddress Team share /// @param _robotAddress Address of our processing backend function TokenCampaign( address _tokenAddress, address _trusteeAddress, address _opAddress, address _bountyAddress, address _robotAddress) { controller = msg.sender; /// set addresses tokenAddr = _tokenAddress; //teamVaultAddr = _teamAddress; trusteeVaultAddr = _trusteeAddress; opVaultAddr = _opAddress; bountyVaultAddr = _bountyAddress; robotAddr = _robotAddress; /// reference our token token = rea_token_interface(tokenAddr); // adjust 'constants' for decimals used // decimals = token.decimals(); // should be 18 } ////////////////////////////////////////////////// /// /// Functions that do not change contract state function get_presale_goal() constant returns (bool){ if ((now <= tBonusStageEnd) && (tokensGenerated >= bonusTokenThreshold)){ return true; } else { return false; } } /// @notice computes the current rate /// according to time passed since the start /// @return amount of tokens per ETH function get_rate() constant returns (uint256){ // obviously one gets 0 tokens // if campaign not yet started // or is already over if (now < tCampaignStart) return 0; if (now > tCampaignEnd) return 0; // compute rate per ETH based on time // assumes that time marks are increasing // from tBonusStageEnd through t_3rd_StageEnd // adjust by factor 'scale' depending on token's decimals // NOTE: can't cause overflow since all numbers are known at compile time if (now <= tBonusStageEnd) return scale * (baseRate + bonusAdd); if (now <= t_1st_StageEnd) return scale * (baseRate + stage_1_add); else if (now <= t_2nd_StageEnd) return scale * (baseRate + stage_2_add); else if (now <= t_3rd_StageEnd) return scale * (baseRate + stage_3_add); else return baseRate * scale; } ///////////////////////////////////////////// /// /// Functions that change contract state /// /// Setters /// /// this is only for emergency case function setRobotAddr(address _newRobotAddr) public onlyController { require( _newRobotAddr != 0x0 ); robotAddr = _newRobotAddr; } // we have to set team token address before campaign start function setTeamAddr(address _newTeamAddr) public onlyController { require( campaignState > 2 && _newTeamAddr != 0x0 ); teamVaultAddr = _newTeamAddr; teamVault = TokenVault(teamVaultAddr); } /// @notice Puts campaign into active state /// only controller can do that /// only possible if team token Vault is set up /// WARNING: usual caveats apply to the Ethereum's interpretation of time function startSale() public onlyController { // we only can start if team token Vault address is set require( campaignState > 2 && teamVaultAddr != 0x0); campaignState = 2; uint256 tNow = now; // assume timestamps will not cause overflow tCampaignStart = tNow; tBonusStageEnd += tNow; tRegSaleStart += tNow; t_1st_StageEnd += tNow; t_2nd_StageEnd += tNow; t_3rd_StageEnd += tNow; tCampaignEnd += tNow; CampaignOpen(now); } /// @notice Pause sale /// just in case we have some troubles /// Note that time marks are not updated function pauseSale() public onlyController { require( campaignState == 2 ); paused = true; CampaignPausd(now); } /// @notice Resume sale function resumeSale() public onlyController { require( campaignState == 2 ); paused = false; CampaignResumed(now); } /// @notice Puts the camapign into closed state /// only controller can do so /// only possible from the active state /// we can call this function if we want to stop sale before end time /// and be able to perform 'finalizeCampaign()' immediately function closeSale() public onlyController { require( campaignState == 2 ); campaignState = 1; CampaignClosed(now); } /// @notice Finalizes the campaign /// Get funds out, generates team, bounty and reserve tokens function finalizeCampaign() public { /// only if sale was closed or 48 hours = 2880 minutes have passed since campaign end /// we leave this time to complete possibly pending orders /// from offchain contributions require ( (campaignState == 1) || ((campaignState != 0) && (now > tCampaignEnd + (2880 minutes)))); campaignState = 0; // forward funds to the trustee // since we forward a fraction of the incomming ether on every contribution // 'amountRaised' IS NOT equal to the contract's balance // we use 'this.balance' instead trusteeVaultAddr.transfer(this.balance); uint256 bountyTokens = (tokensGenerated.mul(PRCT_BOUNTY)).div(100); uint256 teamTokens = (tokensGenerated.mul(PRCT_TEAM)).div(100); // generate bounty tokens assert( do_grant_tokens(bountyVaultAddr, bountyTokens) ); // generate team tokens // time lock team tokens before transfer // we dont use it anymore //teamVault.setTimeLock( tCampaignEnd + 6 * (6 minutes)); tFinalized = now; // generate all the tokens assert( do_grant_tokens(teamVaultAddr, teamTokens) ); // prevent further token generation token.finalize(); // notify the world Finalized(tFinalized); } /// @notice triggers token generaton for the recipient /// can be called only from the token sale contract itself /// side effect: increases the generated tokens counter /// CAUTION: we do not check campaign state and parameters assuming that's calee's task function do_grant_tokens(address _to, uint256 _nTokens) internal returns (bool){ require( token.generate_token_for(_to, _nTokens) ); tokensGenerated = tokensGenerated.add(_nTokens); return true; } /// @notice processes the contribution /// checks campaign state, time window and minimal contribution /// throws if one of the conditions fails function process_contribution(address _toAddr) internal { require ((campaignState == 2) // active main sale && (now <= tCampaignEnd) // within time window && (paused == false)); // not on hold // contributions are not possible before regular sale starts if ( (now > tBonusStageEnd) && //<--- new (now < tRegSaleStart)){ //<--- new revert(); //<--- new } // during the bonus phase we require a minimal eth contribution if ((now <= tBonusStageEnd) && ((msg.value < bonusMinContribution ) || (tokensGenerated >= bonusTokenThreshold))) //<--- new, revert if bonusThreshold is exceeded { revert(); } // otherwise we check that Eth sent is sufficient to generate at least one token // though our token has decimals we don't want nanocontributions require ( msg.value >= minContribution ); // compute the rate // NOTE: rate is scaled to account for token decimals uint256 rate = get_rate(); // compute the amount of tokens to be generated uint256 nTokens = (rate.mul(msg.value)).div(1 ether); // compute the fraction of ETH going to op account uint256 opEth = (PRCT_ETH_OP.mul(msg.value)).div(100); // transfer to op account opVaultAddr.transfer(opEth); // @todo check success (NOTE we have no cap now so success is assumed) // side effect: do_grant_tokens updates the "tokensGenerated" variable require( do_grant_tokens(_toAddr, nTokens) ); amountRaised = amountRaised.add(msg.value); // notify the world TokenGranted(_toAddr, nTokens); TotalRaised(amountRaised); } /// @notice Gnenerate token "manually" without payment /// We intend to use this to generate tokens from Bitcoin contributions without /// without Ether being sent to this contract /// Note that this function can be triggered only by our BTC processing robot. /// A string reference is passed and logged for better book keeping /// side effect: increases the generated tokens counter via do_grant_tokens /// @param _toAddr benificiary address /// @param _nTokens amount of tokens to be generated /// @param _ref payment reference e.g. Bitcoin address used for contribution function grant_token_from_offchain(address _toAddr, uint _nTokens, string _ref) public onlyRobot { require ( (campaignState == 2) ||(campaignState == 1)); do_grant_tokens(_toAddr, _nTokens); TokenGranted(_toAddr, _nTokens, _ref); } /// @notice This function handles receiving Ether in favor of a third party address /// we can use this function for buying tokens on behalf /// @param _toAddr the address which will receive tokens function proxy_contribution(address _toAddr) public payable { require ( _toAddr != 0x0 ); /// prevent contracts from buying tokens /// we assume it is still usable for a while /// we aknowledge the fact that this prevents ALL contracts including MultiSig's /// from contributing, it is intended and we add a corresponding statement /// to our Terms and the ICO site require( msg.sender == tx.origin ); process_contribution(_toAddr); } /// @notice This function handles receiving Ether function () payable { /// prevent contracts from buying tokens /// we assume it is still usable for a while /// we aknowledge the fact that this prevents ALL contracts including MultiSig's /// from contributing, it is intended and we add a corresponding statement /// to our Terms and the ICO site require( msg.sender == tx.origin ); process_contribution(msg.sender); } ////////// // Safety Methods ////////// /* inspired by MiniMeToken.sol */ /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. function claimTokens(address _tokenAddr) public onlyController { // if (_token == 0x0) { // controller.transfer(this.balance); // return; // } ERC20Basic some_token = ERC20Basic(_tokenAddr); uint balance = some_token.balanceOf(this); some_token.transfer(controller, balance); ClaimedTokens(_tokenAddr, controller, balance); } }
this is only for emergency case
function setRobotAddr(address _newRobotAddr) public onlyController { require( _newRobotAddr != 0x0 ); robotAddr = _newRobotAddr; }
12,894,911
/** * @authors: [@fnanni-0] * @reviewers: [] * @auditors: [] * @bounties: [] */ pragma solidity >=0.7; import "@kleros/erc-792/contracts/IArbitrator.sol"; import "@kleros/ethereum-libraries/contracts/CappedMath.sol"; library BinaryUpgradableArbitrable { using CappedMath for uint256; /* *** Contract variables *** */ uint256 private constant AMOUNT_OF_CHOICES = 2; uint256 private constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. uint256 private constant PARTY_A = 1; // Represents the ruling option 1. uint256 private constant PARTY_B = 2; // Represents the ruling option 2. struct Round { uint256[3] paidFees; // Tracks the fees paid for each ruling in this round. uint256 rulingFunded; // {0, 1, 2} If the round is appealed, i.e. this is not the last round, 0 means that both rulings (1 and 2) were fully funded. uint256 feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the ruling that ultimately wins a dispute. mapping(address => uint256[3]) contributions; // Maps contributors to their contributions for each ruling. } struct DisputeData { mapping(uint256 => Round) rounds; uint184 roundCounter; // ruling is adapted in the following way to save gas: // 0: the dispute wasn't created or no ruling was given yet. // 1: invalid/refused to rule. The dispute is resolved. // 2: option 1. The dispute is resolved. // 3: option 2. The dispute is resolved. uint64 arbitratorDataID; uint8 ruling; uint256 disputeIDOnArbitratorSide; } struct ArbitratorData { IArbitrator arbitrator; // Address of the trusted arbitrator to solve disputes. TRUSTED. bytes arbitratorExtraData; // Extra data for the arbitrator. } struct ArbitrableStorage { uint256 sharedStakeMultiplier; // Multiplier for calculating the appeal fee that must be paid by the submitter in the case where there is no winner or loser (e.g. when the arbitrator ruled "refuse to arbitrate"). uint256 winnerStakeMultiplier; // Multiplier for calculating the appeal fee of the party that won the previous round. uint256 loserStakeMultiplier; // Multiplier for calculating the appeal fee of the party that lost the previous round. mapping(uint256 => DisputeData) disputes; // disputes[localDisputeID] mapping(uint256 => uint256) externalIDtoLocalID; // Maps external (arbitrator's side) dispute ids to local dispute ids. The local dispute ids must be defined by the arbitrable contract. externalIDtoLocalID[disputeIDOnArbitratorSide] ArbitratorData[] arbitratorDataList; // Stores the arbitrator data of the contract. Updated each time the data is changed. } /* *** Events *** */ /// @dev When a library function emits an event, Solidity requires the event to be defined both inside the library and in the contract where the library is used. Make sure that your arbitrable contract inherits the interfaces mentioned below in order to comply with this (IArbitrable, IEvidence and IAppealEvents). /// @dev See {@kleros/erc-792/contracts/IArbitrable.sol}. event Ruling(IArbitrator indexed _arbitrator, uint256 indexed _disputeIDOnArbitratorSide, uint256 _ruling); /// @dev See {@kleros/erc-792/contracts/erc-1497/IEvidence.sol}. event Evidence(IArbitrator indexed _arbitrator, uint256 indexed _evidenceGroupID, address indexed _party, string _evidence); /// @dev See {@kleros/erc-792/contracts/erc-1497/IEvidence.sol}. event Dispute(IArbitrator indexed _arbitrator, uint256 indexed _disputeIDOnArbitratorSide, uint256 _metaEvidenceID, uint256 _evidenceGroupID); /// @dev See {https://github.com/kleros/arbitrable-contract-libraries/blob/main/contracts/interfaces/IAppealEvents.sol}. event HasPaidAppealFee(uint256 indexed _localDisputeID, uint256 _round, uint256 indexed _ruling); /// @dev See {https://github.com/kleros/arbitrable-contract-libraries/blob/main/contracts/interfaces/IAppealEvents.sol}. event AppealContribution(uint256 indexed _localDisputeID, uint256 _round, uint256 indexed _ruling, address indexed _contributor, uint256 _amount); /// @dev See {https://github.com/kleros/arbitrable-contract-libraries/blob/main/contracts/interfaces/IAppealEvents.sol}. event Withdrawal(uint256 indexed _localDisputeID, uint256 indexed _round, uint256 _ruling, address indexed _contributor, uint256 _reward); // **************************** // // * Modifying the state * // // **************************** // /** @dev Changes the stake multipliers. * @param _sharedStakeMultiplier A new value of the multiplier for calculating appeal fees. In basis points. * @param _winnerStakeMultiplier A new value of the multiplier for calculating appeal fees. In basis points. * @param _loserStakeMultiplier A new value of the multiplier for calculating appeal fees. In basis points. */ function setMultipliers( ArbitrableStorage storage self, uint256 _sharedStakeMultiplier, uint256 _winnerStakeMultiplier, uint256 _loserStakeMultiplier ) internal { self.sharedStakeMultiplier = _sharedStakeMultiplier; self.winnerStakeMultiplier = _winnerStakeMultiplier; self.loserStakeMultiplier = _loserStakeMultiplier; } /** @dev Sets the arbitrator data. Must be set at least once to be able to use the library. Affects only disputes created after this method is called. Disputes already created keep using older arbitrator's data. * @param _arbitrator The address of the arbitrator contract that is going to be used for every dispute created. * @param _arbitratorExtraData The extra data for the arbitrator. */ function setArbitrator( ArbitrableStorage storage self, IArbitrator _arbitrator, bytes memory _arbitratorExtraData ) internal { ArbitratorData storage arbitratorData = self.arbitratorDataList.push(); arbitratorData.arbitrator = _arbitrator; arbitratorData.arbitratorExtraData = _arbitratorExtraData; } /** @dev Invokes the arbitrator to create a dispute. Requires _arbitrationCost ETH. It's the arbitrable contract's responsability to make sure the amount of ETH available in the contract is enough. * @param _localDisputeID The dispute ID defined by the arbitrable contract. * @param _arbitrationCost Value in wei, as defined in getArbitrationCost(), that is needed to create a dispute. * @param _metaEvidenceID The ID of the meta-evidence of the dispute as defined in the ERC-1497 standard. * @param _evidenceGroupID The ID of the evidence group the evidence belongs to. * @return disputeID The ID assigned by the arbitrator to the newly created dispute. */ function createDispute( ArbitrableStorage storage self, uint256 _localDisputeID, uint256 _arbitrationCost, uint256 _metaEvidenceID, uint256 _evidenceGroupID ) internal returns(uint256 disputeID) { DisputeData storage dispute = self.disputes[_localDisputeID]; require(dispute.roundCounter == 0, "Dispute already created."); uint256 arbitratorDataID = self.arbitratorDataList.length - 1; ArbitratorData storage arbitratorData = self.arbitratorDataList[arbitratorDataID]; // Reverts if arbitrator data is not set. IArbitrator arbitrator = arbitratorData.arbitrator; disputeID = arbitrator.createDispute{value: _arbitrationCost}(AMOUNT_OF_CHOICES, arbitratorData.arbitratorExtraData); dispute.arbitratorDataID = uint64(arbitratorDataID); dispute.disputeIDOnArbitratorSide = disputeID; dispute.roundCounter = 1; self.externalIDtoLocalID[disputeID] = _localDisputeID; emit Dispute(arbitrator, disputeID, _metaEvidenceID, _evidenceGroupID); } /** @dev Submits a reference to evidence. EVENT. * @param _localDisputeID The dispute ID defined by the arbitrable contract. * @param _evidenceGroupID ID of the evidence group the evidence belongs to. It must match the one used in createDispute(). * @param _evidence A link to evidence using its URI. */ function submitEvidence( ArbitrableStorage storage self, uint256 _localDisputeID, uint256 _evidenceGroupID, string memory _evidence ) internal { DisputeData storage dispute = self.disputes[_localDisputeID]; require(dispute.ruling == 0, "The dispute is resolved."); if (bytes(_evidence).length > 0) { ArbitratorData storage arbitratorData; if (dispute.roundCounter == 0) // The dispute does not exist. arbitratorData = self.arbitratorDataList[self.arbitratorDataList.length - 1]; else arbitratorData = self.arbitratorDataList[uint256(dispute.arbitratorDataID)]; emit Evidence(arbitratorData.arbitrator, _evidenceGroupID, msg.sender, _evidence); } } /** @dev Takes up to the total amount required to fund a ruling of an appeal. Reimburses the rest. Creates an appeal if both rulings (1 and 2) are fully funded. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @param _ruling The ruling to which the contribution is made. */ function fundAppeal(ArbitrableStorage storage self, uint256 _localDisputeID, uint256 _ruling) internal { DisputeData storage dispute = self.disputes[_localDisputeID]; uint256 currentRound = uint256(dispute.roundCounter - 1); require( currentRound + 1 != 0 && // roundCounter equal to 0 means that the dispute was not created. dispute.ruling == 0, "No ongoing dispute to appeal." ); Round storage round = dispute.rounds[currentRound]; uint256 rulingFunded = round.rulingFunded; // Use local variable for gas saving purposes. require( _ruling != rulingFunded && _ruling != 0, "Ruling is funded or is invalid." ); (uint256 appealCost, uint256 totalCost) = getAppealFeeComponents(self, _localDisputeID, _ruling); uint256 paidFee = round.paidFees[_ruling]; // Use local variable for gas saving purposes. // Take up to the amount necessary to fund the current round at the current costs. (uint256 contribution, uint256 remainingETH) = calculateContribution(msg.value, totalCost.subCap(paidFee)); round.contributions[msg.sender][_ruling] += contribution; paidFee += contribution; round.paidFees[_ruling] = paidFee; emit AppealContribution(_localDisputeID, currentRound, _ruling, msg.sender, contribution); // Reimburse leftover ETH if any. if (remainingETH > 0) msg.sender.send(remainingETH); // Deliberate use of send in order not to block the contract in case of reverting fallback. if (paidFee >= totalCost) { emit HasPaidAppealFee(_localDisputeID, currentRound, _ruling); if (rulingFunded == 0) { round.rulingFunded = _ruling; } else { // Both rulings are fully funded. Create an appeal. ArbitratorData storage arbitratorData = self.arbitratorDataList[uint256(dispute.arbitratorDataID)]; arbitratorData.arbitrator.appeal{value: appealCost}(dispute.disputeIDOnArbitratorSide, arbitratorData.arbitratorExtraData); round.feeRewards = paidFee + round.paidFees[rulingFunded] - appealCost; round.rulingFunded = 0; // clear storage dispute.roundCounter = uint184(currentRound + 2); // currentRound starts at 0 while roundCounter at 1. } } } /** @dev Validates and registers the ruling for a dispute. Can only be called from the IArbitrable rule() function, which is 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. The ruling is inverted if a party loses from lack of appeal fees funding. * @param _disputeIDOnArbitratorSide ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refuse to arbitrate". */ function processRuling( ArbitrableStorage storage self, uint256 _disputeIDOnArbitratorSide, uint256 _ruling ) internal returns(uint256 finalRuling) { uint256 localDisputeID = self.externalIDtoLocalID[_disputeIDOnArbitratorSide]; DisputeData storage dispute = self.disputes[localDisputeID]; IArbitrator arbitrator = self.arbitratorDataList[uint256(dispute.arbitratorDataID)].arbitrator; require( dispute.ruling == 0 && msg.sender == address(arbitrator) && _ruling <= AMOUNT_OF_CHOICES, "Ruling can't be processed." ); Round storage round = dispute.rounds[dispute.roundCounter - 1]; // If only one ruling was fully funded, we consider it the winner, regardless of the arbitrator's decision. if (round.rulingFunded == 0) finalRuling = _ruling; else finalRuling = round.rulingFunded; dispute.ruling = uint8(finalRuling + 1); emit Ruling(arbitrator, _disputeIDOnArbitratorSide, finalRuling); } /** @dev Withdraws contributions of appeal rounds. Reimburses contributions if the appeal was not fully funded. * If the appeal was fully funded, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @param _beneficiary The address that made the contributions. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards( ArbitrableStorage storage self, uint256 _localDisputeID, address payable _beneficiary, uint256 _round ) internal { DisputeData storage dispute = self.disputes[_localDisputeID]; require(dispute.ruling != 0, "Dispute not resolved."); (uint256 rewardA, uint256 rewardB) = getWithdrawableAmount(self, _localDisputeID, _beneficiary, _round); uint256[3] storage contributionTo = dispute.rounds[_round].contributions[_beneficiary]; if (rewardA > 0) { contributionTo[PARTY_A] = 0; emit Withdrawal(_localDisputeID, _round, PARTY_A, _beneficiary, rewardA); } if (rewardB > 0) { contributionTo[PARTY_B] = 0; emit Withdrawal(_localDisputeID, _round, PARTY_B, _beneficiary, rewardB); } _beneficiary.send(rewardA + rewardB); // It is the user responsibility to accept ETH. } /** @dev Withdraws contributions of multiple appeal rounds at once. This function is O(n) where n is the number of rounds. * This could exceed the gas limit, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @param _beneficiary The address that made the contributions. * @param _cursor The round from where to start withdrawing. * @param _count The number of rounds to iterate. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchWithdrawFeesAndRewards( ArbitrableStorage storage self, uint256 _localDisputeID, address payable _beneficiary, uint256 _cursor, uint256 _count ) internal { DisputeData storage dispute = self.disputes[_localDisputeID]; require(dispute.ruling != 0, "Dispute not resolved."); uint256 maxRound = _cursor + _count > dispute.roundCounter ? dispute.roundCounter : _cursor + _count; uint256 reward; for (uint256 i = _cursor; i < maxRound; i++) { (uint256 rewardA, uint256 rewardB) = getWithdrawableAmount(self, _localDisputeID, _beneficiary, i); reward += rewardA + rewardB; uint256[3] storage contributionTo = dispute.rounds[i].contributions[_beneficiary]; if (rewardA > 0) { contributionTo[PARTY_A] = 0; emit Withdrawal(_localDisputeID, i, PARTY_A, _beneficiary, rewardA); } if (rewardB > 0) { contributionTo[PARTY_B] = 0; emit Withdrawal(_localDisputeID, i, PARTY_B, _beneficiary, rewardB); } } _beneficiary.send(reward); // It is the user responsibility to accept ETH. } // ******************** // // * Getters * // // ******************** // /** @dev Gets the rewards withdrawable for a given round. * Beware that withdrawals are allowed only after the dispute gets Resolved. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @param _beneficiary The address that made the contributions. * @param _round The round from which to withdraw. * @return rewardA rewardB The rewards to which the _beneficiary is entitled at a given round. */ function getWithdrawableAmount( ArbitrableStorage storage self, uint256 _localDisputeID, address _beneficiary, uint256 _round ) internal view returns(uint256 rewardA, uint256 rewardB) { DisputeData storage dispute = self.disputes[_localDisputeID]; Round storage round = dispute.rounds[_round]; uint256 ruling = uint256(dispute.ruling - 1); uint256 lastRound = dispute.roundCounter - 1; uint256[3] storage contributionTo = round.contributions[_beneficiary]; if (_round == lastRound) { // Allow to reimburse if funding was unsuccessful. rewardA = contributionTo[PARTY_A]; rewardB = contributionTo[PARTY_B]; } else if (ruling == 0) { // Reimburse unspent fees proportionally if there is no winner and loser. uint256 totalFeesPaid = round.paidFees[PARTY_A] + round.paidFees[PARTY_B]; uint256 feeRewards = round.feeRewards; if (totalFeesPaid > 0) { rewardA = contributionTo[PARTY_A] * feeRewards / totalFeesPaid; rewardB = contributionTo[PARTY_B] * feeRewards / totalFeesPaid; } } else { // Reward the winner. uint256 paidFees = round.paidFees[ruling]; uint256 reward = paidFees > 0 ? (contributionTo[ruling] * round.feeRewards) / paidFees : 0; if (ruling == PARTY_A) rewardA = reward; else if (ruling == PARTY_B) rewardB = reward; } } /** @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( uint256 _available, uint256 _requiredAmount ) internal pure returns(uint256 taken, uint256 remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** * @dev Calculates the appeal fee and total cost for an arbitration. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @param _ruling The ruling to which the contribution is made. * @return appealCost The appeal fee charged by the arbitrator. * @return totalCost The total cost for appealing. */ function getAppealFeeComponents( ArbitrableStorage storage self, uint256 _localDisputeID, uint256 _ruling ) internal view returns (uint256 appealCost, uint256 totalCost) { DisputeData storage dispute = self.disputes[_localDisputeID]; ArbitratorData storage arbitratorData = self.arbitratorDataList[uint256(dispute.arbitratorDataID)]; IArbitrator arbitrator = arbitratorData.arbitrator; uint256 disputeIDOnArbitratorSide = dispute.disputeIDOnArbitratorSide; (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(disputeIDOnArbitratorSide); require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Not in appeal period."); uint256 multiplier; uint256 winner = arbitrator.currentRuling(disputeIDOnArbitratorSide); if (winner == _ruling){ multiplier = self.winnerStakeMultiplier; } else if (winner == 0){ multiplier = self.sharedStakeMultiplier; } else { require(block.timestamp < (appealPeriodEnd + appealPeriodStart)/2, "Not in loser's appeal period."); multiplier = self.loserStakeMultiplier; } appealCost = arbitrator.appealCost(disputeIDOnArbitratorSide, arbitratorData.arbitratorExtraData); totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR); } /** @dev Returns true if the dispute exists. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @return bool. */ function disputeExists(ArbitrableStorage storage self, uint256 _localDisputeID) internal view returns (bool) { return self.disputes[_localDisputeID].roundCounter != 0; } /** @dev Gets the final ruling if the dispute is resolved. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @return The ruling that won the dispute. */ function getFinalRuling(ArbitrableStorage storage self, uint256 _localDisputeID) internal view returns(uint256) { DisputeData storage dispute = self.disputes[_localDisputeID]; uint256 ruling = dispute.ruling; require(ruling != 0, "Arbitrator has not ruled yet."); return ruling - 1; } /** @dev Gets the cost of arbitration using the given arbitrator and arbitratorExtraData. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. If the disputeID does not exist, the arbitration cost is calculate with to most up-to-date arbitrator. * @return Arbitration cost. */ function getArbitrationCost(ArbitrableStorage storage self, uint256 _localDisputeID) internal view returns(uint256) { DisputeData storage dispute = self.disputes[_localDisputeID]; ArbitratorData storage arbitratorData; if (dispute.roundCounter == 0) // The dispute does not exist. arbitratorData = self.arbitratorDataList[self.arbitratorDataList.length - 1]; else arbitratorData = self.arbitratorDataList[uint256(dispute.arbitratorDataID)]; return arbitratorData.arbitrator.arbitrationCost(arbitratorData.arbitratorExtraData); } /** @dev Gets the number of rounds of the specific dispute. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @return The number of rounds. */ function getNumberOfRounds(ArbitrableStorage storage self, uint256 _localDisputeID) internal view returns (uint256) { return self.disputes[_localDisputeID].roundCounter; } /** @dev Gets the information on a round of a disputed dispute. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @param _round The round to be queried. * @return paidFees rulingFunded feeRewards appealed The round information. */ function getRoundInfo( ArbitrableStorage storage self, uint256 _localDisputeID, uint256 _round ) internal view returns( uint256[3] storage paidFees, uint256 rulingFunded, uint256 feeRewards, bool appealed ) { DisputeData storage dispute = self.disputes[_localDisputeID]; Round storage round = dispute.rounds[_round]; return ( round.paidFees, round.rulingFunded, round.feeRewards, _round != dispute.roundCounter - 1 ); } /** @dev Gets the contributions made by an address for a given round of appeal of a dispute. * @param _localDisputeID The dispute ID as defined in the arbitrable contract. * @param _round The round number. * @param _contributor The address of the contributor. * @return contributions Array of contributions. Notice that index 0 corresponds to 'refuse to rule' and will always be empty. */ function getContributions( ArbitrableStorage storage self, uint256 _localDisputeID, uint256 _round, address _contributor ) internal view returns(uint256[3] storage contributions) { DisputeData storage dispute = self.disputes[_localDisputeID]; Round storage round = dispute.rounds[_round]; contributions = round.contributions[_contributor]; } }
Calculates the appeal fee and total cost for an arbitration. _localDisputeID The dispute ID as defined in the arbitrable contract. _ruling The ruling to which the contribution is made. return appealCost The appeal fee charged by the arbitrator. return totalCost The total cost for appealing./
function getAppealFeeComponents( ArbitrableStorage storage self, uint256 _localDisputeID, uint256 _ruling ) internal view returns (uint256 appealCost, uint256 totalCost) { DisputeData storage dispute = self.disputes[_localDisputeID]; ArbitratorData storage arbitratorData = self.arbitratorDataList[uint256(dispute.arbitratorDataID)]; IArbitrator arbitrator = arbitratorData.arbitrator; uint256 disputeIDOnArbitratorSide = dispute.disputeIDOnArbitratorSide; (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(disputeIDOnArbitratorSide); require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Not in appeal period."); uint256 multiplier; uint256 winner = arbitrator.currentRuling(disputeIDOnArbitratorSide); if (winner == _ruling){ multiplier = self.winnerStakeMultiplier; multiplier = self.sharedStakeMultiplier; require(block.timestamp < (appealPeriodEnd + appealPeriodStart)/2, "Not in loser's appeal period."); multiplier = self.loserStakeMultiplier; } appealCost = arbitrator.appealCost(disputeIDOnArbitratorSide, arbitratorData.arbitratorExtraData); totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR); }
12,801,684
/** *Submitted for verification at Etherscan.io on 2021-09-15 */ /** ███████ ████████ ███████ ██ ██ ███████ ██████ ██████ ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ███████ ██ █████ ██ ██ █████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██ ███████ ████ ███████ ██████ ██████ ██ ██ ████ */ // SPDX-License-Identifier: MIT pragma solidity 0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IBEP20 { /** * @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); } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @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); } } } } interface IBEP20Metadata is IBEP20 { /** * @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); } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { //address msgSender = _msgSender(); // Owner address address msgSender = _msgSender(); // Owner address _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Stevecoin is Context, IBEP20, IBEP20Metadata, Ownable { 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; uint private _decimals; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor () { _name = "Stevecoin"; _symbol = "STEVE"; _decimals = 18; _totalSupply = 500000000 * 10**(_decimals); _balances[_msgSender()] = _totalSupply; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {BEP20} 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 * {IBEP20-balanceOf} and {IBEP20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IBEP20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IBEP20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IBEP20-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 {IBEP20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IBEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override onlyOwner() returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IBEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "BEP20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IBEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual onlyOwner returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IBEP20-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 onlyOwner returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "BEP20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "BEP20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "BEP20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function mint(address account, uint256 amount) public onlyOwner { _mint(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), "BEP20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "BEP20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function burn(address account, uint256 amount) public onlyOwner{ _burn(account, 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), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
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 {IBEP20-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 onlyOwner returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "BEP20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; }
10,507,759
./partial_match/1/0xe3BE0054Da2F8da5002E8bdD8AA4c7fDf851E86D/sources/ERC721CreatorMaxMint.sol
Helper function to set royalties/
function _setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints, RoyaltyConfig[] storage royalties) private { for (uint i; i < basisPoints.length;) { royalties.push( RoyaltyConfig( { receiver: receivers[i], bps: uint16(basisPoints[i]) } ) ); } }
2,680,697
./full_match/80001/0xdF87C42818767EE2F2EBB9B10b36d2546cf3dC50/sources/contracts/CustomTreasury.sol
deposit principalToken and receive back payoutToken supporting payoutToken fee _principalTokenAddress Address of the principalToken _amountPrincipalToken Amount of principalToken to transfer into the treasury _amountPayoutToken Amount of payoutToken to transfer to Bill Contract (msg.sender)/
function deposit( IERC20Upgradeable _principalTokenAddress, uint256 _amountPrincipalToken, uint256 _amountPayoutToken ) external onlyBillContract() { _deposit(_principalTokenAddress, _amountPrincipalToken, _amountPayoutToken, 0, address(0)); }
5,598,269
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract Token { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title Reference implementation of the ERC220 standard token. */ contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { 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 success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract BurnableToken is StandardToken, Ownable { event Burn(address indexed burner, uint256 amount); /** * @dev Anybody can burn a specific amount of their tokens. * @param _amount The amount of token to be burned. */ function burn(uint256 _amount) public { require(_amount > 0); require(_amount <= balances[msg.sender]); // no need to require _amount <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = SafeMath.sub(balances[burner],_amount); totalSupply = SafeMath.sub(totalSupply,_amount); emit Transfer(burner, address(0), _amount); emit Burn(burner, _amount); } /** * @dev Owner can burn a specific amount of tokens of other token holders. * @param _from The address of token holder whose tokens to be burned. * @param _amount The amount of token to be burned. */ function burnFrom(address _from, uint256 _amount) onlyOwner public { require(_from != address(0)); require(_amount > 0); require(_amount <= balances[_from]); balances[_from] = SafeMath.sub(balances[_from],_amount); totalSupply = SafeMath.sub(totalSupply,_amount); emit Transfer(_from, address(0), _amount); emit Burn(_from, _amount); } } contract AxpirePausableToken is StandardToken, Pausable,BurnableToken { 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); } } contract AxpireToken is AxpirePausableToken { using SafeMath for uint; // metadata string public constant name = "aXpire"; string public constant symbol = "AXPR"; uint256 public constant decimals = 18; address private ethFundDeposit; address private escrowFundDeposit; uint256 public icoTokenExchangeRate = 715; // 715 b66 tokens per 1 ETH uint256 public tokenCreationCap = 350 * (10**6) * 10**decimals; //address public ; // crowdsale parameters bool public tokenSaleActive; // switched to true in operational state bool public haltIco; bool public dead = false; // events event CreateToken(address indexed _to, uint256 _value); event Transfer(address from, address to, uint256 value); // constructor constructor ( address _ethFundDeposit, address _escrowFundDeposit ) public { tokenSaleActive = true; haltIco = true; paused = true; require(_ethFundDeposit != address(0)); require(_escrowFundDeposit != address(0)); ethFundDeposit = _ethFundDeposit; escrowFundDeposit=_escrowFundDeposit; balances[escrowFundDeposit] = tokenCreationCap; totalSupply = tokenCreationCap; emit CreateToken(escrowFundDeposit, totalSupply); } /// @dev Accepts ether and creates new tge tokens. function createTokens() payable external { if (!tokenSaleActive) revert(); if (haltIco) revert(); if (msg.value == 0) revert(); uint256 tokens; tokens = SafeMath.mul(msg.value, icoTokenExchangeRate); // check that we're not over totals uint256 checkedSupply = SafeMath.add(totalSupply, tokens); // return money if something goes wrong if (tokenCreationCap < checkedSupply) revert(); // odd fractions won't be found totalSupply = checkedSupply; balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here emit CreateToken(msg.sender, tokens); // logs token creation } function setIcoTokenExchangeRate (uint _icoTokenExchangeRate) onlyOwner external { icoTokenExchangeRate = _icoTokenExchangeRate; } function setHaltIco(bool _haltIco) onlyOwner external { haltIco = _haltIco; } /// @dev Ends the funding period and sends the ETH home function sendFundHome() onlyOwner external { // move to operational if (!ethFundDeposit.send(address(this).balance)) revert(); // send the eth to tge International } function sendFundHomeAmt(uint _amt) onlyOwner external { if (!ethFundDeposit.send(_amt*10**decimals)) revert(); // send the eth to tge International } function toggleDead() external onlyOwner returns (bool) { dead = !dead; } function endIco() onlyOwner external { // end ICO // ensure that sale is active. is set to false at the end. can only be performed once. require(tokenSaleActive == true); tokenSaleActive=false; } }
Accepts ether and creates new tge tokens. return money if something goes wrong
function createTokens() payable external { if (!tokenSaleActive) revert(); if (haltIco) revert(); if (msg.value == 0) revert(); uint256 tokens; uint256 checkedSupply = SafeMath.add(totalSupply, tokens); if (tokenCreationCap < checkedSupply) totalSupply = checkedSupply; }
6,049,693
pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; import "../token/ProperlyToken.sol"; import "../access/Ownable.sol"; import "../utils/math/SafeMath.sol"; import "../token/ERC20/libs/SafeERC20.sol"; // Code is inspired from most popular farms on BSC. // Code has been modified. contract Farm is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // The Protocol Token! ProperlyToken public dpi; // Dev address. address public devaddr; // DPI tokens created per block. uint256 public dpiPerBlock; // Deposit Fee address address public feeAddress; constructor( ProperlyToken _dpi, address _devaddr, address _feeAddress, uint256 _dpiPerBlock, uint256 _startBlock ) public { dpi = _dpi; devaddr = _devaddr; feeAddress = _feeAddress; dpiPerBlock = _dpiPerBlock; startBlock = _startBlock; } struct UserInfo { uint256 amount; // How many LP tokens the user has user provided. uint256 rewardDebt; // Reward debt. See explanation below. // pending reward = (user.amount * pool.accdpiPerShare) - user.rewardDebt // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accdpiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // Portion of reward allocation to this pool. uint256 lastRewardBlock; // Block number when last distribution happened on a pool. uint256 accDPIPerShare; // Accumulated DPI's per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points } // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when DPI mining starts. uint256 public startBlock; // Calculate how many pools exist. function poolLength() external view returns (uint256) { return poolInfo.length; } mapping(ERC20 => bool) public poolExistence; // Prevents creation of a pool with the same token. modifier nonDuplicated(ERC20 _lpToken) { require(poolExistence[_lpToken] == false, "nonDuplicated: duplicated"); _; } // Create a new pool. Can only be called by the owner. // You define the token address. // You set the weightto the pool - allocPoint. It determine how much rewards will go to stakers of this pool relative to other pools. // You also define the deposit fee. This fee is moved to fee collecter address. function add( uint256 _allocPoint, ERC20 _lpToken, uint16 _depositFeeBP, bool _withUpdate ) public onlyOwner nonDuplicated(_lpToken) { // The deposit fee has to be below 100% require( _depositFeeBP <= 10000, "add: invalid deposit fee basis points" ); if (_withUpdate) { massUpdatePools(); } // In case Farm already running set the lastRewardBlock to curenct block number. // In case farm is launched in the future, set it to the farm startBlock number. uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; // Adjust totalAllocPoint to weight of all pools, accounting for new pool added. totalAllocPoint = totalAllocPoint.add(_allocPoint); // You set the pool as it already exists so you wouln't be able to create the same exact pool twice. poolExistence[_lpToken] = true; // Store the information of the new pool. poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accDPIPerShare: 0, depositFeeBP: _depositFeeBP }) ); } // Update reward variables for all pools. function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // View pending DPIs rewards. function pendingDPI(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accDPIPerShare = pool.accDPIPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blockDifference = block.number.sub(pool.lastRewardBlock); uint256 dpiReward = blockDifference.mul(dpiPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accDPIPerShare = accDPIPerShare.add( dpiReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accDPIPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; // if the pool reward block number is in the future the farm has not started yet. if (block.number <= pool.lastRewardBlock) { return; } // Total of pool token that been supplied. uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // If pool has no LP tokens or pool weight is set to 0 don't distribute rewards. // Just update the update to last block. if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } // If none of the above is true mint tokens and distribute rewards. // First we get the number of blocks that we have advanced forward since the last time we updated the farm. uint256 blockDifference = block.number.sub(pool.lastRewardBlock); // After we got to the block timeframe defference, we calculate how much we mint. // For each farm we consider the weight it has compared to the other farms. uint256 dpiReward = blockDifference.mul(dpiPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); // A % of reward is going to the developers address so that would be a portion of total reward. dpi.mint(devaddr, dpiReward.div(10)); // We are minting to the protocol address the address the reward tokens. dpi.mint(address(this), dpiReward); // Calculates how many tokens does each supplied of token get. pool.accDPIPerShare = pool.accDPIPerShare.add( dpiReward.mul(1e12).div(lpSupply) ); // We update the farm to the current block number. pool.lastRewardBlock = block.number; } // Deposit pool tokens for DPI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; // Update pool when user interacts with the contract. updatePool(_pid); // If the user has previously deposited money to the farm. if (user.amount > 0) { // Calculate how much does the farm owe the user. uint256 pending = user.amount.mul(pool.accDPIPerShare).div(1e12).sub( user.rewardDebt ); // When user executes deposit, pending rewards get sent to the user. if (pending > 0) { safeDPITransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); // If the pool has a deposit fee if (pool.depositFeeBP > 0) { // Calculate what does it represent in token terms. uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); // Send the deposit fee to the feeAddress pool.lpToken.safeTransfer(feeAddress, depositFee); // Add the user token to the farm and substract the deposit fee. user.amount = user.amount.add(_amount).sub(depositFee); // If there is no deposit fee just add the money to the total amount that a user has deposited. } else { user.amount = user.amount.add(_amount); } } // Generate Debt for the previous rewards that the user is not entitled to. Because he just entered. user.rewardDebt = user.amount.mul(pool.accDPIPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw pool tokens, function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); // Check's what is the pending amount considering current block. // Assuming that we distribute 5 Tokens for every 1 token. // if user deposited 0.5 tokens, he recives 2.5 tokens. uint256 pending = user.amount.mul(pool.accDPIPerShare).div(1e12).sub(user.rewardDebt); // If the user has a reward pending, send the user his rewards. if (pending > 0) { safeDPITransfer(msg.sender, pending); } // If the user is withdrawing from the farm more than 0 tokens if (_amount > 0) { // reduce from the user DB the ammount he is trying to withdraw. user.amount = user.amount.sub(_amount); // Send the user the amount of LP tokens he is withdrawing. pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accDPIPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // In case if rounding error causes pool to not have enough DPI TOKENS function safeDPITransfer(address _to, uint256 _amount) internal { // Check how many DPI token's on the protocol address. uint256 DPIBal = dpi.balanceOf(address(this)); // In case if the amount requested is higher than the money on the protocol balance. if (_amount > DPIBal) { // Transfer absolutely everything from the balance to the contract. dpi.transfer(_to, DPIBal); } else { // If there is enough tokens on the protocol, make the usual transfer. dpi.transfer(_to, _amount); } } // Update developer fee address. function dev(address _devaddr) public { // Can be done only by developer require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // Address that collects fees on the protocol. // Fees will be used to buy back DPI tokens. function setFeeAddress(address _feeAddress) public { require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN"); feeAddress = _feeAddress; } // Function that sets the new amount of how many new DPI Tokens will be minted per each block. function updateEmissionRate(uint256 _DPIPerBlock) public onlyOwner { massUpdatePools(); dpiPerBlock = _DPIPerBlock; } }
Withdraw pool tokens, Check's what is the pending amount considering current block. Assuming that we distribute 5 Tokens for every 1 token. if user deposited 0.5 tokens, he recives 2.5 tokens. If the user has a reward pending, send the user his rewards. If the user is withdrawing from the farm more than 0 tokens reduce from the user DB the ammount he is trying to withdraw. Send the user the amount of LP tokens he is withdrawing.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accDPIPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeDPITransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accDPIPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
12,992,027
./full_match/1/0xD634626DE5C6237CE3eaa6805B102Bb8CE9a0e9E/sources/contracts/ClayMatic.sol
Returns information about all nodes.
function getNodes() external view returns (StakingNode[] memory, uint256[] memory) { uint256 n = activeNodes.length; (, uint256[] memory stakedNodes) = _getTotalStaked(); StakingNode[] memory nodes = new StakingNode[](n); for (uint256 i = 0; i < n; i++) { nodes[i] = stakingNodes[activeNodes[i]]; } return (nodes, stakedNodes); }
9,774,068
pragma solidity ^0.4.18; /************************************************** */ /* WhenHub Token Smart Contract */ /* Author: Nik Kalyani [email protected] */ /* Copyright (c) 2018 CalendarTree, Inc. */ /* https://interface.whenhub.com */ /************************************************** */ contract WHENToken { using SafeMath for uint256; mapping(address => uint256) balances; // Token balance for each address mapping (address => mapping (address => uint256)) internal allowed; // Approval granted to transfer tokens by one address to another address /* ERC20 fields */ string public name; string public symbol; uint public decimals = 18; string public sign = "₩"; string public logoPng = "https://github.com/WhenHub/WHEN/raw/master/assets/when-token-icon.png"; /* Each registered user on WhenHub Interface Network has a record in this contract */ struct User { bool isRegistered; // Flag to indicate user was registered uint256 seedJiffys; // Tracks free tokens granted to user uint256 interfaceEscrowJiffys; // Tracks escrow tokens used in Interfaces address referrer; // Tracks who referred this user } // IcoBurnAuthorized is used to determine when remaining ICO tokens should be burned struct IcoBurnAuthorized { bool contractOwner; // Flag to indicate ContractOwner has authorized bool platformManager; // Flag to indicate PlatformManager has authorized bool icoOwner; // Flag to indicate SupportManager has authorized } // PurchaseCredit is used to track purchases made by USD when user isn't already registered struct PurchaseCredit { uint256 jiffys; // Number of jiffys purchased uint256 purchaseTimestamp; // Date/time of original purchase } mapping(address => PurchaseCredit) purchaseCredits; // Temporary store for USD-purchased tokens uint private constant ONE_WEEK = 604800; uint private constant SECONDS_IN_MONTH = 2629743; uint256 private constant ICO_START_TIMESTAMP = 1521471600; // 3/19/2018 08:00:00 PDT uint private constant BASIS_POINTS_TO_PERCENTAGE = 10000; // All fees are expressed in basis points. This makes conversion easier /* Token allocations per published WhenHub token economics */ uint private constant ICO_TOKENS = 350000000; // Tokens available for public purchase uint private constant PLATFORM_TOKENS = 227500000; // Tokens available for network seeding uint private constant COMPANY_TOKENS = 262500000; // Tokens available to WhenHub for employees and future expansion uint private constant PARTNER_TOKENS = 17500000; // Tokens available for WhenHub partner inventives uint private constant FOUNDATION_TOKENS = 17500000; // Tokens available for WhenHub Foundationn charity /* Network seeding tokens */ uint constant INCENTIVE_TOKENS = 150000000; // Total pool of seed tokens for incentives uint constant REFERRAL_TOKENS = 77500000; // Total pool of seed tokens for referral uint256 private userSignupJiffys = 0; // Number of Jiffys per user who signs up uint256 private referralSignupJiffys = 0; // Number of Jiffys per user(x2) referrer + referree uint256 private jiffysMultiplier; // 10 ** decimals uint256 private incentiveJiffysBalance; // Available balance of Jiffys for incentives uint256 private referralJiffysBalance; // Available balance of Jiffys for referrals /* ICO variables */ uint256 private bonus20EndTimestamp = 0; // End of 20% ICO token bonus timestamp uint256 private bonus10EndTimestamp = 0; // End of 10% ICO token bonus timestamp uint256 private bonus5EndTimestamp = 0; // End of 5% ICO token bonus timestamp uint private constant BUYER_REFERRER_BOUNTY = 3; // Referral bounty percentage IcoBurnAuthorized icoBurnAuthorized = IcoBurnAuthorized(false, false, false); /* Interface transaction settings */ bool private operational = true; // Blocks all state changes throughout the contract if false // Change using setOperatingStatus() uint256 public winNetworkFeeBasisPoints = 0; // Per transaction fee deducted from payment to Expert // Change using setWinNetworkFeeBasisPoints() uint256 public weiExchangeRate = 500000000000000; // Exchange rate for 1 WHEN Token in Wei ($0.25/₩) // Change using setWeiExchangeRate() uint256 public centsExchangeRate = 25; // Exchange rate for 1 WHEN Token in cents // Change using setCentsExchangeRate() /* State variables */ address private contractOwner; // Account used to deploy contract address private platformManager; // Account used by API for Interface app address private icoOwner; // Account from which ICO funds are disbursed address private supportManager; // Account used by support team to reimburse users address private icoWallet; // Account to which ICO ETH is sent mapping(address => User) private users; // All registered users mapping(address => uint256) private vestingEscrows; // Unvested tokens held in escrow mapping(address => uint256) private authorizedContracts; // Contracts authorized to call this one address[] private registeredUserLookup; // Lookup table of registered users /* ERC-20 Contract Events */ event Approval // Fired when an account authorizes another account to spend tokens on its behalf ( address indexed owner, address indexed spender, uint256 value ); event Transfer // Fired when tokens are transferred from one account to another ( address indexed from, address indexed to, uint256 value ); /* Interface app-specific Events */ event UserRegister // Fired when a new user account (wallet) is registered ( address indexed user, uint256 value, uint256 seedJiffys ); event UserRefer // Fired when tokens are granted to a user for referring a new user ( address indexed user, address indexed referrer, uint256 value ); event UserLink // Fired when a previously existing user is linked to an account in the Interface DB ( address indexed user ); /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner); _; } /** * @dev Modifier that requires the "PlatformManager" account to be the function caller */ modifier requirePlatformManager() { require(isPlatformManager(msg.sender)); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * * @param tokenName ERC-20 token name * @param tokenSymbol ERC-20 token symbol * @param platformAccount Account for making calls from Interface API (i.e. PlatformManager) * @param icoAccount Account that holds ICO tokens (i.e. IcoOwner) * @param supportAccount Account with limited access to manage Interface user support (i.e. SupportManager) * */ function WHENToken ( string tokenName, string tokenSymbol, address platformAccount, address icoAccount, address supportAccount ) public { name = tokenName; symbol = tokenSymbol; jiffysMultiplier = 10 ** uint256(decimals); // Multiplier used throughout contract incentiveJiffysBalance = INCENTIVE_TOKENS.mul(jiffysMultiplier); // Network seeding tokens referralJiffysBalance = REFERRAL_TOKENS.mul(jiffysMultiplier); // User referral tokens contractOwner = msg.sender; // Owner of the contract platformManager = platformAccount; // API account for Interface icoOwner = icoAccount; // Account with ICO tokens for settling Interface transactions icoWallet = icoOwner; // Account to which ICO ETH is sent supportManager = supportAccount; // Support account with limited permissions // Create user records for accounts users[contractOwner] = User(true, 0, 0, address(0)); registeredUserLookup.push(contractOwner); users[platformManager] = User(true, 0, 0, address(0)); registeredUserLookup.push(platformManager); users[icoOwner] = User(true, 0, 0, address(0)); registeredUserLookup.push(icoOwner); users[supportManager] = User(true, 0, 0, address(0)); registeredUserLookup.push(supportManager); } /** * @dev Contract constructor * * Initialize is to be called immediately after the supporting contracts are deployed. * * @param dataContract Address of the deployed InterfaceData contract * @param appContract Address of the deployed InterfaceApp contract * @param vestingContract Address of the deployed TokenVesting contract * */ function initialize ( address dataContract, address appContract, address vestingContract ) external requireContractOwner { require(bonus20EndTimestamp == 0); // Ensures function cannot be called twice authorizeContract(dataContract); // Authorizes InterfaceData contract to make calls to this contract authorizeContract(appContract); // Authorizes InterfaceApp contract to make calls to this contract authorizeContract(vestingContract); // Authorizes TokenVesting contract to make calls to this contract bonus20EndTimestamp = ICO_START_TIMESTAMP.add(ONE_WEEK); bonus10EndTimestamp = bonus20EndTimestamp.add(ONE_WEEK); bonus5EndTimestamp = bonus10EndTimestamp.add(ONE_WEEK); // ICO tokens are allocated without vesting to ICO account for distribution during sale balances[icoOwner] = ICO_TOKENS.mul(jiffysMultiplier); // Platform tokens (a.k.a. network seeding tokens) are allocated without vesting balances[platformManager] = balances[platformManager].add(PLATFORM_TOKENS.mul(jiffysMultiplier)); // Allocate all other tokens to contract owner without vesting // These will be disbursed in initialize() balances[contractOwner] = balances[contractOwner].add((COMPANY_TOKENS + PARTNER_TOKENS + FOUNDATION_TOKENS).mul(jiffysMultiplier)); userSignupJiffys = jiffysMultiplier.mul(500); // Initial signup incentive referralSignupJiffys = jiffysMultiplier.mul(100); // Initial referral incentive } /** * @dev Token allocations for various accounts * * Called from TokenVesting to grant tokens to each account * */ function getTokenAllocations() external view returns(uint256, uint256, uint256) { return (COMPANY_TOKENS.mul(jiffysMultiplier), PARTNER_TOKENS.mul(jiffysMultiplier), FOUNDATION_TOKENS.mul(jiffysMultiplier)); } /********************************************************************************************/ /* ERC20 TOKEN */ /********************************************************************************************/ /** * @dev Total supply of tokens */ function totalSupply() external view returns (uint) { uint256 total = ICO_TOKENS.add(PLATFORM_TOKENS).add(COMPANY_TOKENS).add(PARTNER_TOKENS).add(FOUNDATION_TOKENS); return total.mul(jiffysMultiplier); } /** * @dev Gets the balance of the calling address. * * @return An uint256 representing the amount owned by the calling address */ function balance() public view returns (uint256) { return balanceOf(msg.sender); } /** * @dev Gets the balance of the specified address. * * @param owner The address to query the balance of * @return An uint256 representing the amount owned by the passed address */ function balanceOf ( address owner ) public view returns (uint256) { return balances[owner]; } /** * @dev Transfers token for a specified address * * Constraints are added to ensure that tokens granted for network * seeding and tokens in escrow are not transferable * * @param to The address to transfer to. * @param value The amount to be transferred. * @return A bool indicating if the transfer was successful. */ function transfer ( address to, uint256 value ) public requireIsOperational returns (bool) { require(to != address(0)); require(to != msg.sender); require(value <= transferableBalanceOf(msg.sender)); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); return true; } /** * @dev Transfers tokens from one address to another * * Constraints are added to ensure that tokens granted for network * seeding and tokens in escrow are not transferable * * @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 * @return A bool indicating if the transfer was successful. */ function transferFrom ( address from, address to, uint256 value ) public requireIsOperational returns (bool) { require(from != address(0)); require(value <= allowed[from][msg.sender]); require(value <= transferableBalanceOf(from)); require(to != address(0)); require(from != to); 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 Checks 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 Approves 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. * @return A bool indicating success (always returns true) */ function approve ( address spender, uint256 value ) public requireIsOperational returns (bool) { allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } /** * @dev Gets the balance of the specified address less greater of escrow tokens and free signup tokens. * * @param account The address to query the the balance of. * @return An uint256 representing the transferable amount owned by the passed address. */ function transferableBalanceOf ( address account ) public view returns (uint256) { require(account != address(0)); if (users[account].isRegistered) { uint256 restrictedJiffys = users[account].interfaceEscrowJiffys >= users[account].seedJiffys ? users[account].interfaceEscrowJiffys : users[account].seedJiffys; return balances[account].sub(restrictedJiffys); } return balances[account]; } /** * @dev Gets the balance of the specified address less escrow tokens * * Since seed tokens can be used to pay for Interface transactions * this balance indicates what the user can afford to spend for such * "internal" transactions ignoring distinction between paid and signup tokens * * @param account The address to query the balance of. * @return An uint256 representing the spendable amount owned by the passed address. */ function spendableBalanceOf ( address account ) public view returns(uint256) { require(account != address(0)); if (users[account].isRegistered) { return balances[account].sub(users[account].interfaceEscrowJiffys); } return balances[account]; } /********************************************************************************************/ /* WHENHUB INTERFACE */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this * one will fail * @return A bool that is the new operational mode */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /** * @dev Authorizes ICO end and burn of remaining tokens * * ContractOwner, PlatformManager and IcoOwner must each call this function * in any order. The third entity calling the function will cause the * icoOwner account balance to be reset to 0. */ function authorizeIcoBurn() external { require(balances[icoOwner] > 0); require((msg.sender == contractOwner) || (msg.sender == platformManager) || (msg.sender == icoOwner)); if (msg.sender == contractOwner) { icoBurnAuthorized.contractOwner = true; } else if (msg.sender == platformManager) { icoBurnAuthorized.platformManager = true; } else if (msg.sender == icoOwner) { icoBurnAuthorized.icoOwner = true; } if (icoBurnAuthorized.contractOwner && icoBurnAuthorized.platformManager && icoBurnAuthorized.icoOwner) { balances[icoOwner] = 0; } } /** * @dev Sets fee used in Interface transactions * * A network fee is charged for each transaction represented * as a percentage of the total fee payable to Experts. This fee * is deducted from the amount paid by Callers to Experts. * @param basisPoints The fee percentage expressed as basis points */ function setWinNetworkFee ( uint256 basisPoints ) external requireIsOperational requireContractOwner { require(basisPoints >= 0); winNetworkFeeBasisPoints = basisPoints; } /** * @dev Sets signup tokens allocated for each user (based on availability) * * @param tokens The number of tokens each user gets */ function setUserSignupTokens ( uint256 tokens ) external requireIsOperational requireContractOwner { require(tokens <= 10000); userSignupJiffys = jiffysMultiplier.mul(tokens); } /** * @dev Sets signup tokens allocated for each user (based on availability) * * @param tokens The number of tokens each referrer and referree get */ function setReferralSignupTokens ( uint256 tokens ) external requireIsOperational requireContractOwner { require(tokens <= 10000); referralSignupJiffys = jiffysMultiplier.mul(tokens); } /** * @dev Sets wallet to which ICO ETH funds are sent * * @param account The address to which ETH funds are sent */ function setIcoWallet ( address account ) external requireIsOperational requireContractOwner { require(account != address(0)); icoWallet = account; } /** * @dev Authorizes a smart contract to call this contract * * @param account Address of the calling smart contract */ function authorizeContract ( address account ) public requireIsOperational requireContractOwner { require(account != address(0)); authorizedContracts[account] = 1; } /** * @dev Deauthorizes a previously authorized smart contract from calling this contract * * @param account Address of the calling smart contract */ function deauthorizeContract ( address account ) external requireIsOperational requireContractOwner { require(account != address(0)); delete authorizedContracts[account]; } /** * @dev Checks if a contract is authorized to call this contract * * @param account Address of the calling smart contract */ function isContractAuthorized ( address account ) public view returns(bool) { return authorizedContracts[account] == 1; } /** * @dev Sets the Wei to WHEN exchange rate * * @param rate Number of Wei for one WHEN token */ function setWeiExchangeRate ( uint256 rate ) external requireIsOperational requireContractOwner { require(rate >= 0); // Cannot set to less than 0.0001 ETH/₩ weiExchangeRate = rate; } /** * @dev Sets the U.S. cents to WHEN exchange rate * * @param rate Number of cents for one WHEN token */ function setCentsExchangeRate ( uint256 rate ) external requireIsOperational requireContractOwner { require(rate >= 1); centsExchangeRate = rate; } /** * @dev Sets the account that will be used for Platform Manager functions * * @param account Account to replace existing Platform Manager */ function setPlatformManager ( address account ) external requireIsOperational requireContractOwner { require(account != address(0)); require(account != platformManager); balances[account] = balances[account].add(balances[platformManager]); balances[platformManager] = 0; if (!users[account].isRegistered) { users[account] = User(true, 0, 0, address(0)); registeredUserLookup.push(account); } platformManager = account; } /** * @dev Checks if an account is the PlatformManager * * @param account Account to check */ function isPlatformManager ( address account ) public view returns(bool) { return account == platformManager; } /** * @dev Checks if an account is the PlatformManager or SupportManager * * @param account Account to check */ function isPlatformOrSupportManager ( address account ) public view returns(bool) { return (account == platformManager) || (account == supportManager); } /** * @dev Gets address of SupportManager * */ function getSupportManager() public view returns(address) { return supportManager; } /** * @dev Checks if referral tokens are available * * referralSignupTokens is doubled because both referrer * and recipient get referral tokens * * @return A bool indicating if referral tokens are available */ function isReferralSupported() public view returns(bool) { uint256 requiredJiffys = referralSignupJiffys.mul(2); return (referralJiffysBalance >= requiredJiffys) && (balances[platformManager] >= requiredJiffys); } /** * @dev Checks if user is a registered user * * @param account The address which owns the funds. * @return A bool indicating if user is a registered user. */ function isUserRegistered ( address account ) public view returns(bool) { return (account != address(0)) && users[account].isRegistered; } /** * @dev Checks pre-reqs and handles user registration * * @param account The address which is to be registered * @param creditAccount The address which contains token credits from CC purchase * @param referrer The address referred the account */ function processRegisterUser ( address account, address creditAccount, address referrer ) private { require(account != address(0)); // No invalid account require(!users[account].isRegistered); // No double registration require(referrer == address(0) ? true : users[referrer].isRegistered); // Referrer, if present, must be a registered user require(referrer != account); // User can't refer her/himself // Initialize user with restricted jiffys users[account] = User(true, 0, 0, referrer); registeredUserLookup.push(account); if (purchaseCredits[creditAccount].jiffys > 0) { processPurchase(creditAccount, account, purchaseCredits[creditAccount].jiffys, purchaseCredits[creditAccount].purchaseTimestamp); purchaseCredits[creditAccount].jiffys = 0; delete purchaseCredits[creditAccount]; } } /** * @dev Registers a user wallet with a referrer and deposits any applicable signup tokens * * @param account The wallet address * @param creditAccount The address containing any tokens purchased with USD * @param referrer The referring user address * @return A uint256 with the user's token balance */ function registerUser ( address account, address creditAccount, address referrer ) public requireIsOperational requirePlatformManager returns(uint256) { processRegisterUser(account, creditAccount, referrer); UserRegister(account, balanceOf(account), 0); // Fire event return balanceOf(account); } /** * @dev Registers a user wallet with a referrer and deposits any applicable bonus tokens * * @param account The wallet address * @param creditAccount The address containing any tokens purchased with USD * @param referrer The referring user address * @return A uint256 with the user's token balance */ function registerUserBonus ( address account, address creditAccount, address referrer ) external requireIsOperational requirePlatformManager returns(uint256) { processRegisterUser(account, creditAccount, referrer); // Allocate if there are any remaining signup tokens uint256 jiffys = 0; if ((incentiveJiffysBalance >= userSignupJiffys) && (balances[platformManager] >= userSignupJiffys)) { incentiveJiffysBalance = incentiveJiffysBalance.sub(userSignupJiffys); users[account].seedJiffys = users[account].seedJiffys.add(userSignupJiffys); transfer(account, userSignupJiffys); jiffys = userSignupJiffys; } UserRegister(account, balanceOf(account), jiffys); // Fire event // Allocate referral tokens for both user and referrer if available if ((referrer != address(0)) && isReferralSupported()) { referralJiffysBalance = referralJiffysBalance.sub(referralSignupJiffys.mul(2)); // Referal tokens are restricted so it is necessary to update user's account transfer(referrer, referralSignupJiffys); users[referrer].seedJiffys = users[referrer].seedJiffys.add(referralSignupJiffys); transfer(account, referralSignupJiffys); users[account].seedJiffys = users[account].seedJiffys.add(referralSignupJiffys); UserRefer(account, referrer, referralSignupJiffys); // Fire event } return balanceOf(account); } /** * @dev Adds Jiffys to escrow for a user * * Escrows track the number of Jiffys that the user may owe another user. * This function is called by the InterfaceData contract when a caller * subscribes to a call. * * @param account The wallet address * @param jiffys The number of Jiffys to put into escrow */ function depositEscrow ( address account, uint256 jiffys ) external requireIsOperational { if (jiffys > 0) { require(isContractAuthorized(msg.sender) || isPlatformManager(msg.sender)); require(isUserRegistered(account)); require(spendableBalanceOf(account) >= jiffys); users[account].interfaceEscrowJiffys = users[account].interfaceEscrowJiffys.add(jiffys); } } /** * @dev Refunds Jiffys from escrow for a user * * This function is called by the InterfaceData contract when a caller * unsubscribes from a call. * * @param account The wallet address * @param jiffys The number of Jiffys to remove from escrow */ function refundEscrow ( address account, uint256 jiffys ) external requireIsOperational { if (jiffys > 0) { require(isContractAuthorized(msg.sender) || isPlatformManager(msg.sender)); require(isUserRegistered(account)); require(users[account].interfaceEscrowJiffys >= jiffys); users[account].interfaceEscrowJiffys = users[account].interfaceEscrowJiffys.sub(jiffys); } } /** * @dev Handles payment for an Interface transaction * * This function is called by the InterfaceData contract when the front-end * application makes a settle() call indicating that the transaction is * complete and it's time to pay the Expert. To prevent unauthorized use * the function is only callable by a previously authorized contract and * is limited to paying out funds previously escrowed. * * @param payer The account paying (i.e. a caller) * @param payee The account being paid (i.e. the Expert) * @param referrer The account that referred payer to payee * @param referralFeeBasisPoints The referral fee payable to referrer * @param billableJiffys The number of Jiffys for payment * @param escrowJiffys The number of Jiffys held in escrow for Interface being paid */ function pay ( address payer, address payee, address referrer, uint256 referralFeeBasisPoints, uint256 billableJiffys, uint256 escrowJiffys ) external requireIsOperational returns(uint256, uint256) { require(isContractAuthorized(msg.sender)); require(billableJiffys >= 0); require(users[payer].interfaceEscrowJiffys >= billableJiffys); // Only payment of Interface escrowed funds is allowed require(users[payee].isRegistered); // This function may be called if the Expert's surety is // being forfeited. In that case, the payment is made to the // Support and then funds will be distributed as appropriate // to parties following a grievance process. Since the rules // for forfeiture can get very complex, they are best handled // off-contract. payee == supportManager indicates a forfeiture. // First, release Payer escrow users[payer].interfaceEscrowJiffys = users[payer].interfaceEscrowJiffys.sub(escrowJiffys); uint256 referralFeeJiffys = 0; uint256 winNetworkFeeJiffys = 0; if (billableJiffys > 0) { // Second, pay the payee processPayment(payer, payee, billableJiffys); // Payee is SupportManager if Expert surety is being forfeited, so skip referral and network fees if (payee != supportManager) { // Third, Payee pays Referrer and referral fees due if ((referralFeeBasisPoints > 0) && (referrer != address(0)) && (users[referrer].isRegistered)) { referralFeeJiffys = billableJiffys.mul(referralFeeBasisPoints).div(BASIS_POINTS_TO_PERCENTAGE); // Basis points to percentage conversion processPayment(payee, referrer, referralFeeJiffys); } // Finally, Payee pays contract owner WIN network fee if (winNetworkFeeBasisPoints > 0) { winNetworkFeeJiffys = billableJiffys.mul(winNetworkFeeBasisPoints).div(BASIS_POINTS_TO_PERCENTAGE); // Basis points to percentage conversion processPayment(payee, contractOwner, winNetworkFeeJiffys); } } } return(referralFeeJiffys, winNetworkFeeJiffys); } /** * @dev Handles actual token transfer for payment * * @param payer The account paying * @param payee The account being paid * @param jiffys The number of Jiffys for payment */ function processPayment ( address payer, address payee, uint256 jiffys ) private { require(isUserRegistered(payer)); require(isUserRegistered(payee)); require(spendableBalanceOf(payer) >= jiffys); balances[payer] = balances[payer].sub(jiffys); balances[payee] = balances[payee].add(jiffys); Transfer(payer, payee, jiffys); // In the event the payer had received any signup tokens, their value // would be stored in the seedJiffys property. When any contract payment // is made, we reduce the seedJiffys number. seedJiffys tracks how many // tokens are not allowed to be transferred out of an account. As a user // makes payments to other users, those tokens have served their purpose // of encouraging use of the network and are no longer are restricted. if (users[payer].seedJiffys >= jiffys) { users[payer].seedJiffys = users[payer].seedJiffys.sub(jiffys); } else { users[payer].seedJiffys = 0; } } /** * @dev Handles transfer of tokens for vesting grants * * This function is called by the TokenVesting contract. To prevent unauthorized * use the function is only callable by a previously authorized contract. * * @param issuer The account granting tokens * @param beneficiary The account being granted tokens * @param vestedJiffys The number of vested Jiffys for immediate payment * @param unvestedJiffys The number of unvested Jiffys to be placed in escrow */ function vestingGrant ( address issuer, address beneficiary, uint256 vestedJiffys, uint256 unvestedJiffys ) external requireIsOperational { require(isContractAuthorized(msg.sender)); require(spendableBalanceOf(issuer) >= unvestedJiffys.add(vestedJiffys)); // Any vestedJiffys are transferred immediately to the beneficiary if (vestedJiffys > 0) { balances[issuer] = balances[issuer].sub(vestedJiffys); balances[beneficiary] = balances[beneficiary].add(vestedJiffys); Transfer(issuer, beneficiary, vestedJiffys); } // Any unvestedJiffys are removed from the granting account balance // A corresponding number of Jiffys is added to the granting account's // vesting escrow balance. balances[issuer] = balances[issuer].sub(unvestedJiffys); vestingEscrows[issuer] = vestingEscrows[issuer].add(unvestedJiffys); } /** * @dev Handles transfer of tokens for vesting revokes and releases * * This function is called by the TokenVesting contract. To prevent unauthorized * use the function is only callable by a previously authorized contract. * * @param issuer The account granting tokens * @param beneficiary The account being granted tokens * @param jiffys The number of Jiffys for release or revoke */ function vestingTransfer ( address issuer, address beneficiary, uint256 jiffys ) external requireIsOperational { require(isContractAuthorized(msg.sender)); require(vestingEscrows[issuer] >= jiffys); vestingEscrows[issuer] = vestingEscrows[issuer].sub(jiffys); balances[beneficiary] = balances[beneficiary].add(jiffys); Transfer(issuer, beneficiary, jiffys); } /** * @dev Gets an array of addresses registered with contract * * This can be used by API to enumerate all users */ function getRegisteredUsers() external view requirePlatformManager returns(address[]) { return registeredUserLookup; } /** * @dev Gets an array of addresses registered with contract * * This can be used by API to enumerate all users */ function getRegisteredUser ( address account ) external view requirePlatformManager returns(uint256, uint256, uint256, address) { require(users[account].isRegistered); return (balances[account], users[account].seedJiffys, users[account].interfaceEscrowJiffys, users[account].referrer); } /** * @dev Returns ICO-related state information for use by API */ function getIcoInfo() public view returns(bool, uint256, uint256, uint256, uint256, uint256) { return ( balances[icoOwner] > 0, weiExchangeRate, centsExchangeRate, bonus20EndTimestamp, bonus10EndTimestamp, bonus5EndTimestamp ); } /********************************************************************************************/ /* TOKEN SALE */ /********************************************************************************************/ /** * @dev Fallback function for buying ICO tokens. This is not expected to be called with * default gas as it will most certainly fail. * */ function() external payable { buy(msg.sender); } /** * @dev Buy ICO tokens * * @param account Account that is buying tokens * */ function buy ( address account ) public payable requireIsOperational { require(balances[icoOwner] > 0); require(account != address(0)); require(msg.value >= weiExchangeRate); // Minimum 1 token uint256 weiReceived = msg.value; // Convert Wei to Jiffys based on the exchange rate uint256 buyJiffys = weiReceived.mul(jiffysMultiplier).div(weiExchangeRate); processPurchase(icoOwner, account, buyJiffys, now); icoWallet.transfer(msg.value); } /** * @dev Buy ICO tokens with USD * * @param account Account that is buying tokens * @param cents Purchase amount in cents * */ function buyUSD ( address account, uint256 cents ) public requireIsOperational requirePlatformManager { require(balances[icoOwner] > 0); require(account != address(0)); require(cents >= centsExchangeRate); // Minimum 1 token // Convert Cents to Jiffys based on the exchange rate uint256 buyJiffys = cents.mul(jiffysMultiplier).div(centsExchangeRate); if (users[account].isRegistered) { processPurchase(icoOwner, account, buyJiffys, now); } else { // Purchased credits will be transferred to account when user registers // They are kept in a holding area until then. We deduct buy+bonus from // icoOwner because that is the amount that will eventually be credited. // However, we store the credit as buyJiffys so that the referral calculation // will be against the buy amount and not the buy+bonus amount uint256 totalJiffys = buyJiffys.add(calculatePurchaseBonus(buyJiffys, now)); balances[icoOwner] = balances[icoOwner].sub(totalJiffys); balances[account] = balances[account].add(totalJiffys); purchaseCredits[account] = PurchaseCredit(buyJiffys, now); Transfer(icoOwner, account, buyJiffys); } } /** * @dev Process token purchase * * @param account Account that is buying tokens * @param buyJiffys Number of Jiffys purchased * */ function processPurchase ( address source, address account, uint256 buyJiffys, uint256 purchaseTimestamp ) private { uint256 totalJiffys = buyJiffys.add(calculatePurchaseBonus(buyJiffys, purchaseTimestamp)); // Transfer purchased Jiffys to buyer require(transferableBalanceOf(source) >= totalJiffys); balances[source] = balances[source].sub(totalJiffys); balances[account] = balances[account].add(totalJiffys); Transfer(source, account, totalJiffys); // If the buyer has a referrer attached to their profile, then // transfer 3% of the purchased Jiffys to the referrer's account if (users[account].isRegistered && (users[account].referrer != address(0))) { address referrer = users[account].referrer; uint256 referralJiffys = (buyJiffys.mul(BUYER_REFERRER_BOUNTY)).div(100); if ((referralJiffys > 0) && (transferableBalanceOf(icoOwner) >= referralJiffys)) { balances[icoOwner] = balances[icoOwner].sub(referralJiffys); balances[referrer] = balances[referrer].add(referralJiffys); Transfer(icoOwner, referrer, referralJiffys); } } } /** * @dev Calculates ICO bonus tokens * * @param buyJiffys Number of Jiffys purchased * */ function calculatePurchaseBonus ( uint256 buyJiffys, uint256 purchaseTimestamp ) private view returns(uint256) { uint256 bonusPercentage = 0; // Time-based bonus if (purchaseTimestamp <= bonus5EndTimestamp) { if (purchaseTimestamp <= bonus10EndTimestamp) { if (purchaseTimestamp <= bonus20EndTimestamp) { bonusPercentage = 20; } else { bonusPercentage = 10; } } else { bonusPercentage = 5; } } return (buyJiffys.mul(bonusPercentage)).div(100); } } /* LICENSE FOR SafeMath and TokenVesting The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library SafeMath { /* Copyright (c) 2016 Smart Contract Solutions, Inc. */ /* See License at end of file */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Token allocations for various accounts Called from TokenVesting to grant tokens to each account/
function getTokenAllocations() external view returns(uint256, uint256, uint256) { return (COMPANY_TOKENS.mul(jiffysMultiplier), PARTNER_TOKENS.mul(jiffysMultiplier), FOUNDATION_TOKENS.mul(jiffysMultiplier)); }
1,334,538
./full_match/4/0x0C040d1b7Ba29106a54689a4a282CD9dd9f2f2B2/sources/contracts/MeFi.sol
Creates the Chainlink request Stores the hash of the params as the on-chain commitment for the request. Emits OracleRequest event for the Chainlink node to detect. _sender The sender of the request _payment The amount of payment given (specified in wei) _specId The Job Specification ID _callbackAddress The callback address for the response _callbackFunctionId The callback function ID for the response _nonce The nonce sent by the requester _dataVersion The specified data version _data The CBOR payload of the request/ solhint-disable-next-line not-rely-on-time
function oracleRequest( address _sender, uint256 _payment, bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionId, uint256 _nonce, uint256 _dataVersion, bytes calldata _data ) external override onlyMDT() checkCallbackAddress(_callbackAddress) { bytes32 requestId = keccak256(abi.encodePacked(_sender, _nonce)); require(commitments[requestId] == 0, "Must use a unique ID"); uint256 expiration = now.add(EXPIRY_TIME); commitments[requestId] = keccak256( abi.encodePacked( _payment, _callbackAddress, _callbackFunctionId, expiration ) ); payments[requestId] = _payment; callbackAddresses[requestId] = _callbackAddress; callbackFunctionIndices[requestId] = _callbackFunctionId; expirations[requestId] = expiration; forwardRequest(_specId, "AAPL", _payment); }
12,495,724
/** * OpenZepplin contracts contained within are licensed under an MIT License. * * The MIT License (MIT) * * Copyright (c) 2016-2021 zOS Global Limited * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * SPDX-License-Identifier: MIT */ // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/security/ReentrancyGuard.sol pragma solidity ^0.8.0; abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } 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: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; 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: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Strings.sol pragma solidity ^0.8.0; library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; 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); } 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); } 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: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Context.sol pragma solidity ^0.8.0; 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: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Address.sol pragma solidity ^0.8.0; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } pragma solidity ^0.8.0; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name = "Igor - EtherCats.io"; // Token symbol string private _symbol = "IGOR"; // 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; function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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())) : "ipfs://QmY2RtPNfCYyJJW8CtbNWLs3GGSaUus5vG38g4kRZ5Ci7k"; } function _baseURI() internal view virtual returns (string memory) { return ""; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } 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); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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" ); } 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); } 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); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not owned"); 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); } function snipe( address from, address to, uint256 tokenId ) internal virtual { _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); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } 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; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } //Igor's Manifest is an EtherCats production. Igor was illustrated and animated by Nadia Khuzina. The principle concept was developed by Woody Deck. The contract was written by Woody Deck and Edvard Gzraryan. Special thanks to Vitalik Buterin for his inspiration in challenging economic dogma. contract IgorsManifest is ERC721, ReentrancyGuard { address public contractOwner; uint256 public snipeStep; uint256 public snipePrice; bool public snipeable; uint256 public blockTimerStartTime; string igorsHash; event Snipe(address indexed owner, uint256 price, uint256 step, uint256 blockTimestamp); event ExtendLeasehold(uint256 blockTimestamp); event DecreaseSnipeStep(uint256 price, uint256 step, uint256 blockTimestamp); constructor() { contractOwner = msg.sender; _safeMint(msg.sender, 1, ""); //Igor is minted as token ID number 1, and the contractOwner owns it initially. snipeStep = 0; snipePrice = snipePriceTable(snipeStep); snipeable = true; blockTimerStartTime = block.timestamp; igorsHash = "QmSGsx5Cs1zLxmMX8YjvGx1x1vYn47jzuFKy13yhM4S61q"; } //This is a lookup table to determine the cost to snipe Igor from someone. function snipePriceTable(uint256 _snipeStep) internal pure returns(uint256 _snipePrice) { if (_snipeStep == 0) return 0.1 * 10 ** 18; else if (_snipeStep == 1) return 0.15 * 10 ** 18; else if (_snipeStep == 2) return 0.21 * 10 ** 18; else if (_snipeStep == 3) return 0.28 * 10 ** 18; else if (_snipeStep == 4) return 0.36 * 10 ** 18; else if (_snipeStep == 5) return 0.45 * 10 ** 18; else if (_snipeStep == 6) return 0.55 * 10 ** 18; else if (_snipeStep == 7) return 0.66 * 10 ** 18; else if (_snipeStep == 8) return 0.78 * 10 ** 18; else if (_snipeStep == 9) return 1 * 10 ** 18; else if (_snipeStep == 10) return 1.5 * 10 ** 18; else if (_snipeStep == 11) return 2.2 * 10 ** 18; else if (_snipeStep == 12) return 3 * 10 ** 18; else if (_snipeStep == 13) return 4 * 10 ** 18; else if (_snipeStep == 14) return 6 * 10 ** 18; else if (_snipeStep == 15) return 8.5 * 10 ** 18; else if (_snipeStep == 16) return 12 * 10 ** 18; else if (_snipeStep == 17) return 17 * 10 ** 18; else if (_snipeStep == 18) return 25 * 10 ** 18; else if (_snipeStep == 19) return 35 * 10 ** 18; else if (_snipeStep == 20) return 47 * 10 ** 18; else if (_snipeStep == 21) return 60 * 10 ** 18; else if (_snipeStep == 22) return 75 * 10 ** 18; else if (_snipeStep == 23) return 92 * 10 ** 18; else if (_snipeStep == 24) return 110 * 10 ** 18; else if (_snipeStep == 25) return 130 * 10 ** 18; else if (_snipeStep == 26) return 160 * 10 ** 18; else if (_snipeStep == 27) return 200 * 10 ** 18; else if (_snipeStep == 28) return 250 * 10 ** 18; else if (_snipeStep == 29) return 310 * 10 ** 18; else if (_snipeStep == 30) return 380 * 10 ** 18; else if (_snipeStep == 31) return 460 * 10 ** 18; else if (_snipeStep == 32) return 550 * 10 ** 18; else if (_snipeStep == 33) return 650 * 10 ** 18; else if (_snipeStep == 34) return 760 * 10 ** 18; } modifier onlyIgorOwner() { require(msg.sender == ownerOf(1), "Sender is not the owner of Igor."); _; } function snipeIgor() external payable nonReentrant { require(msg.sender != ownerOf(1), "You cannot snipe Igor from the address that already owns him."); require(msg.value == snipePrice, "The amount sent did not match the current snipePrice."); require(snipeable == true, "Sniping is permanently disabled. Igor is owned as a freehold now."); address tokenOwner = ownerOf(1); //If the snipeStep is 0, then all proceeds go to the owner. if (snipeStep == 0) { snipeStep++; snipePrice = snipePriceTable(snipeStep); snipe(tokenOwner, msg.sender, 1); (bool sent,) = payable(tokenOwner).call{ value: msg.value }(""); require(sent, "Failed to send Ether."); } else { //Else is all cases after Step 0. uint256 etherCatsRoyalty = (msg.value - snipePriceTable(snipeStep - 1)) * 25 / 100; uint256 payment = msg.value - etherCatsRoyalty; if (snipeStep < 34) { snipeStep++; snipePrice = snipePriceTable(snipeStep); } //Automatically stop sniping if Igor is sniped on Step 33. if (snipeStep == 34) { snipeable = false; } snipe(tokenOwner, msg.sender, 1); (bool paymentSent,) = payable(tokenOwner).call{ value: payment }(""); require(paymentSent, "Failed to send Ether."); (bool royaltySent,) = payable(contractOwner).call{ value: etherCatsRoyalty }(""); require(royaltySent, "Failed to send Ether."); } blockTimerStartTime = block.timestamp; emit Snipe(msg.sender, snipePrice, snipeStep, blockTimerStartTime); } //This option disables sniping permanently. It will behave like a normal ERC721 after this function is triggered. It can only be called by Igor's owner. function permanentlyStopSniping() external payable onlyIgorOwner { require(snipeStep <= 20, "Igor can only be bought out on snipe steps before Step 21."); require(msg.value == 141 * 10 ** 18, "The amount sent did not match the freehold option amount."); require(snipeable == true, "Cannot disable sniping twice. Igor is already not snipeable."); snipeable = false; (bool sent,) = payable(contractOwner).call{ value: msg.value }(""); require(sent, "Failed to send Ether."); } //To prevent people from reducing the snipe step, you must pay 1/1000th (0.1%) tax to the creator every two weeks. Activating this function early or multiple times does not result in time accumulating. It will always reset the countdown clock back to 1209600 seconds (two weeks). function extendLeasehold() external payable onlyIgorOwner { require(snipeStep >= 1, "You cannot extend the leasehold timer when it is step zero."); require(msg.value == snipePriceTable(snipeStep-1) / 1000, "The price to extend is 1/1000th of the current value, or the snipe step minus 1"); require(snipeable == true, "Cannot extend. Igor is not snipeable anymore, sorry."); blockTimerStartTime = block.timestamp; (bool sent,) = payable(contractOwner).call{ value: msg.value }(""); require(sent, "Failed to send Ether."); emit ExtendLeasehold(blockTimerStartTime); } //If the owner after 1209600 seconds (two weeks) has not paid the extension tax, then anyone can reduce the snipeStep by 1. function decreaseSnipeStep() external { require(block.timestamp - blockTimerStartTime > 1209600, "You cannot reduce the snipe step until after the lease is up."); require(snipeStep >= 1, "You cannot reduce the snipe step when it is at zero."); require(snipeStep < 34, "You cannot reduce the snipe step once it reaches step 34."); require(snipeable == true, "Igor is not snipeable anymore, sorry."); snipeStep--; snipePrice = snipePriceTable(snipeStep); blockTimerStartTime = block.timestamp; emit DecreaseSnipeStep(snipePrice, snipeStep, blockTimerStartTime); } //This function is for site owners to vet that Igor is only shown by the Ethereum address that owns him. This is conceptual, and only facilitates the possibility of restricting PFP NFTs from being displayed by accounts that do not own the NFT. It is up to a site to implement such a process on its own. It is not mandated by the terms of this contract. Reputable sites concerned about security will never store or even ask you to create a password. Reputable sites will require Web3 authentication for logins. Adding PFP avatar restrictions is trivial after adopting Web3 for authentication. function pfpOwner() external view returns (address igorsOwner, string memory igorsIPFSHash){ return (ownerOf(1), igorsHash); } //There's only one Igor. Some frontends may look for this optional ERC721 implementation. function totalSupply() public pure returns (uint256) { return 1; } }
If the owner after 1209600 seconds (two weeks) has not paid the extension tax, then anyone can reduce the snipeStep by 1.
function decreaseSnipeStep() external { require(block.timestamp - blockTimerStartTime > 1209600, "You cannot reduce the snipe step until after the lease is up."); require(snipeStep >= 1, "You cannot reduce the snipe step when it is at zero."); require(snipeStep < 34, "You cannot reduce the snipe step once it reaches step 34."); require(snipeable == true, "Igor is not snipeable anymore, sorry."); snipeStep--; snipePrice = snipePriceTable(snipeStep); blockTimerStartTime = block.timestamp; emit DecreaseSnipeStep(snipePrice, snipeStep, blockTimerStartTime); }
1,510,562
pragma solidity ^0.4.24; /** * Version: 0.1.0 * The ERC-1384 is an Equity Agreement Standard used for smart contracts on Ethereum * blockchain for project equity allocation. * The current ERC-1384 agreement standard version is 0.1.0, which includes the basic * information of the project query, equity creation, confirmation of equity validity, * equity transfer, record of equity transfer and other functions. */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } } contract ERC20 { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ERC1384Interface { function name() external view returns (string _name); function FasNum() external view returns (uint256 _FasNum); function owner() external view returns (address _owner); function createTime() external view returns (uint256 _createTime); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _FasId) public view returns (address _owner); function exists(uint256 _FasId) public view returns (bool); function allOwnedFas(address _owner) public view returns (uint256[] _allOwnedFasList); function getTransferRecords(uint256 _FasId) public view returns (address[] _preOwners); function transfer(address _to, uint256[] _FasId) public; function createVote() public payable returns (uint256 _voteId); function vote(uint256 _voteId, uint256 _vote_status_value) public; function getVoteResult(uint256 _voteId) public payable returns (bool result); function dividend(address _token_owner) public; event Transfer( address indexed _from, address indexed _to, uint256 indexed _FasId ); event Vote( uint256 _voteId ); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address internal project_owner; address internal new_project_owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { project_owner = msg.sender; } modifier onlyOwner { require(msg.sender == project_owner); _; } function transferOwnership(address _new_project_owner) public onlyOwner { new_project_owner = _new_project_owner; } } contract ERC1384BasicContract is ERC1384Interface, Owned { using SafeMath for uint256; // Project Name string internal proejct_name; // Project Fas Number uint256 internal project_fas_number; // Project Create Time uint256 internal project_create_time; // Owner Number uint256 internal owners_num; // Vote Number uint256 internal votes_num; address internal token_0x_address; /** * @dev Constructor function */ constructor(string _project_name, address _token_0x_address) public { proejct_name = _project_name; project_fas_number = 100; project_create_time = block.timestamp; token_0x_address = _token_0x_address; for(uint i = 0; i < project_fas_number; i++) { FasOwner[i] = project_owner; ownedFasCount[project_owner] = ownedFasCount[project_owner].add(1); address[1] memory preOwnerList = [project_owner]; transferRecords[i] = preOwnerList; } owners_num = 0; votes_num = 0; ownerExists[project_owner] = true; addOwnerNum(project_owner); } /** * @dev Gets the project name * @return string representing the project name */ function name() external view returns (string) { return proejct_name; } /** * @dev Gets the project Fas number * @return uint256 representing the project Fas number */ function FasNum() external view returns (uint256) { return project_fas_number; } /** * @dev Gets the project owner * @return address representing the project owner */ function owner() external view returns (address) { return project_owner; } /** * @dev Gets the project create time * @return uint256 representing the project create time */ function createTime() external view returns (uint256) { return project_create_time; } // Mapping from number of owner to owner mapping (uint256 => address) internal ownerNum; mapping (address => bool) internal ownerExists; // Mapping from Fas ID to owner mapping (uint256 => address) internal FasOwner; // Mapping from owner to number of owned Fas mapping (address => uint256) internal ownedFasCount; // Mapping from Fas ID to approved address mapping (uint256 => address) internal FasApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; // Mapping from Fas ID to previous owners mapping (uint256 => address[]) internal transferRecords; // Mapping from vote ID to vote result mapping (uint256 => mapping (uint256 => uint256)) internal voteResult; function acceptOwnership() public { require(msg.sender == new_project_owner); emit OwnershipTransferred(project_owner, new_project_owner); transferForOwnerShip(project_owner, new_project_owner, allOwnedFas(project_owner)); project_owner = new_project_owner; new_project_owner = address(0); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedFasCount[_owner]; } /** * @dev Gets the owner of the specified Fas ID * @param _FasId uint256 ID of the Fas to query the owner of * @return owner address currently marked as the owner of the given Fas ID */ function ownerOf(uint256 _FasId) public view returns (address) { address _owner = FasOwner[_FasId]; require(_owner != address(0)); return _owner; } /** * @dev Returns whether the specified Fas exists * @param _FasId uint256 ID of the Fas to query the existence of * @return whether the Fas exists */ function exists(uint256 _FasId) public view returns (bool) { address _owner = FasOwner[_FasId]; return _owner != address(0); } /** * @dev Gets the owner of all owned Fas * @param _owner address to query the balance of * @return the FasId list of owners */ function allOwnedFas(address _owner) public view returns (uint256[]) { uint256 _ownedFasCount = ownedFasCount[_owner]; uint256 j = 0; uint256[] memory _allOwnedFasList = new uint256[](_ownedFasCount); for(uint256 i = 0; i < project_fas_number; i++) { if(FasOwner[i] == _owner) { _allOwnedFasList[j] = i; j = j.add(1); } } return _allOwnedFasList; } /** * @dev Internal function to add Owner Count to the list of a given address * @param _owner address representing the new owner */ function addOwnerNum(address _owner) internal { require(ownedFasCount[_owner] != 0); if(ownerExists[_owner] == false) { ownerNum[owners_num] = _owner; owners_num = owners_num.add(1); ownerExists[_owner] = true; } } /** * @dev Internal function to add a Fas ID to the list of a given address * @param _to address representing the new owner of the given Fas ID * @param _FasId uint256 ID of the Fas to be added to the Fas list of the given address */ function addFasTo(address _to, uint256 _FasId) internal { require(FasOwner[_FasId] == address(0)); FasOwner[_FasId] = _to; ownedFasCount[_to] = ownedFasCount[_to].add(1); } /** * @dev Internal function to remove a Fas ID from the list of a given address * @param _from address representing the previous owner of the given Fas ID * @param _FasId uint256 ID of the Fas to be removed from the Fas list of the given address */ function removeFasFrom(address _from, uint256 _FasId) internal { require(ownerOf(_FasId) == _from); ownedFasCount[_from] = ownedFasCount[_from].sub(1); FasOwner[_FasId] = address(0); } /** * @dev Returns whether the given spender can transfer a given Fas ID * @param _spender address of the spender to query * @param _FasId uint256 ID of the Fas to be transferred * @return bool whether the msg.sender is approved for the given Fas ID, * is an operator of the owner, or is the owner of the Fas */ function isOwner(address _spender, uint256 _FasId) internal view returns (bool){ address _owner = ownerOf(_FasId); return (_spender == _owner); } /** * @dev Record the transfer records for a Fas ID * @param _FasId uint256 ID of the Fas * @return bool record */ function transferRecord(address _nowOwner, uint256 _FasId) internal{ address[] memory preOwnerList = transferRecords[_FasId]; address[] memory _preOwnerList = new address[](preOwnerList.length + 1); for(uint i = 0; i < _preOwnerList.length; ++i) { if(i != preOwnerList.length) { _preOwnerList[i] = preOwnerList[i]; } else { _preOwnerList[i] = _nowOwner; } } transferRecords[_FasId] = _preOwnerList; } /** * @dev Gets the transfer records for a Fas ID * @param _FasId uint256 ID of the Fas * @return address of previous owners */ function getTransferRecords(uint256 _FasId) public view returns (address[]) { return transferRecords[_FasId]; } /** * @dev Transfers the ownership of a given Fas ID to a specified address * @param _project_owner the address of _project_owner * @param _to address to receive the ownership of the given Fas ID * @param _FasId uint256 ID of the Fas to be transferred */ function transferForOwnerShip(address _project_owner,address _to, uint256[] _FasId) internal{ for(uint i = 0; i < _FasId.length; i++) { require(isOwner(_project_owner, _FasId[i])); require(_to != address(0)); transferRecord(_to, _FasId[i]); removeFasFrom(_project_owner, _FasId[i]); addFasTo(_to, _FasId[i]); } addOwnerNum(_to); } /** * @dev Transfers the ownership of a given Fas ID to a specified address * @param _to address to receive the ownership of the given Fas ID * @param _FasId uint256 ID of the Fas to be transferred */ function transfer(address _to, uint256[] _FasId) public{ for(uint i = 0; i < _FasId.length; i++) { require(isOwner(msg.sender, _FasId[i])); require(_to != address(0)); transferRecord(_to, _FasId[i]); removeFasFrom(msg.sender, _FasId[i]); addFasTo(_to, _FasId[i]); emit Transfer(msg.sender, _to, _FasId[i]); } addOwnerNum(_to); } /** * @dev Create a new vote * @return the new vote of ID */ function createVote() public payable returns (uint256){ votes_num = votes_num.add(1); // Vote Agree Number voteResult[votes_num][0] = 0; // Vote Disagree Number voteResult[votes_num][1] = 0; // Vote Abstain Number voteResult[votes_num][2] = 0; // Start Voting Time voteResult[votes_num][3] = block.timestamp; emit Vote(votes_num); return votes_num; } /** * @dev Voting for a given vote ID * @param _voteId the given vote ID * @param _vote_status_value uint256 the vote of status, 0 Agree, 1 Disagree, 2 Abstain */ function vote(uint256 _voteId, uint256 _vote_status_value) public{ require(_vote_status_value >= 0); require(_vote_status_value <= 2); require(block.timestamp <= (voteResult[_voteId][3] + 1 days)); uint256 temp_Fas_count = balanceOf(msg.sender); if(_vote_status_value == 0) { voteResult[_voteId][0] = voteResult[_voteId][0].add(temp_Fas_count); } else if(_vote_status_value == 1) { voteResult[_voteId][1] = voteResult[_voteId][1].add(temp_Fas_count); } else { voteResult[_voteId][2] = voteResult[_voteId][2].add(temp_Fas_count); } } /** * @dev Gets the voting restult for a vote ID * @param _voteId the given vote ID * @return the voting restult, true success, false failure */ function getVoteResult(uint256 _voteId) public payable returns (bool){ require(block.timestamp > (voteResult[_voteId][3] + 1 days)); uint agree_num = voteResult[_voteId][0]; uint disagree_num = voteResult[_voteId][1]; uint abstain_num = voteResult[_voteId][2]; uint temp_abstain_num = 100 - agree_num - disagree_num; if(temp_abstain_num != abstain_num) { voteResult[_voteId][2] = temp_abstain_num; } if(agree_num > disagree_num) { return true; } else { return false; } } /** * @dev Distribution of benefits * @param _token_owner Divider's Token address */ function dividend(address _token_owner) public{ uint256 temp_allowance = ERC20(token_0x_address).allowance(_token_owner, address(this)); for(uint i = 0; i < owners_num; i++) { uint256 temp_Fas_count = balanceOf(ownerNum[i]); uint256 _dividend = temp_allowance * temp_Fas_count / 100; ERC20(token_0x_address).transferFrom(_token_owner, ownerNum[i], _dividend); } } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
Record the transfer records for a Fas ID _FasId uint256 ID of the Fas return bool record/
function transferRecord(address _nowOwner, uint256 _FasId) internal{ address[] memory preOwnerList = transferRecords[_FasId]; address[] memory _preOwnerList = new address[](preOwnerList.length + 1); for(uint i = 0; i < _preOwnerList.length; ++i) { if(i != preOwnerList.length) { _preOwnerList[i] = preOwnerList[i]; } else { _preOwnerList[i] = _nowOwner; } } transferRecords[_FasId] = _preOwnerList; }
12,981,256
// SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface IERC20 { function TOTALSUPPLY622() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF753(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER955(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL691(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER876(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFER955.selector, to, value)); } function SAFETRANSFERFROM621(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFERFROM690.selector, from, to, value)); } function SAFEAPPROVE2(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.ALLOWANCE76(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, value)); } function SAFEINCREASEALLOWANCE52(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE76(address(this), spender).ADD393(value); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE76(address(this), spender).SUB829(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN191(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).FUNCTIONCALL585(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 IWETH { function DEPOSIT379() external payable; //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function WITHDRAW91(uint) external; //inject NONSTANDARD NAMING } interface IUniswapV2Router01 { function FACTORY423() external pure returns (address); //inject NONSTANDARD NAMING function WETH656() external pure returns (address); //inject NONSTANDARD NAMING function ADDLIQUIDITY566( //inject NONSTANDARD NAMING 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 ADDLIQUIDITYETH439( //inject NONSTANDARD NAMING address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function REMOVELIQUIDITY294( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function REMOVELIQUIDITYETH142( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function REMOVELIQUIDITYWITHPERMIT785( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function REMOVELIQUIDITYETHWITHPERMIT822( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function SWAPEXACTTOKENSFORTOKENS694( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPTOKENSFOREXACTTOKENS112( //inject NONSTANDARD NAMING uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPEXACTETHFORTOKENS23(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function SWAPTOKENSFOREXACTETH134(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPEXACTTOKENSFORETH465(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPETHFOREXACTTOKENS477(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function QUOTE151(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING function GETAMOUNTOUT667(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING function GETAMOUNTIN118(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING function GETAMOUNTSOUT962(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING function GETAMOUNTSIN769(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING } interface IUniswapV2Router02 is IUniswapV2Router01 { function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS84( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS171( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS513( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS617( //inject NONSTANDARD NAMING uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS347( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Pair { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT816(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN577(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP591( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC313(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY897() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY423() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0588() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1553() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES947() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST382() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST280() external view returns (uint); //inject NONSTANDARD NAMING function KLAST968() external view returns (uint); //inject NONSTANDARD NAMING function MINT750(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN945(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP412(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM546(address to) external; //inject NONSTANDARD NAMING function SYNC14() external; //inject NONSTANDARD NAMING function INITIALIZE840(address, address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED444(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO98() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER656() external view returns (address); //inject NONSTANDARD NAMING function MIGRATOR786() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR761(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS341(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH448() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR119(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO526(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER51(address) external; //inject NONSTANDARD NAMING function SETMIGRATOR114(address) external; //inject NONSTANDARD NAMING } 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_entered266 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered280 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered266; } modifier NONREENTRANT384() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered280, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered280; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered266; } } library Math { function MAX80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN629(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE241(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } library Address { function ISCONTRACT204(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE55(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 FUNCTIONCALL585(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL585(target, data, "Address: low-level call failed"); } function FUNCTIONCALL585(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE394(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE130(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE130(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 _FUNCTIONCALLWITHVALUE394(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE394(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT204(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 { function ADD393(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB829(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB829(a, b, "SafeMath: subtraction overflow"); } function SUB829(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 MUL131(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 DIV283(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV283(a, b, "SafeMath: division by zero"); } function DIV283(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 MOD208(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD208(a, b, "SafeMath: modulo by zero"); } function MOD208(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library MathUtils { using SafeMath for uint256; function SQRT196(uint256 x) internal pure returns (uint256 y) { //inject NONSTANDARD NAMING uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function ROUNDEDDIV172(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, 'div by 0'); uint256 halfB = (b.MOD208(2) == 0) ? (b.DIV283(2)) : (b.DIV283(2).ADD393(1)); return (a.MOD208(b) >= halfB) ? (a.DIV283(b).ADD393(1)) : (a.DIV283(b)); } } interface IUniswapV2ERC20 { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING } interface IUniswapV2Callee { function UNISWAPV2CALL695(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING } interface IERC20Uniswap { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING } abstract contract Context { function _MSGSENDER27() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA543() 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; } } 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 NAME590() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL603() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS715() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY622() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF753(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER955(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER21(_MSGSENDER27(), recipient, amount); return true; } function ALLOWANCE76(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE213(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, amount); return true; } function TRANSFERFROM690(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER21(sender, recipient, amount); _APPROVE77(sender, _MSGSENDER27(), _allowances[sender][_MSGSENDER27()].SUB829(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE203(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].ADD393(addedValue)); return true; } function DECREASEALLOWANCE568(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].SUB829(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER21(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"); _BEFORETOKENTRANSFER156(sender, recipient, amount); _balances[sender] = _balances[sender].SUB829(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD393(amount); emit TRANSFER649(sender, recipient, amount); } function _MINT693(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER156(address(0), account, amount); _totalSupply = _totalSupply.ADD393(amount); _balances[account] = _balances[account].ADD393(amount); emit TRANSFER649(address(0), account, amount); } function _BURN313(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER156(account, address(0), amount); _balances[account] = _balances[account].SUB829(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB829(amount); emit TRANSFER649(account, address(0), amount); } function _APPROVE77(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 APPROVAL691(owner, spender, amount); } function _SETUPDECIMALS749(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER156(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event APPROVAL691(address indexed src, address indexed guy, uint wad); //inject NONSTANDARD NAMING event TRANSFER649(address indexed src, address indexed dst, uint wad); //inject NONSTANDARD NAMING event DEPOSIT981(address indexed dst, uint wad); //inject NONSTANDARD NAMING event WITHDRAWAL378(address indexed src, uint wad); //inject NONSTANDARD NAMING mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; receive() external payable { DEPOSIT379(); } function DEPOSIT379() public payable { //inject NONSTANDARD NAMING balanceOf[msg.sender] += msg.value; DEPOSIT981(msg.sender, msg.value); } function WITHDRAW91(uint wad) public { //inject NONSTANDARD NAMING require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); WITHDRAWAL378(msg.sender, wad); } function TOTALSUPPLY622() public view returns (uint) { //inject NONSTANDARD NAMING return address(this).balance; } function APPROVE213(address guy, uint wad) public returns (bool) { //inject NONSTANDARD NAMING allowance[msg.sender][guy] = wad; APPROVAL691(msg.sender, guy, wad); return true; } function TRANSFER955(address dst, uint wad) public returns (bool) { //inject NONSTANDARD NAMING return TRANSFERFROM690(msg.sender, dst, wad); } function TRANSFERFROM690(address src, address dst, uint wad) //inject NONSTANDARD NAMING public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(- 1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; TRANSFER649(src, dst, wad); return true; } } contract twis is ERC20 { address minter; modifier ONLYMINTER285 { //inject NONSTANDARD NAMING require(msg.sender == minter, 'Only minter can call this function.'); _; } constructor(address _minter) public ERC20('Twister', 'TWIS') { minter = _minter; } function MINT750(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING _MINT693(account, amount); } function BURN945(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING _BURN313(account, amount); } } contract Twister is ReentrancyGuard { using SafeMath for uint256; using Address for address; using SafeERC20 for IERC20; event STAKED534(address indexed from, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING event WITHDRAWN851(address indexed to, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING event CLAIMED515(address indexed to, uint256 amount); //inject NONSTANDARD NAMING event HALVING833(uint256 amount); //inject NONSTANDARD NAMING event RECEIVED501(address indexed from, uint256 amount); //inject NONSTANDARD NAMING twis public token; IUniswapV2Factory public factory; IUniswapV2Router02 public router; address public weth; address payable public treasury; address public pairAddress; struct AccountInfo { // Staked LP token balance uint256 balance; uint256 peakBalance; uint256 withdrawTimestamp; uint256 reward; uint256 rewardPerTokenPaid; } mapping(address => AccountInfo) public accountInfos; // Staked LP token total supply uint256 private _totalSupply = 0; uint256 public constant halving_duration255 = 7 days; //inject NONSTANDARD NAMING uint256 public rewardAllocation = 1500 * 1e18; uint256 public halvingTimestamp = 0; uint256 public lastUpdateTimestamp = 0; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored = 0; // Farming will be open on this timestamp // Date and time (GMT): Monday, October 26, 2020 3:00:00 PM uint256 public farmingStartTimestamp = 1604635200; bool public farmingStarted = false; // Max 10% / day LP withdraw uint256 public constant withdraw_limit638 = 10; //inject NONSTANDARD NAMING // Burn address address constant burn_address389 = 0x000000000000000000000000000000000000dEaD; //inject NONSTANDARD NAMING // Dev decided to launch without whitelist but since it has been coded and tested, so dev will leave it here. // Whitelisted address mapping (address => bool) public whitelists; // Whitelist deposited balance mapping (address => uint256) public whitelistBalance; // End period for whitelist advantage uint256 public whitelistEndTimestamp = 0; // Max stake for whitelist uint256 public constant whitelist_stake_limit67 = 3 ether; //inject NONSTANDARD NAMING // Whitelist advantage duration (reduced to 1 minutes since we dont have whitelist) uint256 public constant whitelist_duration869 = 1 minutes; //inject NONSTANDARD NAMING constructor(address _routerAddress, address[] memory _whitelists) public { token = new twis(address(this)); router = IUniswapV2Router02(_routerAddress); factory = IUniswapV2Factory(router.FACTORY423()); weth = router.WETH656(); treasury = msg.sender; pairAddress = factory.CREATEPAIR119(address(token), weth); // Calc reward rate rewardRate = rewardAllocation.DIV283(halving_duration255); // Init whitelist _SETUPWHITELISTS161(_whitelists); whitelistEndTimestamp = farmingStartTimestamp.ADD393(whitelist_duration869); } receive() external payable { emit RECEIVED501(msg.sender, msg.value); } function STAKE961() external payable NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); require(msg.value > 0, 'Cannot stake 0'); require(!address(msg.sender).ISCONTRACT204(), 'Please use your individual account'); // If we are still in whitelist duration if (whitelistEndTimestamp >= block.timestamp) { require(whitelists[msg.sender], 'Only whitelisted address can stake right now'); whitelistBalance[msg.sender] = whitelistBalance[msg.sender].ADD393(msg.value); require(whitelistBalance[msg.sender] <= whitelist_stake_limit67, 'Cannot stake more than allowed in whitelist period'); } // 10% compensation fee // since dev doesn't hold any initial supply uint256 fee = msg.value.DIV283(10); uint256 amount = msg.value.SUB829(fee); treasury.transfer(fee); uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress); uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress); // If eth amount = 0 then set initial price to 1 eth = 2 twis uint256 amountTokenDesired = ethAmount == 0 ? (amount * 2) : amount.MUL131(tokenAmount).DIV283(ethAmount); // Mint borrowed twis token.MINT750(address(this), amountTokenDesired); // Add liquidity in uniswap uint256 amountETHDesired = amount; IERC20(token).APPROVE213(address(router), amountTokenDesired); (,, uint256 liquidity) = router.ADDLIQUIDITYETH439{value : amountETHDesired}(address(token), amountTokenDesired, 1, 1, address(this), block.timestamp + 1 days); // Add LP token to total supply _totalSupply = _totalSupply.ADD393(liquidity); // Add to balance accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.ADD393(liquidity); // Set peak balance if (accountInfos[msg.sender].balance > accountInfos[msg.sender].peakBalance) { accountInfos[msg.sender].peakBalance = accountInfos[msg.sender].balance; } // Set stake timestamp as withdraw timestamp // to prevent withdraw immediately after first staking if (accountInfos[msg.sender].withdrawTimestamp == 0) { accountInfos[msg.sender].withdrawTimestamp = block.timestamp; } emit STAKED534(msg.sender, msg.value, liquidity); } function WITHDRAW91() external NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); require(accountInfos[msg.sender].withdrawTimestamp + 1 days <= block.timestamp, 'You must wait 1 day since your last withdraw or stake'); require(accountInfos[msg.sender].balance > 0, 'Cannot withdraw 0'); // Limit withdraw LP token uint256 amount = accountInfos[msg.sender].peakBalance.DIV283(withdraw_limit638); if (accountInfos[msg.sender].balance < amount) { amount = accountInfos[msg.sender].balance; } // Reduce total supply _totalSupply = _totalSupply.SUB829(amount); // Reduce balance accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.SUB829(amount); // Set timestamp accountInfos[msg.sender].withdrawTimestamp = block.timestamp; // Remove liquidity in uniswap IERC20(pairAddress).APPROVE213(address(router), amount); (uint256 tokenAmount, uint256 ethAmount) = router.REMOVELIQUIDITY294(address(token), weth, amount, 0, 0, address(this), block.timestamp + 1 days); // Burn borrowed twis token.BURN945(address(this), tokenAmount); // Withdraw ETH and send to sender IWETH(weth).WITHDRAW91(ethAmount); msg.sender.transfer(ethAmount); emit WITHDRAWN851(msg.sender, ethAmount, amount); } function CLAIM763() external NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); uint256 reward = accountInfos[msg.sender].reward; require(reward > 0, 'There is no reward to claim'); if (reward > 0) { // Reduce first accountInfos[msg.sender].reward = 0; // Apply tax uint256 taxDenominator = CLAIMTAXDENOMINATOR467(); uint256 tax = taxDenominator > 0 ? reward.DIV283(taxDenominator) : 0; uint256 net = reward.SUB829(tax); // Send reward token.MINT750(msg.sender, net); if (tax > 0) { // Burn taxed token token.MINT750(burn_address389, tax); } emit CLAIMED515(msg.sender, reward); } } function TOTALSUPPLY622() external view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF753(address account) external view returns (uint256) { //inject NONSTANDARD NAMING return accountInfos[account].balance; } function BURNEDTOKENAMOUNT890() public view returns (uint256) { //inject NONSTANDARD NAMING return token.BALANCEOF753(burn_address389); } function REWARDPERTOKEN638() public view returns (uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored .ADD393( LASTREWARDTIMESTAMP705() .SUB829(lastUpdateTimestamp) .MUL131(rewardRate) .MUL131(1e18) .DIV283(_totalSupply) ); } function LASTREWARDTIMESTAMP705() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN629(block.timestamp, halvingTimestamp); } function REWARDEARNED380(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return accountInfos[account].balance.MUL131( REWARDPERTOKEN638().SUB829(accountInfos[account].rewardPerTokenPaid) ) .DIV283(1e18) .ADD393(accountInfos[account].reward); } // Token price in eth function TOKENPRICE205() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress); uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress); return tokenAmount > 0 ? // Current price ethAmount.MUL131(1e18).DIV283(tokenAmount) : // Initial price (uint256(1e18).DIV283(2)); } function CLAIMTAXDENOMINATOR467() public view returns (uint256) { //inject NONSTANDARD NAMING if (block.timestamp < farmingStartTimestamp + 1 days) { return 4; } else if (block.timestamp < farmingStartTimestamp + 2 days) { return 5; } else if (block.timestamp < farmingStartTimestamp + 3 days) { return 10; } else if (block.timestamp < farmingStartTimestamp + 4 days) { return 20; } else { return 0; } } function _UPDATEREWARD485(address account) internal { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN638(); lastUpdateTimestamp = LASTREWARDTIMESTAMP705(); if (account != address(0)) { accountInfos[account].reward = REWARDEARNED380(account); accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored; } } // Do halving when timestamp reached function _HALVING349() internal { //inject NONSTANDARD NAMING if (block.timestamp >= halvingTimestamp) { rewardAllocation = rewardAllocation.DIV283(2); rewardRate = rewardAllocation.DIV283(halving_duration255); halvingTimestamp = halvingTimestamp.ADD393(halving_duration255); _UPDATEREWARD485(msg.sender); emit HALVING833(rewardAllocation); } } // Check if farming is started function _CHECKFARMING62() internal { //inject NONSTANDARD NAMING require(farmingStartTimestamp <= block.timestamp, 'Please wait until farming started'); if (!farmingStarted) { farmingStarted = true; halvingTimestamp = block.timestamp.ADD393(halving_duration255); lastUpdateTimestamp = block.timestamp; } } function _SETUPWHITELISTS161(address[] memory addresses) internal { //inject NONSTANDARD NAMING for (uint256 i = 0; i < addresses.length; i++) { whitelists[addresses[i]] = true; } } }
inject NONSTANDARD NAMING
function APPROVE213(address guy, uint wad) public returns (bool) {
12,607,487
pragma solidity ^0.4.23; import "./Ownable.sol"; import "./SafeMath.sol"; import "./DaiInterface.sol"; import "./oraclizeAPI_0_5.sol"; contract Adversary is DaiTransferrer, usingOraclize { using SafeMath for uint256; event NewOffer(); event OfferDeleted(); event NewEscrow(); event TradeCompleted(); event LogNewOraclizeQuery(string description); struct Offer { address maker; bool makerIsLong; string currency; uint dai; uint listIndex; uint margin; uint PositiveDelta; // nano units uint NegativeDelta; // nano units uint lockSeconds; } struct PendingTake { address taker; uint64 offerId; } struct PendingClaim { address claimer; uint64 escrowId; } struct Escrow { address maker; address taker; bool makerIsLong; string currency; uint dai; uint listIndex; uint StartPrice; // nano units uint margin; uint CeilingPrice; // nano units uint FloorPrice; // nano units uint unlockSecond; } bool private contractEnabled = true; uint private timeDisabled = 0xFFFFFFFFFF; uint constant public MINIMUM_DAI = 10 * 10 ** 18; // 10 Dai uint constant public CREATE_ESCROW_GAS_LIMIT = 400000; // TODO set once code is finalised uint constant public CLAIM_ESCROW_GAS_LIMIT = 400000; // TODO calculate in testing // result of web3.sha3(\x19Ethereum Signed Message:\n22sign to destroy escrow); see test to reproduce. bytes32 constant public RESCUE_MSG_HASH = 0x0b5aeebdde1c7d6f965711096ca4f564aba1fea366fa994cf30a2bde9958891c; uint public oracleGasPrice = 20000000000; uint64[] public offerIds; uint64[] public escrowIds; uint64 public currentId = 1; mapping(uint64 => Offer) public offers; mapping(uint64 => Escrow) public escrows; mapping(bytes32 => PendingTake) public pendingTakes; mapping(bytes32 => PendingClaim) public pendingClaims; function() public payable {} /* @param long, If true the offer maker is long and profits when the result increases and vice versa. @param currency, String to specify the symbol used in bitfinex api, eg "ETHUSD". @param dai, Quantity of dai the maker and taker will contribute to the escrow. @param margin, Integer which multiplies rate rewards change with price, use zero for step function rewards. @param positiveDelta If margin is zero then the required increase from start price before long can claim entire escrow. Nano units. @param negativeDelta If margin is zero then the required decrease from start price before short can claim entire escrow. Nano units. @param lockSeconds Time after escrow starts before either party can claim escrow. */ function createOffer( bool long, string currency, uint dai, uint margin, uint positiveDelta, uint negativeDelta, uint lockSeconds ) external { require(dai >= MINIMUM_DAI && contractEnabled); transferDai(msg.sender, address(this), dai); offers[currentId] = Offer( msg.sender, long, currency, dai, offerIds.push(currentId) - 1, margin, positiveDelta, negativeDelta, lockSeconds ); currentId++; emit NewOffer(); } function deleteOffer(uint64 offerId) external { require(msg.sender == offers[offerId].maker); transferDai(address(this), msg.sender, offers[offerId].dai); _deleteOffer(offerId); } function createEscrow(uint64 offerId) external payable { setOracleResponseGasPrice(tx.gasprice); require(msg.value >= getEthRequiredForEscrow() && contractEnabled); if (oraclize_getPrice("URL") > address(this).balance) { emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); bytes32 queryId = oraclize_query("URL", strConcat("json(https://api.bitfinex.com/v2/ticker/t", offers[offerId].currency, ").[6]"), CREATE_ESCROW_GAS_LIMIT); pendingTakes[queryId] = PendingTake(msg.sender, offerId); } } function claimEscrow(uint64 escrowId) external payable { setOracleResponseGasPrice(tx.gasprice); require(msg.value >= getEthRequiredForClaim()); if (oraclize_getPrice("URL") > address(this).balance) { emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); bytes32 queryId = oraclize_query("URL", strConcat("json(https://api.bitfinex.com/v2/ticker/t", escrows[escrowId].currency, ").[6]"), CLAIM_ESCROW_GAS_LIMIT); pendingClaims[queryId] = PendingClaim(msg.sender, escrowId); } } /* If an escrow gets stuck and both the maker and taker sign the key the escrow can be distributed equally */ function rescueStuckEscrow( uint64 escrowId, uint8 makerV, bytes32 makerR, bytes32 makerS, uint8 takerV, bytes32 takerR, bytes32 takerS ) external { Escrow memory escrow = escrows[escrowId]; require(ecrecover(RESCUE_MSG_HASH, makerV, makerR, makerS) == escrow.maker); require(ecrecover(RESCUE_MSG_HASH, takerV, takerR, takerS) == escrow.taker); uint payoutForMaker = escrow.dai / 2; uint payoutForTaker = escrow.dai - payoutForMaker; transferDai(address(this), escrow.maker, payoutForMaker); transferDai(address(this), escrow.taker, payoutForTaker); _deleteEscrow(escrowId); emit TradeCompleted(); } function withdrawEth() external onlyOwner { msg.sender.transfer(address(this).balance); } function withdrawDai() external onlyOwner { uint daiInUse = 0; for (uint i = 0; i < offerIds.length; i++) { daiInUse += offers[offerIds[i]].dai; } for (i = 0; i < escrowIds.length; i++) { daiInUse += escrows[escrowIds[i]].dai; } transferDai(address(this), msg.sender, getDaiBalance(address(this)) - daiInUse); } /*This will prevent creating offers and escrows but existing ones will still function*/ function disableContract() external onlyOwner { contractEnabled = false; timeDisabled = now; } function finalise() external onlyOwner { require(now > timeDisabled + 365 days); transferDai(address(this), msg.sender, getDaiBalance(address(this))); selfdestruct(owner); } function getNumOffers() external view returns (uint length) { return offerIds.length; } function getNumEscrows() external view returns (uint length) { return escrowIds.length; } function __callback(bytes32 myid, string result) public { require(msg.sender == oraclize_cbAddress()); if (pendingTakes[myid].offerId != 0) { completeEscrowCreation(pendingTakes[myid], result); } else { if (pendingClaims[myid].escrowId != 0) { completeEscrowClaim(pendingClaims[myid], result); } } } function getEthRequiredForEscrow() public view returns (uint ethAmount) { return CREATE_ESCROW_GAS_LIMIT.mul(oracleGasPrice) + 1 ether / 1000; // TODO calculate properly when finalised } function getEthRequiredForClaim() public view returns (uint ethAmount) { return CLAIM_ESCROW_GAS_LIMIT.mul(oracleGasPrice) + 1 ether / 10000; // TODO calculate properly when finalised } function calculateReturns( uint margin, uint CeilingPrice, uint FloorPrice, uint daiInEscrow, uint StartPrice, bool makerIsLong, string priceResult ) public pure returns (uint payoutForMaker, uint payoutForTaker) { uint payoutForLong = 0; uint payoutForShort = 0; uint FinalPrice = parseInt(priceResult, 9); if (margin == 0) { require(FinalPrice >= CeilingPrice || FinalPrice <= FloorPrice); if (FinalPrice >= CeilingPrice) { payoutForLong = daiInEscrow; } else { payoutForShort = daiInEscrow; } } else { int marginDelta = int(margin) * int(FinalPrice - StartPrice); int marginDeltaPlusStart = marginDelta + int(StartPrice); if (marginDelta > int(StartPrice)) { payoutForLong = daiInEscrow; } else if (marginDeltaPlusStart < 0) { payoutForLong = 0; } else { payoutForLong = (daiInEscrow * (uint(marginDeltaPlusStart))) / (2 * StartPrice); } payoutForShort = daiInEscrow - payoutForLong; } if (makerIsLong) { return (payoutForLong, payoutForShort); } else { return (payoutForShort, payoutForLong); } } function setOracleResponseGasPrice(uint priceInWei) internal { oraclize_setCustomGasPrice(priceInWei); oracleGasPrice = priceInWei; } function _deleteOffer(uint64 offerId) internal { uint listIndex = offers[offerId].listIndex; offerIds[listIndex] = offerIds[offerIds.length - 1]; offers[offerIds[listIndex]].listIndex = listIndex; delete offers[offerId]; offerIds.length --; emit OfferDeleted(); } function _deleteEscrow(uint64 escrowId) internal { uint listIndex = escrows[escrowId].listIndex; escrowIds[listIndex] = escrowIds[escrowIds.length - 1]; escrows[escrowIds[listIndex]].listIndex = listIndex; delete escrows[escrowId]; escrowIds.length --; } function completeEscrowCreation(PendingTake take, string priceResult) internal { Offer memory offer = offers[take.offerId]; require(offer.dai > 0); // to check it is a real initialised offer transferDai(take.taker, address(this), offer.dai); uint StartPrice = parseInt(priceResult, 9); escrows[currentId] = Escrow( offer.maker, take.taker, offer.makerIsLong, offer.currency, offer.dai.mul(995).div(500), escrowIds.push(currentId) - 1, StartPrice, offer.margin, StartPrice + offer.PositiveDelta, StartPrice - offer.NegativeDelta, offer.lockSeconds + now ); _deleteOffer(take.offerId); emit NewEscrow(); currentId++; } function completeEscrowClaim(PendingClaim pendingClaim, string priceResult) internal { Escrow memory escrow = escrows[pendingClaim.escrowId]; require(pendingClaim.claimer == escrow.maker || pendingClaim.claimer == escrow.taker); require(now > escrow.unlockSecond); uint payoutForMaker = 0; uint payoutForTaker = 0; (payoutForMaker, payoutForTaker) = calculateReturns( escrow.margin, escrow.CeilingPrice, escrow.FloorPrice, escrow.dai, escrow.StartPrice, escrow.makerIsLong, priceResult ); transferDai(address(this), escrow.maker, payoutForMaker); transferDai(address(this), escrow.taker, payoutForTaker); _deleteEscrow(pendingClaim.escrowId); emit TradeCompleted(); } } /* TODO: fix calculation of oraclize fee. optimise for gas,check how much smaller struct members can be and place adjacent. At least uint64 for prices. handle overflows etc */
If an escrow gets stuck and both the maker and taker sign the key the escrow can be distributed equally/
function rescueStuckEscrow( uint64 escrowId, uint8 makerV, bytes32 makerR, bytes32 makerS, uint8 takerV, bytes32 takerR, bytes32 takerS ) external { Escrow memory escrow = escrows[escrowId]; require(ecrecover(RESCUE_MSG_HASH, makerV, makerR, makerS) == escrow.maker); require(ecrecover(RESCUE_MSG_HASH, takerV, takerR, takerS) == escrow.taker); uint payoutForMaker = escrow.dai / 2; uint payoutForTaker = escrow.dai - payoutForMaker; transferDai(address(this), escrow.maker, payoutForMaker); transferDai(address(this), escrow.taker, payoutForTaker); _deleteEscrow(escrowId); emit TradeCompleted(); }
2,488,585
./full_match/4/0x9D8166409294a72495aAC157D457051E8Ca7C3aB/sources/LotteryBNB.sol
Hàm quay số : quay ra kết qua của 1 round .
function dial() public { uint hoahongadmin = TotalBNB * 2 / 10 ; payable(owner).transfer(hoahongadmin) ; TotalBNB = TotalBNB - hoahongadmin ; for(uint i = 0 ; i < rounds.length; i++){ require(rounds[i].id != RoundId , "Chi qua so 1 lan moi round"); } uint [3] memory numbers ; uint indexN1 = getRamdomArray(RoundId); numbers[0] = numberArray[indexN1]; removeArray(indexN1) ; uint indexN2= getRamdomArray(RoundId); numbers[1] = numberArray[indexN2] ; removeArray(indexN2) ; uint indexN3= getRamdomArray(RoundId); numbers[2] = numberArray[indexN3] ; numberArray = [0,1,2,3,4,5,6,7,8,9]; Round memory round = Round(RoundId,numbers,TotalBNB) ; rounds.push(round); _pickWinner(); }
690,748
./full_match/1/0xe28f876B8ae08Ce4FC65201fF29C5a132Bd1A961/sources/contracts/pimpills.sol
Converts a `uint256` to its ASCII `string` decimal representation./ Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); }
2,978,661
./partial_match/1/0xa0c695033350c17F98405dC10604301BC0e18c10/sources/NFTs_Latam_DubbelNFT.sol
External interface of AccessControl declared to support ERC165 detection./
interface IAccessControlUpgradeable { event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; }
16,118,103
./full_match/80001/0x990D76F1190D5098928cd2cAcCe0a2C9293EfBa8/sources/contracts/v1/SynsMarketplace.sol
Returns an array of `Listings` that are owned by a specific listing's creator
function getListingsOwnedBy(address _listingCreator) public view returns (Listing[] memory) { uint256 totalAmountListedByOwner = getTotalAmountListingBy(_listingCreator); uint256 currentIndex; Listing[] memory listings = new Listing[](totalAmountListedByOwner); for (uint256 i = 0; i < totalListings; i++) { if (totalListingItems[i].tokenOwner == _listingCreator) { Listing memory listing = totalListingItems[i]; listings[currentIndex] = listing; currentIndex++; } } return listings; }
845,928
./full_match/69/0xa46d600e30D9C718F44F675d85f550eb843601e9/sources/contracts/rubiconPools/BathToken.sol
No rebalance implementation for lower fees and faster swaps
function withdraw(uint256 _shares) external { uint256 r = (underlyingBalance().mul(_shares)).div(totalSupply); _burn(msg.sender, _shares); uint256 _fee = r.mul(feeBPS).div(feeDenominator); IERC20(underlyingToken).transfer(feeTo, _fee); underlyingToken.transfer(msg.sender, r.sub(_fee)); }
13,239,101
./partial_match/1/0x9Bb0Fc6C1E2ADFaC756a8c9a9A89BB3489B1bd30/sources/AlphaMaster.sol
View function to see pending APOOL on frontend..mul(alphapoolsPerBlock).wdiv(1e18);.mul(1e6)
function pendingAlphaPools(uint _pid, address _user) external view returns (uint) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint accAlphaPoolsPerShare = pool.accAlphaPoolsPerShare; uint lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint alphapoolsReward = multiplier .wmul(pool.allocPoint) .wdiv(totalAllocPoint); accAlphaPoolsPerShare = accAlphaPoolsPerShare.add( alphapoolsReward .wdiv(lpSupply) ); } return user.amount.wmul(accAlphaPoolsPerShare) }
9,359,278
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract AniCatsMintpass is ERC1155, Ownable { uint constant public TICKET_ID = 0; uint constant public MAX_SUPPLY = 900; uint constant public TEAM_RESERVE = 50; struct MintpassPlan { uint price; uint amount; } bool public mintpassEnabled; bool public transferLocked; uint public ticketsMinted; mapping(address => bool) public isOperatorApproved; mapping(uint => MintpassPlan) public minpassPlans; constructor() ERC1155("https://anicats-mintpass.herokuapp.com/meta/{id}") { minpassPlans[1] = MintpassPlan(0.06 ether, 1); // 0.06 per one ticket minpassPlans[2] = MintpassPlan(0.165 ether, 3); // 0.055 per one ticket minpassPlans[3] = MintpassPlan(0.25 ether, 5); // 0.05 per one ticket } // Admin methods region function setURI(string memory uri) external onlyOwner { _setURI(uri); } function approveOperator(address operator, bool approved) external onlyOwner { isOperatorApproved[operator] = approved; } function setTransferLocked(bool locked) external onlyOwner { transferLocked = locked; } function setMintpassSaleState(bool state) external onlyOwner { mintpassEnabled = state; } function withdraw(address to) external onlyOwner { uint balance = address(this).balance; payable(to).transfer(balance); } function giveAway(address to, uint amount) public onlyOwner { _mint(to, TICKET_ID, amount, ""); } // endregion // Mint methods modifier mintpassGuard(uint planId) { require(mintpassEnabled, "Minting is not available"); require(ticketsMinted + minpassPlans[planId].amount <= MAX_SUPPLY - TEAM_RESERVE, "Mintpass tickets supply reached limit"); require(minpassPlans[planId].amount != 0, "No such Mintpass plan"); _; } function buyMintpass(uint planId) external payable mintpassGuard(planId) { require(minpassPlans[planId].price == msg.value, "Incorrect ethers value"); ticketsMinted += minpassPlans[planId].amount; _mint(msg.sender, TICKET_ID, minpassPlans[planId].amount, ""); } // endregion function mintpassPlanPrice(uint planId) external view returns (uint) { return minpassPlans[planId].price; } // 1151 interface region function isApprovedForAll(address account, address operator) public view override returns (bool) { return isOperatorApproved[operator] || super.isApprovedForAll(account, operator); } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public override { require(!transferLocked, "Transfer is locked"); super._safeTransferFrom(from, to, id, amount, data); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(!transferLocked, "Transfer is locked"); super._safeBatchTransferFrom(from, to, ids, amounts, data); } // endregion } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
1151 interface region
function isApprovedForAll(address account, address operator) public view override returns (bool) { return isOperatorApproved[operator] || super.isApprovedForAll(account, operator); }
13,875,106
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPosition Contract /// @author Enzyme Council <[email protected]> interface IExternalPosition { function getDebtAssets() external returns (address[] memory, uint256[] memory); function getManagedAssets() external returns (address[] memory, uint256[] memory); function init(bytes memory) external; function receiveCallFromVault(bytes memory) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title 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; /// @title IExternalPositionParser Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all external position parsers interface IExternalPositionParser { function parseAssetsForAction( address _externalPosition, uint256 _actionId, bytes memory _encodedActionArgs ) external returns ( address[] memory assetsToTransfer_, uint256[] memory amountsToTransfer_, address[] memory assetsToReceive_ ); function parseInitArgs(address _vaultProxy, bytes memory _initializationData) external returns (bytes memory initArgs_); } // 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 AaveDebtPositionDataDecoder Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract containing data decodings for AaveDebtPosition payloads abstract contract AaveDebtPositionDataDecoder { /// @dev Helper to decode args used during the AddCollateral action function __decodeAddCollateralActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory aTokens_, uint256[] memory amounts_) { return abi.decode(_actionArgs, (address[], uint256[])); } /// @dev Helper to decode args used during the Borrow action function __decodeBorrowActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory tokens_, uint256[] memory amounts_) { return abi.decode(_actionArgs, (address[], uint256[])); } /// @dev Helper to decode args used during the ClaimRewards action function __decodeClaimRewardsActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory assets_) { return abi.decode(_actionArgs, (address[])); } /// @dev Helper to decode args used during the RemoveCollateral action function __decodeRemoveCollateralActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory aTokens_, uint256[] memory amounts_) { return abi.decode(_actionArgs, (address[], uint256[])); } /// @dev Helper to decode args used during the RepayBorrow action function __decodeRepayBorrowActionArgs(bytes memory _actionArgs) internal pure returns (address[] memory tokens_, uint256[] memory amounts_) { return abi.decode(_actionArgs, (address[], uint256[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "../IExternalPositionParser.sol"; import "./AaveDebtPositionDataDecoder.sol"; import "./IAaveDebtPosition.sol"; pragma solidity 0.6.12; /// @title AaveDebtPositionParser /// @author Enzyme Council <[email protected]> /// @notice Parser for Aave Debt Positions contract AaveDebtPositionParser is IExternalPositionParser, AaveDebtPositionDataDecoder { address private immutable VALUE_INTERPRETER; constructor(address _valueInterpreter) public { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Parses the assets to send and receive for the callOnExternalPosition /// @param _externalPosition The _externalPosition to be called /// @param _actionId The _actionId for the callOnExternalPosition /// @param _encodedActionArgs The encoded parameters for the callOnExternalPosition /// @return assetsToTransfer_ The assets to be transferred from the Vault /// @return amountsToTransfer_ The amounts to be transferred from the Vault /// @return assetsToReceive_ The assets to be received at the Vault function parseAssetsForAction( address _externalPosition, uint256 _actionId, bytes memory _encodedActionArgs ) external override returns ( address[] memory assetsToTransfer_, uint256[] memory amountsToTransfer_, address[] memory assetsToReceive_ ) { if (_actionId == uint256(IAaveDebtPosition.Actions.AddCollateral)) { // No need to validate aTokens, as the worst case would be that this function is used // to indirectly add and track a misc supported asset (assetsToTransfer_, amountsToTransfer_) = __decodeAddCollateralActionArgs( _encodedActionArgs ); __validateSupportedAssets(assetsToTransfer_); } else if (_actionId == uint256(IAaveDebtPosition.Actions.Borrow)) { // No need to validate tokens, as `borrow()` call to Aave will fail for invalid tokens, // and even if Aave logic changes to fail silently, the worst case would be that // this function is used to indirectly add and track a misc supported asset (assetsToReceive_, ) = __decodeBorrowActionArgs(_encodedActionArgs); __validateSupportedAssets(assetsToReceive_); } else if (_actionId == uint256(IAaveDebtPosition.Actions.RemoveCollateral)) { // Lib validates that each is a valid collateral asset (assetsToReceive_, ) = __decodeRemoveCollateralActionArgs(_encodedActionArgs); } else if (_actionId == uint256(IAaveDebtPosition.Actions.RepayBorrow)) { // Lib validates that each is a valid borrowed asset (assetsToTransfer_, amountsToTransfer_) = __decodeRepayBorrowActionArgs( _encodedActionArgs ); for (uint256 i; i < assetsToTransfer_.length; i++) { if (amountsToTransfer_[i] == type(uint256).max) { // Transfers the full repay amount to the external position, // which will still call `repay()` on the lending pool with max uint. // This is fine, because `repay()` only uses up to the full repay amount. address debtToken = IAaveDebtPosition(_externalPosition) .getDebtTokenForBorrowedAsset(assetsToTransfer_[i]); amountsToTransfer_[i] = ERC20(debtToken).balanceOf(_externalPosition); } } } // No validations or transferred assets passed for Actions.ClaimRewards return (assetsToTransfer_, amountsToTransfer_, assetsToReceive_); } /// @notice Parse and validate input arguments to be used when initializing a newly-deployed ExternalPositionProxy /// @dev Empty for this external position type function parseInitArgs(address, bytes memory) external override returns (bytes memory) {} /// @dev Helper to validate that assets are supported within the protocol function __validateSupportedAssets(address[] memory _assets) private view { for (uint256 i; i < _assets.length; i++) { require( IValueInterpreter(VALUE_INTERPRETER).isSupportedAsset(_assets[i]), "__validateSupportedAssets: Unsupported asset" ); } } } // 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 "../../../../../persistent/external-positions/IExternalPosition.sol"; pragma solidity 0.6.12; /// @title IAaveDebtPosition Interface /// @author Enzyme Council <[email protected]> interface IAaveDebtPosition is IExternalPosition { enum Actions {AddCollateral, RemoveCollateral, Borrow, RepayBorrow, ClaimRewards} function getDebtTokenForBorrowedAsset(address) 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; import "./IDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeedMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed abstract contract AggregatedDerivativePriceFeedMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToPriceFeed; /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function __calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) internal returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = getPriceFeedForDerivative(_derivative); require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) internal { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( getPriceFeedForDerivative(_derivatives[i]) == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function __removeDerivatives(address[] memory _derivatives) internal { for (uint256 i = 0; i < _derivatives.length; i++) { require( getPriceFeedForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) public view returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } } // 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 IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; /// @title ChainlinkPriceFeedMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources abstract contract ChainlinkPriceFeedMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; uint256 private immutable STALE_RATE_THRESHOLD; address private immutable WETH_TOKEN; address private ethUsdAggregator; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor(address _wethToken, uint256 _staleRateThreshold) public { STALE_RATE_THRESHOLD = _staleRateThreshold; WETH_TOKEN = _wethToken; } // INTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount function __calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) internal view returns (uint256 quoteAssetAmount_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); require(baseAssetRate > 0, "__calcCanonicalValue: Invalid base asset rate"); int256 quoteAssetRate = __getLatestRateData(_quoteAsset); require(quoteAssetRate > 0, "__calcCanonicalValue: Invalid quote asset rate"); return __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) internal { address prevEthUsdAggregator = getEthUsdAggregator(); require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ); } (, int256 ethPerUsdRate, , uint256 ethPerUsdRateLastUpdatedAt, ) = IChainlinkAggregator( getEthUsdAggregator() ) .latestRoundData(); require(ethPerUsdRate > 0, "__calcConversionAmount: Bad ethUsd rate"); __validateRateIsNotStale(ethPerUsdRateLastUpdatedAt); // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == getWethToken()) { return int256(ETH_UNIT); } address aggregator = getAggregatorForPrimitive(_primitive); require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); uint256 rateUpdatedAt; (, rate_, , rateUpdatedAt, ) = IChainlinkAggregator(aggregator).latestRoundData(); __validateRateIsNotStale(rateUpdatedAt); return rate_; } /// @dev Helper to validate that a rate is not from a round considered to be stale function __validateRateIsNotStale(uint256 _latestUpdatedAt) private view { require( _latestUpdatedAt >= block.timestamp.sub(getStaleRateThreshold()), "__validateRateIsNotStale: Stale rate detected" ); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function __addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) internal { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i; i < _primitives.length; i++) { require( getAggregatorForPrimitive(_primitives[i]) == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function __removePrimitives(address[] calldata _primitives) internal { for (uint256 i; i < _primitives.length; i++) { require( getAggregatorForPrimitive(_primitives[i]) != address(0), "__removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { (, int256 answer, , uint256 updatedAt, ) = IChainlinkAggregator(_aggregator) .latestRoundData(); require(answer > 0, "__validateAggregator: No rate detected"); __validateRateIsNotStale(updatedAt); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregator for a primitive /// @param _primitive The primitive asset for which to get the aggregator value /// @return aggregator_ The aggregator address function getAggregatorForPrimitive(address _primitive) public view returns (address aggregator_) { return primitiveToAggregatorInfo[_primitive].aggregator; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() public view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == getWethToken()) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the `STALE_RATE_THRESHOLD` variable value /// @return staleRateThreshold_ The `STALE_RATE_THRESHOLD` value function getStaleRateThreshold() public view returns (uint256 staleRateThreshold_) { return STALE_RATE_THRESHOLD; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == getWethToken()) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256); function isSupportedAsset(address) external view returns (bool); function isSupportedDerivativeAsset(address) external view returns (bool); function isSupportedPrimitiveAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../utils/FundDeployerOwnerMixin.sol"; import "../../utils/MathHelpers.sol"; import "../price-feeds/derivatives/AggregatedDerivativePriceFeedMixin.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/ChainlinkPriceFeedMixin.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs contract ValueInterpreter is IValueInterpreter, FundDeployerOwnerMixin, AggregatedDerivativePriceFeedMixin, ChainlinkPriceFeedMixin, MathHelpers { using SafeMath for uint256; // Used to only tolerate a max rounding discrepancy of 0.01% // when converting values via an inverse rate uint256 private constant MIN_INVERSE_RATE_AMOUNT = 10000; constructor( address _fundDeployer, address _wethToken, uint256 _chainlinkStaleRateThreshold ) public FundDeployerOwnerMixin(_fundDeployer) ChainlinkPriceFeedMixin(_wethToken, _chainlinkStaleRateThreshold) {} // EXTERNAL FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state. /// Does not handle a derivative quote asset. function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) external override returns (uint256 value_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( isSupportedPrimitiveAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); for (uint256 i; i < _baseAssets.length; i++) { uint256 assetValue = __calcAssetValue(_baseAssets[i], _amounts[i], _quoteAsset); value_ = value_.add(assetValue); } return value_; } // PUBLIC FUNCTIONS /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state. /// See also __calcPrimitiveToDerivativeValue() for important notes regarding a derivative _quoteAsset. function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_) { if (_baseAsset == _quoteAsset || _amount == 0) { return _amount; } if (isSupportedPrimitiveAsset(_quoteAsset)) { return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } else if ( isSupportedDerivativeAsset(_quoteAsset) && isSupportedPrimitiveAsset(_baseAsset) ) { return __calcPrimitiveToDerivativeValue(_baseAsset, _amount, _quoteAsset); } revert("calcCanonicalAssetValue: Unsupported conversion"); } /// @notice Checks whether an asset is a supported asset /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported asset function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return isSupportedPrimitiveAsset(_asset) || isSupportedDerivativeAsset(_asset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_) { if (_baseAsset == _quoteAsset || _amount == 0) { return _amount; } // Handle case that asset is a primitive if (isSupportedPrimitiveAsset(_baseAsset)) { return __calcCanonicalValue(_baseAsset, _amount, _quoteAsset); } // Handle case that asset is a derivative address derivativePriceFeed = getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); for (uint256 i = 0; i < underlyings.length; i++) { uint256 underlyingValue = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); value_ = value_.add(underlyingValue); } } /// @dev Helper to calculate the value of a primitive base asset in a derivative quote asset. /// Assumes that the _primitiveBaseAsset and _derivativeQuoteAsset have been validated as supported. /// Callers of this function should be aware of the following points, and take precautions as-needed, /// such as prohibiting a derivative quote asset: /// - The returned value will be slightly less the actual canonical value due to the conversion formula's /// handling of the intermediate inverse rate (see comments below). /// - If the assets involved have an extreme rate and/or have a low ERC20.decimals() value, /// the inverse rate might not be considered "sufficient", and will revert. function __calcPrimitiveToDerivativeValue( address _primitiveBaseAsset, uint256 _primitiveBaseAssetAmount, address _derivativeQuoteAsset ) private returns (uint256 value_) { uint256 derivativeUnit = 10**uint256(ERC20(_derivativeQuoteAsset).decimals()); address derivativePriceFeed = getPriceFeedForDerivative(_derivativeQuoteAsset); uint256 primitiveAmountForDerivativeUnit = __calcDerivativeValue( derivativePriceFeed, _derivativeQuoteAsset, derivativeUnit, _primitiveBaseAsset ); // Only tolerate a max rounding discrepancy require( primitiveAmountForDerivativeUnit > MIN_INVERSE_RATE_AMOUNT, "__calcPrimitiveToDerivativeValue: Insufficient rate" ); // Adds `1` to primitiveAmountForDerivativeUnit so that the final return value is // slightly less than the actual value, which is congruent with how all other // asset conversions are floored in the protocol. return __calcRelativeQuantity( primitiveAmountForDerivativeUnit.add(1), derivativeUnit, _primitiveBaseAssetAmount ); } //////////////////////////// // PRIMITIVES (CHAINLINK) // //////////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyFundDeployerOwner { __removePrimitives(_primitives); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyFundDeployerOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } /// @notice Updates a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function updatePrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __removePrimitives(_primitives); __addPrimitives(_primitives, _aggregators, _rateAssets); } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is a supported primitive /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedPrimitiveAsset(address _asset) public view override returns (bool isSupported_) { return _asset == getWethToken() || getAggregatorForPrimitive(_asset) != address(0); } //////////////////////////////////// // DERIVATIVE PRICE FEED REGISTRY // //////////////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner { __removeDerivatives(_derivatives); } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __removeDerivatives(_derivatives); __addDerivatives(_derivatives, _priceFeeds); } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative function isSupportedDerivativeAsset(address _asset) public view override returns (bool isSupported_) { return getPriceFeedForDerivative(_asset) != address(0); } } // 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 IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestRoundData() external view returns ( uint80, int256, uint256, uint256, uint80 ); } // 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; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio. /// Caller is responsible as-necessary for: /// 1. validating _quantity1 to be non-zero /// 2. validating relativeQuantity2_ to be non-zero function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } }
Adds a list of primitives with the given aggregator and rateAsset values _primitives The primitives to add _aggregators The ordered aggregators corresponding to the list of _primitives _rateAssets The ordered rate assets corresponding to the list of _primitives
function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __addPrimitives(_primitives, _aggregators, _rateAssets); }
1,406,594
./full_match/4/0x345316ED393a2D71c7bf1A4dB725c18dA383E6F2/sources/ThePixelPortraits.sol
first we deal with the status, payments, and name resrvation Thom has decided to reject your commission or it is made for a taken name this means that the name about to be accepted isn't taken yet and will be accepted
function processCommissions(uint[] memory _commissionIndexes, bool[] memory _rejections) public onlyAdmin { require(_commissionIndexes.length == _rejections.length, "arrays not the same length"); for (uint i = 0; i < _commissionIndexes.length; i++){ Commission storage selectedCommission = commissions[_commissionIndexes[i]]; if (_rejections[i] || names[toLower(selectedCommission.name)] != 0){ } emit CommissionProcessed(_commissionIndexes[i], selectedCommission.status); } }
12,453,132
./full_match/5/0x4f18ce2D52158979B1aD0B353A7F53d2953Dd201/sources/project_/contracts/CollateralHub-ETH_flatV3.sol
incentive contract interface Fei Protocol Called by FEI token contract when transferring with an incentivized address should be appointed as a Minter or Burner as needed
interface IIncentiveController { function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } }
1,863,117
./full_match/56/0x463aEed8B4529D48e9326073cB655c24857a2115/sources/project_/contracts/PokumiWar.sol
Get the number of warrior for a Pokumi return players_ list of all participants/
function getAllParticipants() view external returns (address[] memory players_){ return players; }
3,254,715
/* The MIT License (MIT) Copyright (c) 2016 DFINITY Stiftung Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * title: The DFINITY Stiftung donation contract (FDC). * author: Timo Hanke * * This contract * - accepts on-chain donations for the foundation in ether * - tracks on-chain and off-chain donations made to the foundation * - assigns unrestricted tokens to addresses provided by donors * - assigns restricted tokens to DFINITY Stiftung and early contributors * * On-chain donations are received in ether are converted to Swiss francs (CHF). * Off-chain donations are received and recorded directly in Swiss francs. * Tokens are assigned at a rate of 10 tokens per CHF. * * There are two types of tokens initially. Unrestricted tokens are assigned to * donors and restricted tokens are assigned to DFINITY Stiftung and early * contributors. Restricted tokens are converted to unrestricted tokens in the * finalization phase, after which only unrestricted tokens exist. * * After the finalization phase, tokens assigned to DFINITY Stiftung and early * contributors will make up a pre-defined share of all tokens. This is achieved * through burning excess restricted tokens before their restriction is removed. */ pragma solidity ^0.4.6; // import "TokenTracker.sol"; /** * title: A contract that tracks numbers of tokens assigned to addresses. * author: Timo Hanke * * Optionally, assignments can be chosen to be of "restricted type". * Being "restricted" means that the token assignment may later be partially * reverted (or the tokens "burned") by the contract. * * After all token assignments are completed the contract * - burns some restricted tokens * - releases the restriction on the remaining tokens * The percentage of tokens that burned out of each assignment of restricted * tokens is calculated to achieve the following condition: * - the remaining formerly restricted tokens combined have a pre-configured * share (percentage) among all remaining tokens. * * Once the conversion process has started the contract enters a state in which * no more assignments can be made. */ contract TokenTracker { // Share of formerly restricted tokens among all tokens in percent uint public restrictedShare; // Mapping from address to number of tokens assigned to the address mapping(address => uint) public tokens; // Mapping from address to number of tokens assigned to the address that // underly a restriction mapping(address => uint) public restrictions; // Total number of (un)restricted tokens currently in existence uint public totalRestrictedTokens; uint public totalUnrestrictedTokens; // Total number of individual assignment calls have been for (un)restricted // tokens uint public totalRestrictedAssignments; uint public totalUnrestrictedAssignments; // State flag. Assignments can only be made if false. // Starting the conversion (burn) process irreversibly sets this to true. bool public assignmentsClosed = false; // The multiplier (defined by nominator and denominator) that defines the // fraction of all restricted tokens to be burned. // This is computed after assignments have ended and before the conversion // process starts. uint public burnMultDen; uint public burnMultNom; function TokenTracker(uint _restrictedShare) { // Throw if restricted share >= 100 if (_restrictedShare >= 100) { throw; } restrictedShare = _restrictedShare; } /** * PUBLIC functions * * - isUnrestricted (getter) * - multFracCeiling (library function) * - isRegistered(addr) (getter) */ /** * Return true iff the assignments are closed and there are no restricted * tokens left */ function isUnrestricted() constant returns (bool) { return (assignmentsClosed && totalRestrictedTokens == 0); } /** * Return the ceiling of (x*a)/b * * Edge cases: * a = 0: return 0 * b = 0, a != 0: error (solidity throws on division by 0) */ function multFracCeiling(uint x, uint a, uint b) returns (uint) { // Catch the case a = 0 if (a == 0) { return 0; } // Rounding up is the same as adding 1-epsilon and rounding down. // 1-epsilon is modeled as (b-1)/b below. return (x * a + (b - 1)) / b; } /** * Return true iff the address has tokens assigned (resp. restricted tokens) */ function isRegistered(address addr, bool restricted) constant returns (bool) { if (restricted) { return (restrictions[addr] > 0); } else { return (tokens[addr] > 0); } } /** * INTERNAL functions * * - assign * - closeAssignments * - unrestrict */ /** * Assign (un)restricted tokens to given address */ function assign(address addr, uint tokenAmount, bool restricted) internal { // Throw if assignments have been closed if (assignmentsClosed) { throw; } // Assign tokens tokens[addr] += tokenAmount; // Record restrictions and update total counters if (restricted) { totalRestrictedTokens += tokenAmount; totalRestrictedAssignments += 1; restrictions[addr] += tokenAmount; } else { totalUnrestrictedTokens += tokenAmount; totalUnrestrictedAssignments += 1; } } /** * Close future assignments. * * This is irreversible and closes all future assignments. * The function can only be called once. * * A call triggers the calculation of what fraction of restricted tokens * should be burned by subsequent calls to the unrestrict() function. * The result of this calculation is a multiplication factor whose nominator * and denominator are stored in the contract variables burnMultNom, * burnMultDen. */ function closeAssignmentsIfOpen() internal { // Return if assignments are not open if (assignmentsClosed) { return; } // Set the state to "closed" assignmentsClosed = true; /* * Calculate the total number of tokens that should remain after * conversion. This is based on the total number of unrestricted tokens * assigned so far and the pre-configured share that the remaining * formerly restricted tokens should have. */ uint totalTokensTarget = (totalUnrestrictedTokens * 100) / (100 - restrictedShare); // The total number of tokens in existence now. uint totalTokensExisting = totalRestrictedTokens + totalUnrestrictedTokens; /* * The total number of tokens that need to be burned to bring the existing * number down to the target number. If the existing number is lower than * the target then we won't burn anything. */ uint totalBurn = 0; if (totalTokensExisting > totalTokensTarget) { totalBurn = totalTokensExisting - totalTokensTarget; } // The fraction of restricted tokens to be burned (by nominator and // denominator). burnMultNom = totalBurn; burnMultDen = totalRestrictedTokens; /* * For verifying the correctness of the above calculation it may help to * note the following. * Given 0 <= restrictedShare < 100, we have: * - totalTokensTarget >= totalUnrestrictedTokens * - totalTokensExisting <= totalRestrictedTokens + totalTokensTarget * - totalBurn <= totalRestrictedTokens * - burnMultNom <= burnMultDen * Also note that burnMultDen = 0 means totalRestrictedTokens = 0, in which * burnMultNom = 0 as well. */ } /** * Unrestrict (convert) all restricted tokens assigned to the given address * * This function can only be called after assignments have been closed via * closeAssignments(). * The return value is the number of restricted tokens that were burned in * the conversion. */ function unrestrict(address addr) internal returns (uint) { // Throw is assignments are not yet closed if (!assignmentsClosed) { throw; } // The balance of restricted tokens for the given address uint restrictionsForAddr = restrictions[addr]; // Throw if there are none if (restrictionsForAddr == 0) { throw; } // Apply the burn multiplier to the balance of restricted tokens // The result is the ceiling of the value: // (restrictionForAddr * burnMultNom) / burnMultDen uint burn = multFracCeiling(restrictionsForAddr, burnMultNom, burnMultDen); // Remove the tokens to be burned from the address's balance tokens[addr] -= burn; // Delete record of restrictions delete restrictions[addr]; // Update the counters for total (un)restricted tokens totalRestrictedTokens -= restrictionsForAddr; totalUnrestrictedTokens += restrictionsForAddr - burn; return burn; } } // import "Phased.sol"; /* * title: Contract that advances through multiple configurable phases over time * author: Timo Hanke * * Phases are defined by their transition times. The moment one phase ends the * next one starts. Each time belongs to exactly one phase. * * The contract allows a limited set of changes to be applied to the phase * transitions while the contract is active. As a matter of principle, changes * are prohibited from effecting the past. They may only ever affect future * phase transitions. * * The permitted changes are: * - add a new phase after the last one * - end the current phase right now and transition to the next phase * immediately * - delay the start of a future phase (thereby pushing out all subsequent * phases by an equal amount of time) * - define a maximum delay for a specified phase */ contract Phased { /** * Array of transition times defining the phases * * phaseEndTime[i] is the time when phase i has just ended. * Phase i is defined as the following time interval: * [ phaseEndTime[i-1], * phaseEndTime[i] ) */ uint[] public phaseEndTime; /** * Number of phase transitions N = phaseEndTime.length * * There are N+1 phases, numbered 0,..,N. * The first phase has no start and the last phase has no end. */ uint public N; /** * Maximum delay for phase transitions * * maxDelay[i] is the maximum amount of time by which the transition * phaseEndTime[i] can be delayed. */ mapping(uint => uint) public maxDelay; /* * The contract has no constructor. * The contract initialized itself with no phase transitions (N = 0) and one * phase (N+1=1). * * There are two PUBLIC functions (getters): * - getPhaseAtTime * - isPhase * - getPhaseStartTime * * Note that both functions are guaranteed to return the same value when * called twice with the same argument (but at different times). */ /** * Return the number of the phase to which the given time belongs. * * Return value i means phaseEndTime[i-1] <= time < phaseEndTime[i]. * The given time must not be in the future (because future phase numbers may * still be subject to change). */ function getPhaseAtTime(uint time) constant returns (uint n) { // Throw if time is in the future if (time > now) { throw; } // Loop until we have found the "active" phase while (n < N && phaseEndTime[n] <= time) { n++; } } /** * Return true if the given time belongs to the given phase. * * Returns the logical equivalent of the expression * (phaseEndTime[i-1] <= time < phaseEndTime[i]). * * The given time must not be in the future (because future phase numbers may * still be subject to change). */ function isPhase(uint time, uint n) constant returns (bool) { // Throw if time is in the future if (time > now) { throw; } // Throw if index is out-of-range if (n >= N) { throw; } // Condition 1 if (n > 0 && phaseEndTime[n-1] > time) { return false; } // Condition 2 if (n < N && time >= phaseEndTime[n]) { return false; } return true; } /** * Return the start time of the given phase. * * This function is provided for convenience. * The given phase number must not be 0, as the first phase has no start time. * If calling for a future phase number the caller must be aware that future * phase times can be subject to change. */ function getPhaseStartTime(uint n) constant returns (uint) { // Throw if phase is the first phase if (n == 0) { throw; } return phaseEndTime[n-1]; } /* * There are 4 INTERNAL functions: * 1. addPhase * 2. setMaxDelay * 3. delayPhaseEndBy * 4. endCurrentPhaseIn * * This contract does not implement access control to these function, so * they are made internal. */ /** * 1. Add a phase after the last phase. * * The argument is the new endTime of the phase currently known as the last * phase, or, in other words the start time of the newly introduced phase. * All calls to addPhase() MUST be with strictly increasing time arguments. * It is not allowed to add a phase transition that lies in the past relative * to the current block time. */ function addPhase(uint time) internal { // Throw if new transition time is not strictly increasing if (N > 0 && time <= phaseEndTime[N-1]) { throw; } // Throw if new transition time is not in the future if (time <= now) { throw; } // Append new transition time to array phaseEndTime.push(time); N++; } /** * 2. Define a limit on the amount of time by which the given transition (i) * can be delayed. * * By default, transitions can not be delayed (limit = 0). */ function setMaxDelay(uint i, uint timeDelta) internal { // Throw if index is out-of-range if (i >= N) { throw; } maxDelay[i] = timeDelta; } /** * 3. Delay the end of the given phase (n) by the given time delta. * * The given phase must not have ended. * * This function can be called multiple times for the same phase. * The defined maximum delay will be enforced across multiple calls. */ function delayPhaseEndBy(uint n, uint timeDelta) internal { // Throw if index is out of range if (n >= N) { throw; } // Throw if phase has already ended if (now >= phaseEndTime[n]) { throw; } // Throw if the requested delay is higher than the defined maximum for the // transition if (timeDelta > maxDelay[n]) { throw; } // Subtract from the current max delay, so maxDelay is honored across // multiple calls maxDelay[n] -= timeDelta; // Push out all subsequent transitions by the same amount for (uint i = n; i < N; i++) { phaseEndTime[i] += timeDelta; } } /** * 4. End the current phase early. * * The current phase must not be the last phase, as the last phase has no end. * The current phase will end at time now plus the given time delta. * * The minimal allowed time delta is 1. This is avoid a race condition for * other transactions that are processed in the same block. * Setting phaseEndTime[n] to now would push all later transactions from the * same block into the next phase. * If the specified timeDelta is 0 the function gracefully bumps it up to 1. */ function endCurrentPhaseIn(uint timeDelta) internal { // Get the current phase number uint n = getPhaseAtTime(now); // Throw if we are in the last phase if (n >= N) { throw; } // Set timeDelta to the minimal allowed value if (timeDelta == 0) { timeDelta = 1; } // The new phase end should be earlier than the currently defined phase // end, otherwise we don't change it. if (now + timeDelta < phaseEndTime[n]) { phaseEndTime[n] = now + timeDelta; } } } // import "StepFunction.sol"; /* * title: A configurable step function * author: Timo Hanke * * The contract implements a step function going down from an initialValue to 0 * in a number of steps (nSteps). * The steps are distributed equally over a given time (phaseLength). * Having n steps means that the time phaseLength is divided into n+1 * sub-intervalls of equal length during each of which the function value is * constant. */ contract StepFunction { uint public phaseLength; uint public nSteps; uint public step; function StepFunction(uint _phaseLength, uint _initialValue, uint _nSteps) { // Throw if phaseLength does not leave enough room for number of steps if (_nSteps > _phaseLength) { throw; } // The reduction in value per step step = _initialValue / _nSteps; // Throw if _initialValue was not divisible by _nSteps if ( step * _nSteps != _initialValue) { throw; } phaseLength = _phaseLength; nSteps = _nSteps; } /* * Note the following edge cases. * initialValue = 0: is valid and will create the constant zero function * nSteps = 0: is valid and will create the constant zero function (only 1 * sub-interval) * phaseLength < nSteps: is valid, but unlikely to be intended (so the * constructor throws) */ /** * Evaluate the step function at a given time * * elapsedTime MUST be in the intervall [0,phaseLength) * The return value is between initialValue and 0, never negative. */ function getStepFunction(uint elapsedTime) constant returns (uint) { // Throw is elapsedTime is out-of-range if (elapsedTime >= phaseLength) { throw; } // The function value will bel calculated from the end value backwards. // Hence we need the time left, which will lie in the intervall // [0,phaseLength) uint timeLeft = phaseLength - elapsedTime - 1; // Calculate the number of steps away from reaching end value // When verifying the forumla below it may help to note: // at elapsedTime = 0 stepsLeft evaluates to nSteps, // at elapsedTime = -1 stepsLeft would evaluate to nSteps + 1. uint stepsLeft = ((nSteps + 1) * timeLeft) / phaseLength; // Apply the step function return stepsLeft * step; } } // import "Targets.sol"; /* * title: Contract implementing counters with configurable targets * author: Timo Hanke * * There is an arbitrary number of counters. Each counter is identified by its * counter id, a uint. Counters can never decrease. * * The contract has no constructor. The target values are set and re-set via * setTarget(). */ contract Targets { // Mapping from counter id to counter value mapping(uint => uint) public counter; // Mapping from counter id to target value mapping(uint => uint) public target; // A public getter that returns whether the target was reached function targetReached(uint id) constant returns (bool) { return (counter[id] >= target[id]); } /* * Modifying counter or target are internal functions. */ // (Re-)set the target function setTarget(uint id, uint _target) internal { target[id] = _target; } // Add to the counter // The function returns whether this current addition makes the counter reach // or cross its target value function addTowardsTarget(uint id, uint amount) internal returns (bool firstReached) { firstReached = (counter[id] < target[id]) && (counter[id] + amount >= target[id]); counter[id] += amount; } } // import "Parameters.sol"; /** * title: Configuration parameters for the FDC * author: Timo Hanke */ contract Parameters { /* * Time Constants * * Phases are, in this order: * earlyContribution (defined by end time) * pause * donation round0 (defined by start and end time) * pause * donation round1 (defined by start and end time) * pause * finalization (defined by start time, ends manually) * done */ // The start of round 0 is set to 2017-01-17 19:00 of timezone Europe/Zurich uint public constant round0StartTime = 1484676000; // The start of round 1 is set to 2017-05-17 19:00 of timezone Europe/Zurich // TZ="Europe/Zurich" date -d "2017-05-17 19:00" "+%s" uint public constant round1StartTime = 1495040400; // Transition times that are defined by duration uint public constant round0EndTime = round0StartTime + 6 weeks; uint public constant round1EndTime = round1StartTime + 6 weeks; uint public constant finalizeStartTime = round1EndTime + 1 weeks; // The finalization phase has a dummy end time because it is ended manually uint public constant finalizeEndTime = finalizeStartTime + 1000 years; // The maximum time by which donation round 1 can be delayed from the start // time defined above uint public constant maxRoundDelay = 270 days; // The time for which donation rounds remain open after they reach their // respective targets uint public constant gracePeriodAfterRound0Target = 1 days; uint public constant gracePeriodAfterRound1Target = 0 days; /* * Token issuance * * The following configuration parameters completely govern all aspects of the * token issuance. */ // Tokens assigned for the equivalent of 1 CHF in donations uint public constant tokensPerCHF = 10; // Minimal donation amount for a single on-chain donation uint public constant minDonation = 1 ether; // Bonus in percent added to donations throughout donation round 0 uint public constant round0Bonus = 200; // Bonus in percent added to donations at beginning of donation round 1 uint public constant round1InitialBonus = 25; // Number of down-steps for the bonus during donation round 1 uint public constant round1BonusSteps = 5; // The CHF targets for each of the donation rounds, measured in cents of CHF uint public constant millionInCents = 10**6 * 100; uint public constant round0Target = 1 * millionInCents; uint public constant round1Target = 20 * millionInCents; // Share of tokens eventually assigned to DFINITY Stiftung and early // contributors in % of all tokens eventually in existence uint public constant earlyContribShare = 22; } // FDC.sol contract FDC is TokenTracker, Phased, StepFunction, Targets, Parameters { // An identifying string, set by the constructor string public name; /* * Phases * * The FDC over its lifetime runs through a number of phases. These phases are * tracked by the base contract Phased. * * The FDC maps the chronologically defined phase numbers to semantically * defined states. */ // The FDC states enum state { pause, // Pause without any activity earlyContrib, // Registration of DFINITY Stiftung/early contributions round0, // Donation round 0 round1, // Donation round 1 offChainReg, // Grace period for registration of off-chain donations finalization, // Adjustment of DFINITY Stiftung/early contribution tokens // down to their share done // Read-only phase } // Mapping from phase number (from the base contract Phased) to FDC state mapping(uint => state) stateOfPhase; /* * Tokens * * The FDC uses base contract TokenTracker to: * - track token assignments for * - donors (unrestricted tokens) * - DFINITY Stiftung/early contributors (restricted tokens) * - convert DFINITY Stiftung/early contributor tokens down to their share * * The FDC uses the base contract Targets to: * - track the targets measured in CHF for each donation round * * The FDC itself: * - tracks the memos of off-chain donations (and prevents duplicates) * - tracks donor and early contributor addresses in two lists */ // Mapping to store memos that have been used mapping(bytes32 => bool) memoUsed; // List of registered addresses (each address will appear in one) address[] public donorList; address[] public earlyContribList; /* * Exchange rate and ether handling * * The FDC keeps track of: * - the exchange rate between ether and Swiss francs * - the total and per address ether donations */ // Exchange rate between ether and Swiss francs uint public weiPerCHF; // Total number of Wei donated on-chain so far uint public totalWeiDonated; // Mapping from address to total number of Wei donated for the address mapping(address => uint) public weiDonated; /* * Access control * * The following three addresses have access to restricted functions of the * FDC and to the donated funds. */ // Wallet address to which on-chain donations are being forwarded address public foundationWallet; // Address that is allowed to register DFINITY Stiftung/early contributions // and off-chain donations and to delay donation round 1 address public registrarAuth; // Address that is allowed to update the exchange rate address public exchangeRateAuth; // Address that is allowed to update the other authenticated addresses address public masterAuth; /* * Global variables */ // The phase numbers of the donation phases (set by the constructor, // thereafter constant) uint phaseOfRound0; uint phaseOfRound1; /* * Events * * - DonationReceipt: logs an on-chain or off-chain donation * - EarlyContribReceipt: logs the registration of early contribution * - BurnReceipt: logs the burning of token during finalization */ event DonationReceipt (address indexed addr, // DFN address of donor string indexed currency, // donation currency uint indexed bonusMultiplierApplied, // depends stage uint timestamp, // time occurred uint tokenAmount, // DFN to b recommended bytes32 memo); // unique note e.g TxID event EarlyContribReceipt (address indexed addr, // DFN address of donor uint tokenAmount, // *restricted* tokens bytes32 memo); // arbitrary note event BurnReceipt (address indexed addr, // DFN address adjusted uint tokenAmountBurned); // DFN deleted by adj. /** * Constructor * * The constructor defines * - the privileged addresses for access control * - the phases in base contract Phased * - the mapping between phase numbers and states * - the targets in base contract Targets * - the share for early contributors in base contract TokenTracker * - the step function for the bonus calculation in donation round 1 * * All configuration parameters are taken from base contract Parameters. */ function FDC(address _masterAuth, string _name) TokenTracker(earlyContribShare) StepFunction(round1EndTime-round1StartTime, round1InitialBonus, round1BonusSteps) { /* * Set identifying string */ name = _name; /* * Set privileged addresses for access control */ foundationWallet = _masterAuth; masterAuth = _masterAuth; exchangeRateAuth = _masterAuth; registrarAuth = _masterAuth; /* * Initialize base contract Phased * * |------------------------- Phase number (0-7) * | |-------------------- State name * | | |---- Transition number (0-6) * V V V */ stateOfPhase[0] = state.earlyContrib; addPhase(round0StartTime); // 0 stateOfPhase[1] = state.round0; addPhase(round0EndTime); // 1 stateOfPhase[2] = state.offChainReg; addPhase(round1StartTime); // 2 stateOfPhase[3] = state.round1; addPhase(round1EndTime); // 3 stateOfPhase[4] = state.offChainReg; addPhase(finalizeStartTime); // 4 stateOfPhase[5] = state.finalization; addPhase(finalizeEndTime); // 5 stateOfPhase[6] = state.done; // Let the other functions know what phase numbers the donation rounds were // assigned to phaseOfRound0 = 1; phaseOfRound1 = 3; // Maximum delay for start of donation rounds setMaxDelay(phaseOfRound0 - 1, maxRoundDelay); setMaxDelay(phaseOfRound1 - 1, maxRoundDelay); /* * Initialize base contract Targets */ setTarget(phaseOfRound0, round0Target); setTarget(phaseOfRound1, round1Target); } /* * PUBLIC functions * * Un-authenticated: * - getState * - getMultiplierAtTime * - donateAsWithChecksum * - finalize * - empty * - getStatus * * Authenticated: * - registerEarlyContrib * - registerOffChainDonation * - setExchangeRate * - delayRound1 * - setFoundationWallet * - setRegistrarAuth * - setExchangeRateAuth * - setAdminAuth */ /** * Get current state at the current block time */ function getState() constant returns (state) { return stateOfPhase[getPhaseAtTime(now)]; } /** * Return the bonus multiplier at a given time * * The given time must * - lie in one of the donation rounds, * - not lie in the future. * Otherwise there is no valid multiplier. */ function getMultiplierAtTime(uint time) constant returns (uint) { // Get phase number (will throw if time lies in the future) uint n = getPhaseAtTime(time); // If time lies in donation round 0 we return the constant multiplier if (stateOfPhase[n] == state.round0) { return 100 + round0Bonus; } // If time lies in donation round 1 we return the step function if (stateOfPhase[n] == state.round1) { return 100 + getStepFunction(time - getPhaseStartTime(n)); } // Throw outside of donation rounds throw; } /** * Send donation in the name a the given address with checksum * * The second argument is a checksum which must equal the first 4 bytes of the * SHA-256 digest of the byte representation of the address. */ function donateAsWithChecksum(address addr, bytes4 checksum) payable returns (bool) { // Calculate SHA-256 digest of the address bytes32 hash = sha256(addr); // Throw is the checksum does not match the first 4 bytes if (bytes4(hash) != checksum) { throw ; } // Call un-checksummed donate function return donateAs(addr); } /** * Finalize the balance for the given address * * This function triggers the conversion (and burn) of the restricted tokens * that are assigned to the given address. * * This function is only available during the finalization phase. It manages * the calls to closeAssignments() and unrestrict() of TokenTracker. */ function finalize(address addr) { // Throw if we are not in the finalization phase if (getState() != state.finalization) { throw; } // Close down further assignments in TokenTracker closeAssignmentsIfOpen(); // Burn tokens uint tokensBurned = unrestrict(addr); // Issue burn receipt BurnReceipt(addr, tokensBurned); // If no restricted tokens left if (isUnrestricted()) { // then end the finalization phase immediately endCurrentPhaseIn(0); } } /** * Send any remaining balance to the foundation wallet */ function empty() returns (bool) { return foundationWallet.call.value(this.balance)(); } /** * Get status information from the FDC * * This function returns a mix of * - global status of the FDC * - global status of the FDC specific for one of the two donation rounds * - status related to a specific token address (DFINITY address) * - status (balance) of an external Ethereum account * * Arguments are: * - donationRound: donation round to query (0 or 1) * - dfnAddr: token address to query * - fwdAddr: external Ethereum address to query */ function getStatus(uint donationRound, address dfnAddr, address fwdAddr) public constant returns ( state currentState, // current state (an enum) uint fxRate, // exchange rate of CHF -> ETH (Wei/CHF) uint currentMultiplier, // current bonus multiplier (0 if invalid) uint donationCount, // total individual donations made (a count) uint totalTokenAmount, // total DFN planned allocated to donors uint startTime, // expected start time of specified donation round uint endTime, // expected end time of specified donation round bool isTargetReached, // whether round target has been reached uint chfCentsDonated, // total value donated in specified round as CHF uint tokenAmount, // total DFN planned allocted to donor (user) uint fwdBalance, // total ETH (in Wei) waiting in fowarding address uint donated) // total ETH (in Wei) donated by DFN address { // The global status currentState = getState(); if (currentState == state.round0 || currentState == state.round1) { currentMultiplier = getMultiplierAtTime(now); } fxRate = weiPerCHF; donationCount = totalUnrestrictedAssignments; totalTokenAmount = totalUnrestrictedTokens; // The round specific status if (donationRound == 0) { startTime = getPhaseStartTime(phaseOfRound0); endTime = getPhaseStartTime(phaseOfRound0 + 1); isTargetReached = targetReached(phaseOfRound0); chfCentsDonated = counter[phaseOfRound0]; } else { startTime = getPhaseStartTime(phaseOfRound1); endTime = getPhaseStartTime(phaseOfRound1 + 1); isTargetReached = targetReached(phaseOfRound1); chfCentsDonated = counter[phaseOfRound1]; } // The status specific to the DFN address tokenAmount = tokens[dfnAddr]; donated = weiDonated[dfnAddr]; // The status specific to the Ethereum address fwdBalance = fwdAddr.balance; } /** * Set the exchange rate between ether and Swiss francs in Wei per CHF * * Must be called from exchangeRateAuth. */ function setWeiPerCHF(uint weis) { // Require permission if (msg.sender != exchangeRateAuth) { throw; } // Set the global state variable for exchange rate weiPerCHF = weis; } /** * Register early contribution in the name of the given address * * Must be called from registrarAuth. * * Arguments are: * - addr: address to the tokens are assigned * - tokenAmount: number of restricted tokens to assign * - memo: optional dynamic bytes of data to appear in the receipt */ function registerEarlyContrib(address addr, uint tokenAmount, bytes32 memo) { // Require permission if (msg.sender != registrarAuth) { throw; } // Reject registrations outside the early contribution phase if (getState() != state.earlyContrib) { throw; } // Add address to list if new if (!isRegistered(addr, true)) { earlyContribList.push(addr); } // Assign restricted tokens in TokenTracker assign(addr, tokenAmount, true); // Issue early contribution receipt EarlyContribReceipt(addr, tokenAmount, memo); } /** * Register off-chain donation in the name of the given address * * Must be called from registrarAuth. * * Arguments are: * - addr: address to the tokens are assigned * - timestamp: time when the donation came in (determines round and bonus) * - chfCents: value of the donation in cents of Swiss francs * - currency: the original currency of the donation (three letter string) * - memo: optional bytes of data to appear in the receipt * * The timestamp must not be in the future. This is because the timestamp * defines the donation round and the multiplier and future phase times are * still subject to change. * * If called during a donation round then the timestamp must lie in the same * phase and if called during the extended period for off-chain donations then * the timestamp must lie in the immediately preceding donation round. */ function registerOffChainDonation(address addr, uint timestamp, uint chfCents, string currency, bytes32 memo) { // Require permission if (msg.sender != registrarAuth) { throw; } // The current phase number and state corresponding state uint currentPhase = getPhaseAtTime(now); state currentState = stateOfPhase[currentPhase]; // Reject registrations outside the two donation rounds (incl. their // extended registration periods for off-chain donations) if (currentState != state.round0 && currentState != state.round1 && currentState != state.offChainReg) { throw; } // Throw if timestamp is in the future if (timestamp > now) { throw; } // Phase number and corresponding state of the timestamp uint timestampPhase = getPhaseAtTime(timestamp); state timestampState = stateOfPhase[timestampPhase]; // Throw if called during a donation round and the timestamp does not match // that phase. if ((currentState == state.round0 || currentState == state.round1) && (timestampState != currentState)) { throw; } // Throw if called during the extended period for off-chain donations and // the timestamp does not lie in the immediately preceding donation phase. if (currentState == state.offChainReg && timestampPhase != currentPhase-1) { throw; } // Throw if the memo is duplicated if (memoUsed[memo]) { throw; } // Set the memo item to true memoUsed[memo] = true; // Do the book-keeping bookDonation(addr, timestamp, chfCents, currency, memo); } /** * Delay a donation round * * Must be called from the address registrarAuth. * * This function delays the start of donation round 1 by the given time delta * unless the time delta is bigger than the configured maximum delay. */ function delayDonPhase(uint donPhase, uint timedelta) { // Require permission if (msg.sender != registrarAuth) { throw; } // Pass the call on to base contract Phased // Delaying the start of a donation round is the same as delaying the end // of the preceding phase if (donPhase == 0) { delayPhaseEndBy(phaseOfRound0 - 1, timedelta); } else if (donPhase == 1) { delayPhaseEndBy(phaseOfRound1 - 1, timedelta); } } /** * Set the forwarding address for donated ether * * Must be called from the address masterAuth before donation round 0 starts. */ function setFoundationWallet(address newAddr) { // Require permission if (msg.sender != masterAuth) { throw; } // Require phase before round 0 if (getPhaseAtTime(now) >= phaseOfRound0) { throw; } foundationWallet = newAddr; } /** * Set new authenticated address for setting exchange rate * * Must be called from the address masterAuth. */ function setExchangeRateAuth(address newAuth) { // Require permission if (msg.sender != masterAuth) { throw; } exchangeRateAuth = newAuth; } /** * Set new authenticated address for registrations * * Must be called from the address masterAuth. */ function setRegistrarAuth(address newAuth) { // Require permission if (msg.sender != masterAuth) { throw; } registrarAuth = newAuth; } /** * Set new authenticated address for admin * * Must be called from the address masterAuth. */ function setMasterAuth(address newAuth) { // Require permission if (msg.sender != masterAuth) { throw; } masterAuth = newAuth; } /* * PRIVATE functions * * - donateAs * - bookDonation */ /** * Process on-chain donation in the name of the given address * * This function is private because it shall only be called through its * wrapper donateAsWithChecksum. */ function donateAs(address addr) private returns (bool) { // The current state state st = getState(); // Throw if current state is not a donation round if (st != state.round0 && st != state.round1) { throw; } // Throw if donation amount is below minimum if (msg.value < minDonation) { throw; } // Throw if the exchange rate is not yet defined if (weiPerCHF == 0) { throw; } // Update counters for ether donations totalWeiDonated += msg.value; weiDonated[addr] += msg.value; // Convert ether to Swiss francs uint chfCents = (msg.value * 100) / weiPerCHF; // Do the book-keeping bookDonation(addr, now, chfCents, "ETH", ""); // Forward balance to the foundation wallet return foundationWallet.call.value(this.balance)(); } /** * Put an accepted donation in the books. * * This function * - cannot throw as all checks have been done before, * - is agnostic to the source of the donation (on-chain or off-chain) * - is agnostic to the currency * (the currency argument is simply passed through to the DonationReceipt) * */ function bookDonation(address addr, uint timestamp, uint chfCents, string currency, bytes32 memo) private { // The current phase uint phase = getPhaseAtTime(timestamp); // Add amount to the counter of the current phase bool targetReached = addTowardsTarget(phase, chfCents); // If the target was crossed then start the grace period if (targetReached && phase == getPhaseAtTime(now)) { if (phase == phaseOfRound0) { endCurrentPhaseIn(gracePeriodAfterRound0Target); } else if (phase == phaseOfRound1) { endCurrentPhaseIn(gracePeriodAfterRound1Target); } } // Bonus multiplier that was valid at the given time uint bonusMultiplier = getMultiplierAtTime(timestamp); // Apply bonus to amount in Swiss francs chfCents = (chfCents * bonusMultiplier) / 100; // Convert Swiss francs to amount of tokens uint tokenAmount = (chfCents * tokensPerCHF) / 100; // Add address to list if new if (!isRegistered(addr, false)) { donorList.push(addr); } // Assign unrestricted tokens in TokenTracker assign(addr,tokenAmount,false); // Issue donation receipt DonationReceipt(addr, currency, bonusMultiplier, timestamp, tokenAmount, memo); } }
Put an accepted donation in the books. This function - cannot throw as all checks have been done before, - is agnostic to the source of the donation (on-chain or off-chain) - is agnostic to the currency (the currency argument is simply passed through to the DonationReceipt)/ The current phase Add amount to the counter of the current phase If the target was crossed then start the grace period Add address to list if new
function bookDonation(address addr, uint timestamp, uint chfCents, string currency, bytes32 memo) private { uint phase = getPhaseAtTime(timestamp); bool targetReached = addTowardsTarget(phase, chfCents); if (targetReached && phase == getPhaseAtTime(now)) { if (phase == phaseOfRound0) { endCurrentPhaseIn(gracePeriodAfterRound0Target); endCurrentPhaseIn(gracePeriodAfterRound1Target); } } if (!isRegistered(addr, false)) { donorList.push(addr); } memo); }
1,050,762
/** *Submitted for verification at Etherscan.io on 2021-02-27 */ /** *Submitted for verification at Etherscan.io on 2020-12-29 */ pragma solidity =0.6.12; // SPDX-License-Identifier: MIT interface PocketSwapV2Pair { 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; } library SafeMatswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library PocketSwapV2Library { using SafeMatswap 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, 'PocketSwapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'PocketSwapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'769bed9500aa97b61c54bd21d2e876339984fecd50d2a5d78668f8fdb3754b6f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = PocketSwapV2Pair(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, 'PocketSwapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'PocketSwapV2Library: 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, 'PocketSwapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'PocketSwapV2Library: 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, 'PocketSwapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'PocketSwapV2Library: 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, 'PocketSwapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'PocketSwapV2Library: 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); } } } // 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'); } } interface IPocketSwapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IPocketSwapV2Router02 is IPocketSwapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IPocketSwapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20PocketSwap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } contract PocketSwapV2Router02 is IPocketSwapV2Router02 { using SafeMatswap for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'PocketSwapV2Router: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IPocketSwapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IPocketSwapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = PocketSwapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = PocketSwapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'PocketSwapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = PocketSwapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'PocketSwapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = PocketSwapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = PocketSwapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = PocketSwapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = PocketSwapV2Pair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = PocketSwapV2Library.pairFor(factory, tokenA, tokenB); PocketSwapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = PocketSwapV2Pair(pair).burn(to); (address token0,) = PocketSwapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'PocketSwapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'PocketSwapV2Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = PocketSwapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; PocketSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = PocketSwapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; PocketSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20PocketSwap(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = PocketSwapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; PocketSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = PocketSwapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? PocketSwapV2Library.pairFor(factory, output, path[i + 2]) : _to; PocketSwapV2Pair(PocketSwapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = PocketSwapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = PocketSwapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'PocketSwapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'PocketSwapV2Router: INVALID_PATH'); amounts = PocketSwapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'PocketSwapV2Router: INVALID_PATH'); amounts = PocketSwapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'PocketSwapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'PocketSwapV2Router: INVALID_PATH'); amounts = PocketSwapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'PocketSwapV2Router: INVALID_PATH'); amounts = PocketSwapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'PocketSwapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = PocketSwapV2Library.sortTokens(input, output); PocketSwapV2Pair pair = PocketSwapV2Pair(PocketSwapV2Library.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20PocketSwap(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = PocketSwapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? PocketSwapV2Library.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20PocketSwap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20PocketSwap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'PocketSwapV2Router: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(PocketSwapV2Library.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20PocketSwap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20PocketSwap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'PocketSwapV2Router: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20PocketSwap(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return PocketSwapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return PocketSwapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return PocketSwapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return PocketSwapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return PocketSwapV2Library.getAmountsIn(factory, amountOut, path); } }
refund dust eth, if any
function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = PocketSwapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = PocketSwapV2Pair(pair).mint(to); if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); }
10,566,594
./partial_match/1/0x891696CCa87aa2f175124b412198c23D54680E31/sources/NFTWinner.sol
Returns the storage slot and value for the approved address of `tokenId`./ The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
function _getApprovedSlotAndAddress(uint256 tokenId) internal view returns (uint256 approvedAddressSlot, address approvedAddress) { TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId]; assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) } }
3,585,526
./partial_match/3/0xE07345F0b4824B5b163389FA4FEF713a9d1F4E7F/sources/LavevelToken.sol
fallback function to send ether to for Crowd sale/ self-referrer check bonus for referrer
function () public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 tokens = weiAmount.mul(basePrice).div(1 ether); uint256 returnWei = 0; if(tokensSold.add(tokens) > cap){ uint256 newTokens = cap.sub(tokensSold); uint256 newWei = newTokens.div(basePrice).mul(1 ether); returnWei = weiAmount.sub(newWei); weiAmount = newWei; tokens = newTokens; } remainingTokens = cap.sub(tokensSold); if(returnWei > 0){ msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].add(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.add(tokens); if(msg.data.length == 5) { address referer = bytesToAddress(bytes(msg.data)); require(referer != msg.sender); uint refererTokens = tokens.mul(2).div(100); balances[referer] = balances[referer].add(refererTokens); emit Transfer(address(this), referer, refererTokens); totalSupply_ = totalSupply_.add(refererTokens); } }
5,319,656
./full_match/1/0xa213C344D14e9aE9DA2b70a8f9A0122131d59274/sources/contracts/libraries/ERC1155/ERC1155PS.sol
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 token owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); }
8,357,629
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ====================== CrossChainBridgeBacker ====================== // ==================================================================== // Takes FRAX, FXS, and collateral and bridges it back to the Ethereum Mainnet // Allows withdrawals to designated AMOs // Tokens will need to be bridged to the contract first // 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 import "../Math/Math.sol"; import "../ERC20/__CROSSCHAIN/IAnyswapV4ERC20.sol"; import "../ERC20/__CROSSCHAIN/CrossChainCanonical.sol"; import "../Frax/FraxAMOMinter.sol"; import "../ERC20/ERC20.sol"; import "../ERC20/SafeERC20.sol"; import '../Uniswap/TransferHelper.sol'; import "../Staking/Owned.sol"; import '../Oracle/ICrossChainOracle.sol'; import '../Misc_AMOs/ICrossChainAMO.sol'; contract CrossChainBridgeBacker is Owned { // SafeMath automatically included in Solidity >= 8.0.0 using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core IAnyswapV4ERC20 public anyFRAX; CrossChainCanonical public canFRAX; IAnyswapV4ERC20 public anyFXS; CrossChainCanonical public canFXS; ERC20 public collateral_token; ICrossChainOracle public cross_chain_oracle; // Admin addresses address public timelock_address; // AMO addresses address[] public amos_array; mapping(address => bool) public eoa_amos; // These need to be tracked so allBalances() skips them mapping(address => bool) public amos; // Mapping is also used for faster verification // Informational string public name; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Bridge related address[3] public bridge_addresses; address public destination_address_override; string public non_evm_destination_address; // Frax lent balances mapping(address => uint256) public frax_lent_balances; // Amount of FRAX the contract lent, by AMO uint256 public frax_lent_sum = 0; // Across all AMOs uint256 public frax_bridged_back_sum = 0; // Across all AMOs // Fxs lent balances mapping(address => uint256) public fxs_lent_balances; // Amount of FXS the contract lent, by AMO uint256 public fxs_lent_sum = 0; // Across all AMOs uint256 public fxs_bridged_back_sum = 0; // Across all AMOs // Collateral lent balances mapping(address => uint256) public collat_lent_balances; // Amount of collateral the contract lent, by AMO uint256 public collat_lent_sum = 0; // Across all AMOs uint256 public collat_bridged_back_sum = 0; // Across all AMOs // Collateral balance related uint256 public missing_decimals; /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } modifier validAMO(address amo_address) { require(amos[amo_address], "Invalid AMO"); _; } modifier validCanonicalToken(address token_address) { require ( token_address == address(canFRAX) || token_address == address(canFXS) || token_address == address(collateral_token), "Invalid canonical token" ); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address _timelock_address, address _cross_chain_oracle_address, address[5] memory _token_addresses, address[3] memory _bridge_addresses, address _destination_address_override, string memory _non_evm_destination_address, string memory _name ) Owned(_owner) { // Core timelock_address = _timelock_address; cross_chain_oracle = ICrossChainOracle(_cross_chain_oracle_address); anyFRAX = IAnyswapV4ERC20(_token_addresses[0]); canFRAX = CrossChainCanonical(_token_addresses[1]); anyFXS = IAnyswapV4ERC20(_token_addresses[2]); canFXS = CrossChainCanonical(_token_addresses[3]); collateral_token = ERC20(_token_addresses[4]); missing_decimals = uint(18) - collateral_token.decimals(); // Bridge related bridge_addresses = _bridge_addresses; destination_address_override = _destination_address_override; non_evm_destination_address = _non_evm_destination_address; // Informational name = _name; // Add this bridger as an AMO. Cannot used the addAMO function amos[address(this)] = true; amos_array.push(address(this)); frax_lent_balances[address(this)] = 0; fxs_lent_balances[address(this)] = 0; collat_lent_balances[address(this)] = 0; } /* ========== VIEWS ========== */ function allAMOAddresses() external view returns (address[] memory) { return amos_array; } function allAMOsLength() external view returns (uint256) { return amos_array.length; } function getTokenType(address token_address) public view returns (uint256) { // 0 = FRAX, 1 = FXS, 2 = Collateral if (token_address == address(anyFRAX) || token_address == address(canFRAX)) return 0; else if (token_address == address(anyFXS) || token_address == address(canFXS)) return 1; else if (token_address == address(collateral_token)) return 2; // Revert on invalid tokens revert("getTokenType: Invalid token"); } function showTokenBalances() public view returns (uint256[5] memory tkn_bals) { tkn_bals[0] = anyFRAX.balanceOf(address(this)); // anyFRAX tkn_bals[1] = canFRAX.balanceOf(address(this)); // canFRAX tkn_bals[2] = anyFXS.balanceOf(address(this)); // anyFXS tkn_bals[3] = canFXS.balanceOf(address(this)); // canFXS tkn_bals[4] = collateral_token.balanceOf(address(this)); // anyFRAX } function showAllocations() public view returns (uint256[12] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Get some token balances uint256[5] memory tkn_bals = showTokenBalances(); // FRAX allocations[0] = tkn_bals[0] + tkn_bals[1]; // Free FRAX allocations[1] = frax_lent_sum; // Lent FRAX allocations[2] = allocations[0] + allocations[1]; // Total FRAX // FXS allocations[3] = tkn_bals[2] + tkn_bals[3]; // Free FXS allocations[4] = fxs_lent_sum; // Lent FXS allocations[5] = allocations[3] + allocations[4]; // Total FXS allocations[6] = (allocations[5] * (cross_chain_oracle.getPrice(address(canFXS)))) / PRICE_PRECISION; // Total FXS value in USD // Collateral allocations[7] = tkn_bals[4]; // Free Collateral allocations[8] = collat_lent_sum; // Lent Collateral allocations[9] = allocations[7] + allocations[8]; // Total Collateral, in native decimals() allocations[10] = allocations[9] * (10 ** missing_decimals); // Total Collateral, in E18 // Total USD value of everything, in E18 allocations[11] = allocations[2] + allocations[6] + allocations[10]; } function allBalances() public view returns ( uint256 frax_ttl, uint256 fxs_ttl, uint256 col_ttl, // in native decimals() uint256 ttl_val_usd_e18 ) { // Handle this contract first (amos_array[0]) uint256[12] memory allocations = showAllocations(); frax_ttl = allocations[2]; fxs_ttl = allocations[5]; col_ttl = allocations[9]; ttl_val_usd_e18 = allocations[11]; // [0] will always be this address, so skip it to avoid an infinite loop for (uint i = 1; i < amos_array.length; i++){ // Exclude null addresses and EOAs if (amos_array[i] != address(0) && !eoa_amos[amos_array[i]]){ ( uint256 frax_bal, uint256 fxs_bal, uint256 collat_bal, uint256 total_val_e18 ) = ICrossChainAMO(amos_array[i]).allDollarBalances(); frax_ttl += frax_bal; fxs_ttl += fxs_bal; col_ttl += collat_bal; ttl_val_usd_e18 += total_val_e18; } } } /* ========== BRIDGING / AMO FUNCTIONS ========== */ // Used for crumbs and drop-ins sitting in this contract // Can also manually bridge back anyFRAX // If do_swap is true, it will swap out canTokens in this contract for anyTokens in the canToken contracts function selfBridge(uint256 token_type, uint256 token_amount, bool do_swap) external onlyByOwnGov { require(token_type == 0 || token_type == 1 || token_type == 2, 'Invalid token type'); _receiveBack(address(this), token_type, token_amount, true, do_swap); } // AMOs should only be giving back canonical tokens function receiveBackViaAMO(address canonical_token_address, uint256 token_amount, bool do_bridging) external validCanonicalToken(canonical_token_address) validAMO(msg.sender) { // Pull in the tokens from the AMO TransferHelper.safeTransferFrom(canonical_token_address, msg.sender, address(this), token_amount); // Get the token type uint256 token_type = getTokenType(canonical_token_address); _receiveBack(msg.sender, token_type, token_amount, do_bridging, true); } // Optionally bridge function _receiveBack(address from_address, uint256 token_type, uint256 token_amount, bool do_bridging, bool do_swap) internal { if (do_bridging) { // Swap canTokens for bridgeable anyTokens, if necessary if (token_type == 0) { // FRAX // Swap the canonical tokens out for bridgeable anyTokens if (do_swap) _swapCanonicalForAny(0, token_amount); } else if (token_type == 1){ // FXS // Swap the canonical tokens out for bridgeable anyTokens if (do_swap) _swapCanonicalForAny(1, token_amount); } // Defaults to sending to this contract's address on the other side address address_to_send_to = address(this); // See if there is an overriden destination if (destination_address_override != address(0)) address_to_send_to = destination_address_override; // Can be overridden _bridgingLogic(token_type, address_to_send_to, token_amount); } // Account for the lent balances if (token_type == 0){ if (token_amount >= frax_lent_balances[from_address]) frax_lent_balances[from_address] = 0; else frax_lent_balances[from_address] -= token_amount; if (token_amount >= frax_lent_sum) frax_lent_sum = 0; else frax_lent_sum -= token_amount; if (do_bridging) frax_bridged_back_sum += token_amount; } else if (token_type == 1){ if (token_amount >= fxs_lent_balances[from_address]) fxs_lent_balances[from_address] = 0; else fxs_lent_balances[from_address] -= token_amount; if (token_amount >= fxs_lent_sum) fxs_lent_sum = 0; else fxs_lent_sum -= token_amount; if (do_bridging) fxs_bridged_back_sum += token_amount; } else { if (token_amount >= collat_lent_balances[from_address]) collat_lent_balances[from_address] = 0; else collat_lent_balances[from_address] -= token_amount; if (token_amount >= collat_lent_sum) collat_lent_sum = 0; else collat_lent_sum -= token_amount; if (do_bridging) collat_bridged_back_sum += token_amount; } } // Meant to be overriden function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal virtual { revert("Need bridging logic"); } /* ========== LENDING FUNCTIONS ========== */ // Lend out canonical FRAX function lendFraxToAMO(address destination_amo, uint256 frax_amount) external onlyByOwnGov validAMO(destination_amo) { // Track the balances frax_lent_balances[destination_amo] += frax_amount; frax_lent_sum += frax_amount; // Transfer TransferHelper.safeTransfer(address(canFRAX), destination_amo, frax_amount); } // Lend out canonical FXS function lendFxsToAMO(address destination_amo, uint256 fxs_amount) external onlyByOwnGov validAMO(destination_amo) { // Track the balances fxs_lent_balances[destination_amo] += fxs_amount; fxs_lent_sum += fxs_amount; // Transfer TransferHelper.safeTransfer(address(canFXS), destination_amo, fxs_amount); } // Lend out collateral function lendCollatToAMO(address destination_amo, uint256 collat_amount) external onlyByOwnGov validAMO(destination_amo) { // Track the balances collat_lent_balances[destination_amo] += collat_amount; collat_lent_sum += collat_amount; // Transfer TransferHelper.safeTransfer(address(collateral_token), destination_amo, collat_amount); } /* ========== SWAPPING, GIVING, MINTING, AND BURNING ========== */ // ----------------- SWAPPING ----------------- // Swap anyToken for canToken [GOVERNANCE CALLABLE] function swapAnyForCanonical(uint256 token_type, uint256 token_amount) external onlyByOwnGov { _swapAnyForCanonical(token_type, token_amount); } // Swap anyToken for canToken [INTERNAL] function _swapAnyForCanonical(uint256 token_type, uint256 token_amount) internal { if (token_type == 0) { // FRAX // Approve and swap anyFRAX.approve(address(canFRAX), token_amount); canFRAX.exchangeOldForCanonical(address(anyFRAX), token_amount); } else { // FXS // Approve and swap anyFXS.approve(address(canFXS), token_amount); canFXS.exchangeOldForCanonical(address(anyFXS), token_amount); } } // Swap canToken for anyToken [GOVERNANCE CALLABLE] function swapCanonicalForAny(uint256 token_type, uint256 token_amount) external onlyByOwnGov { _swapCanonicalForAny(token_type, token_amount); } // Swap canToken for anyToken [INTERNAL] function _swapCanonicalForAny(uint256 token_type, uint256 token_amount) internal { if (token_type == 0) { // FRAX // Approve and swap canFRAX.approve(address(canFRAX), token_amount); canFRAX.exchangeCanonicalForOld(address(anyFRAX), token_amount); } else { // FXS // Approve and swap canFXS.approve(address(canFXS), token_amount); canFXS.exchangeCanonicalForOld(address(anyFXS), token_amount); } } // ----------------- GIVING ----------------- // Give anyToken to the canToken contract function giveAnyToCan(uint256 token_type, uint256 token_amount) external onlyByOwnGov { if (token_type == 0) { // FRAX // Transfer TransferHelper.safeTransfer(address(anyFRAX), address(canFRAX), token_amount); } else { // FXS // Transfer TransferHelper.safeTransfer(address(anyFXS), address(canFXS), token_amount); } } // ----------------- FRAX ----------------- function mintCanonicalFrax(uint256 frax_amount) external onlyByOwnGov { canFRAX.minter_mint(address(this), frax_amount); } function burnCanonicalFrax(uint256 frax_amount) external onlyByOwnGov { canFRAX.minter_burn(frax_amount); } // ----------------- FXS ----------------- function mintCanonicalFxs(uint256 fxs_amount) external onlyByOwnGov { canFXS.minter_mint(address(this), fxs_amount); } function burnCanonicalFxs(uint256 fxs_amount) external onlyByOwnGov { canFXS.minter_burn(fxs_amount); } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ function collectBridgeTokens(uint256 token_type, address bridge_token_address, uint256 token_amount) external onlyByOwnGov { if (token_type == 0) { canFRAX.withdrawBridgeTokens(bridge_token_address, token_amount); } else if (token_type == 1) { canFXS.withdrawBridgeTokens(bridge_token_address, token_amount); } else { revert("Invalid token_type"); } } // Adds an AMO function addAMO(address amo_address, bool is_eoa) external onlyByOwnGov { require(amo_address != address(0), "Zero address detected"); if (is_eoa) { eoa_amos[amo_address] = true; } else { (uint256 frax_val_e18, uint256 fxs_val_e18, uint256 collat_val_e18, uint256 total_val_e18) = ICrossChainAMO(amo_address).allDollarBalances(); require(frax_val_e18 >= 0 && fxs_val_e18 >= 0 && collat_val_e18 >= 0 && total_val_e18 >= 0, "Invalid AMO"); } require(amos[amo_address] == false, "Address already exists"); amos[amo_address] = true; amos_array.push(amo_address); frax_lent_balances[amo_address] = 0; fxs_lent_balances[amo_address] = 0; collat_lent_balances[amo_address] = 0; emit AMOAdded(amo_address); } // Removes an AMO function removeAMO(address amo_address) external onlyByOwnGov { require(amo_address != address(0), "Zero address detected"); require(amos[amo_address] == true, "Address nonexistant"); // Delete from the mapping delete amos[amo_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < amos_array.length; i++){ if (amos_array[i] == amo_address) { amos_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit AMORemoved(amo_address); } // 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 onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function setOracleAddress(address _new_cc_oracle_address) external onlyByOwnGov { cross_chain_oracle = ICrossChainOracle(_new_cc_oracle_address); } function setTimelock(address _new_timelock) external onlyByOwnGov { timelock_address = _new_timelock; } function setBridgeInfo( address _frax_bridge_address, address _fxs_bridge_address, address _collateral_bridge_address, address _destination_address_override, string memory _non_evm_destination_address ) external onlyByOwnGov { // Make sure there are valid bridges require( _frax_bridge_address != address(0) && _fxs_bridge_address != address(0) && _collateral_bridge_address != address(0) , "Invalid bridge address"); // Set bridge addresses bridge_addresses = [_frax_bridge_address, _fxs_bridge_address, _collateral_bridge_address]; // Overridden cross-chain destination address destination_address_override = _destination_address_override; // Set bytes32 / non-EVM address on the other chain, if applicable non_evm_destination_address = _non_evm_destination_address; emit BridgeInfoChanged(_frax_bridge_address, _fxs_bridge_address, _collateral_bridge_address, _destination_address_override, _non_evm_destination_address); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event AMOAdded(address amo_address); event AMORemoved(address amo_address); event RecoveredERC20(address token, uint256 amount); event BridgeInfoChanged(address frax_bridge_address, address fxs_bridge_address, address collateral_bridge_address, address destination_address_override, string non_evm_destination_address); }
Swap canToken for anyToken [INTERNAL] FRAX Approve and swap FXS Approve and swap
function _swapCanonicalForAny(uint256 token_type, uint256 token_amount) internal { if (token_type == 0) { canFRAX.approve(address(canFRAX), token_amount); canFRAX.exchangeCanonicalForOld(address(anyFRAX), token_amount); } else { canFXS.approve(address(canFXS), token_amount); canFXS.exchangeCanonicalForOld(address(anyFXS), token_amount); } }
12,644,462