file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// Sources flattened with buidler v0.1.5 pragma solidity 0.4.24; // File openzeppelin-solidity/contracts/token/ERC20/[email protected] /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File openzeppelin-solidity/contracts/math/[email protected] /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private balances_; mapping (address => mapping (address => uint256)) private allowed_; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances_[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed_[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances_[msg.sender]); require(_to != address(0)); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed_[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances_[_from]); require(_value <= allowed_[_from][msg.sender]); require(_to != address(0)); balances_[_from] = balances_[_from].sub(_value); balances_[_to] = balances_[_to].add(_value); allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed_[msg.sender][_spender] = ( allowed_[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed_[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed_[msg.sender][_spender] = 0; } else { allowed_[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances_[_account] = balances_[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0); require(_amount <= balances_[_account]); totalSupply_ = totalSupply_.sub(_amount); balances_[_account] = balances_[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed_[_account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed_[_account][msg.sender] = allowed_[_account][msg.sender].sub( _amount); _burn(_account, _amount); } } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( IERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( IERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File openzeppelin-solidity/contracts/ownership/[email protected] /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File openzeppelin-solidity/contracts/access/rbac/[email protected] /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage _role, address _account) internal { _role.bearer[_account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage _role, address _account) internal { _role.bearer[_account] = false; } /** * @dev check if an account has this role * // reverts */ function check(Role storage _role, address _account) internal view { require(has(_role, _account)); } /** * @dev check if an account has this role * @return bool */ function has(Role storage _role, address _account) internal view returns (bool) { return _role.bearer[_account]; } } // File openzeppelin-solidity/contracts/access/rbac/[email protected] /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) public view { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) public view returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function _addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function _removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File openzeppelin-solidity/contracts/cryptography/[email protected] /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param _hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param _signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 _hash, bytes _signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (_signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 _hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash) ); } } // File openzeppelin-solidity/contracts/access/[email protected] /** * @title SignatureBouncer * @author PhABC, Shrugs and aflesher * @dev Bouncer allows users to submit a signature as a permission to do an action. * If the signature is from one of the authorized bouncer addresses, the signature * is valid. The owner of the contract adds/removes bouncers. * Bouncer addresses can be individual servers signing grants or different * users within a decentralized club that have permission to invite other members. * This technique is useful for whitelists and airdrops; instead of putting all * valid addresses on-chain, simply sign a grant of the form * keccak256(abi.encodePacked(`:contractAddress` + `:granteeAddress`)) using a valid bouncer address. * Then restrict access to your crowdsale/whitelist/airdrop using the * `onlyValidSignature` modifier (or implement your own using _isValidSignature). * In addition to `onlyValidSignature`, `onlyValidSignatureAndMethod` and * `onlyValidSignatureAndData` can be used to restrict access to only a given method * or a given method with given parameters respectively. * See the tests Bouncer.test.js for specific usage examples. * @notice A method that uses the `onlyValidSignatureAndData` modifier must make the _signature * parameter the "last" parameter. You cannot sign a message that has its own * signature in it so the last 128 bytes of msg.data (which represents the * length of the _signature data and the _signaature data itself) is ignored when validating. * Also non fixed sized parameters make constructing the data in the signature * much more complex. See https://ethereum.stackexchange.com/a/50616 for more details. */ contract SignatureBouncer is Ownable, RBAC { using ECDSA for bytes32; // Name of the bouncer role. string private constant ROLE_BOUNCER = "bouncer"; // Function selectors are 4 bytes long, as documented in // https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector uint256 private constant METHOD_ID_SIZE = 4; // Signature size is 65 bytes (tightly packed v + r + s), but gets padded to 96 bytes uint256 private constant SIGNATURE_SIZE = 96; /** * @dev requires that a valid signature of a bouncer was provided */ modifier onlyValidSignature(bytes _signature) { require(_isValidSignature(msg.sender, _signature)); _; } /** * @dev requires that a valid signature with a specifed method of a bouncer was provided */ modifier onlyValidSignatureAndMethod(bytes _signature) { require(_isValidSignatureAndMethod(msg.sender, _signature)); _; } /** * @dev requires that a valid signature with a specifed method and params of a bouncer was provided */ modifier onlyValidSignatureAndData(bytes _signature) { require(_isValidSignatureAndData(msg.sender, _signature)); _; } /** * @dev Determine if an account has the bouncer role. * @return true if the account is a bouncer, false otherwise. */ function isBouncer(address _account) public view returns(bool) { return hasRole(_account, ROLE_BOUNCER); } /** * @dev allows the owner to add additional bouncer addresses */ function addBouncer(address _bouncer) public onlyOwner { require(_bouncer != address(0)); _addRole(_bouncer, ROLE_BOUNCER); } /** * @dev allows the owner to remove bouncer addresses */ function removeBouncer(address _bouncer) public onlyOwner { _removeRole(_bouncer, ROLE_BOUNCER); } /** * @dev is the signature of `this + sender` from a bouncer? * @return bool */ function _isValidSignature(address _address, bytes _signature) internal view returns (bool) { return _isValidDataHash( keccak256(abi.encodePacked(address(this), _address)), _signature ); } /** * @dev is the signature of `this + sender + methodId` from a bouncer? * @return bool */ function _isValidSignatureAndMethod(address _address, bytes _signature) internal view returns (bool) { bytes memory data = new bytes(METHOD_ID_SIZE); for (uint i = 0; i < data.length; i++) { data[i] = msg.data[i]; } return _isValidDataHash( keccak256(abi.encodePacked(address(this), _address, data)), _signature ); } /** * @dev is the signature of `this + sender + methodId + params(s)` from a bouncer? * @notice the _signature parameter of the method being validated must be the "last" parameter * @return bool */ function _isValidSignatureAndData(address _address, bytes _signature) internal view returns (bool) { require(msg.data.length > SIGNATURE_SIZE); bytes memory data = new bytes(msg.data.length - SIGNATURE_SIZE); for (uint i = 0; i < data.length; i++) { data[i] = msg.data[i]; } return _isValidDataHash( keccak256(abi.encodePacked(address(this), _address, data)), _signature ); } /** * @dev internal function to convert a hash to an eth signed message * and then recover the signature and check it against the bouncer role * @return bool */ function _isValidDataHash(bytes32 _hash, bytes _signature) internal view returns (bool) { address signer = _hash .toEthSignedMessageHash() .recover(_signature); return isBouncer(signer); } } // File contracts/bouncers/EscrowedERC20Bouncer.sol contract EscrowedERC20Bouncer is SignatureBouncer { using SafeERC20 for IERC20; uint256 public nonce; modifier onlyBouncer() { require(isBouncer(msg.sender), "DOES_NOT_HAVE_BOUNCER_ROLE"); _; } modifier validDataWithoutSender(bytes _signature) { require(_isValidSignatureAndData(address(this), _signature), "INVALID_SIGNATURE"); _; } constructor(address _bouncer) public { addBouncer(_bouncer); } /** * allow anyone with a valid bouncer signature for the msg data to send `_amount` of `_token` to `_to` */ function withdraw(uint256 _nonce, IERC20 _token, address _to, uint256 _amount, bytes _signature) public validDataWithoutSender(_signature) { require(_nonce > nonce, "NONCE_GT_NONCE_REQUIRED"); nonce = _nonce; _token.safeTransfer(_to, _amount); } /** * Allow the bouncer to withdraw all of the ERC20 tokens in the contract */ function withdrawAll(IERC20 _token, address _to) public onlyBouncer { _token.safeTransfer(_to, _token.balanceOf(address(this))); } } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract ERC20Mintable is ERC20, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { _mint(_to, _amount); emit Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File contracts/bouncers/MintableERC20Bouncer.sol contract MintableERC20Bouncer is SignatureBouncer { uint256 public nonce; modifier validDataWithoutSender(bytes _signature) { require(_isValidSignatureAndData(address(this), _signature), "INVALID_SIGNATURE"); _; } constructor(address _bouncer) public { addBouncer(_bouncer); } /** * allow anyone with a valid bouncer signature for the msg data to mint `_amount` of `_token` to `_to` */ function mint(uint256 _nonce, ERC20Mintable _token, address _to, uint256 _amount, bytes _signature) public validDataWithoutSender(_signature) { require(_nonce > nonce, "NONCE_GT_NONCE_REQUIRED"); nonce = _nonce; _token.mint(_to, _amount); } } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File openzeppelin-solidity/contracts/proposals/ERC1046/[email protected] /** * @title ERC-1047 Token Metadata * @dev See https://eips.ethereum.org/EIPS/eip-1046 * @dev tokenURI must respond with a URI that implements https://eips.ethereum.org/EIPS/eip-1047 * @dev TODO - update https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/IERC721.sol#L17 when 1046 is finalized */ contract ERC20TokenMetadata is IERC20 { function tokenURI() external view returns (string); } contract ERC20WithMetadata is ERC20TokenMetadata { string private tokenURI_ = ""; constructor(string _tokenURI) public { tokenURI_ = _tokenURI; } function tokenURI() external view returns (string) { return tokenURI_; } } // File contracts/tokens/KataToken.sol contract KataToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20WithMetadata { constructor( string _name, string _symbol, uint8 _decimals, string _tokenURI ) ERC20WithMetadata(_tokenURI) ERC20Detailed(_name, _symbol, _decimals) public {} } // File contracts/deploy/TokenAndBouncerDeployer.sol contract TokenAndBouncerDeployer is Ownable { event Deployed(address indexed token, address indexed bouncer); function deploy( string _name, string _symbol, uint8 _decimals, string _tokenURI, address _signer ) public onlyOwner { MintableERC20Bouncer bouncer = new MintableERC20Bouncer(_signer); KataToken token = new KataToken(_name, _symbol, _decimals, _tokenURI); token.transferOwnership(address(bouncer)); emit Deployed(address(token), address(bouncer)); selfdestruct(msg.sender); } } // File contracts/mocks/MockToken.sol contract MockToken is ERC20Detailed, ERC20Mintable { constructor(string _name, string _symbol, uint8 _decimals) ERC20Detailed(_name, _symbol, _decimals) ERC20Mintable() ERC20() public { } } // File contracts/old/ClaimableToken.sol // import "./MintableERC721Token.sol"; // import "openzeppelin-solidity/contracts/token/ERC721/DefaultTokenURI.sol"; // contract ClaimableToken is DefaultTokenURI, MintableERC721Token { // constructor(string _name, string _symbol, string _tokenURI) // MintableERC721Token(_name, _symbol) // DefaultTokenURI(_tokenURI) // public // { // } // } // File contracts/old/ClaimableTokenDeployer.sol // import "./ClaimableTokenMinter.sol"; // import "./ClaimableToken.sol"; // contract ClaimableTokenDeployer { // ClaimableToken public token; // ClaimableTokenMinter public minter; // constructor( // string _name, // string _symbol, // string _tokenURI, // address _bouncer // ) // public // { // token = new ClaimableToken(_name, _symbol, _tokenURI); // minter = new ClaimableTokenMinter(token); // token.addOwner(msg.sender); // token.addMinter(address(minter)); // minter.addOwner(msg.sender); // minter.addBouncer(_bouncer); // } // } // File contracts/old/ClaimableTokenMinter.sol // import "./ClaimableToken.sol"; // import "openzeppelin-solidity/contracts/access/ERC721Minter.sol"; // import "openzeppelin-solidity/contracts/access/NonceTracker.sol"; // contract ClaimableTokenMinter is NonceTracker, ERC721Minter { // constructor(ClaimableToken _token) // ERC721Minter(_token) // public // { // } // function mint(bytes _sig) // withAccess(msg.sender, 1) // public // returns (uint256) // { // return super.mint(_sig); // } // }
Internal function that burns an amount of the token of a given account, deducting from the sender's allowance for said account. Uses the internal _burn function. _account The account whose tokens will be burnt. _amount The amount that will be burnt./ Should https:github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, this function needs to emit an event with the updated approval.
function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed_[_account][msg.sender]); allowed_[_account][msg.sender] = allowed_[_account][msg.sender].sub( _amount); _burn(_account, _amount); }
7,222,390
./partial_match/56/0xF25BC3059Cc041d17Eb253d8883546412102b9D7/sources/cBNB_TOKEN.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, acccBNBPerShare: 0, depositFeeBP: _depositFeeBP })); }
11,246,942
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization * control functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC223 * @dev ERC223 contract interface with ERC20 functions and events * Fully backward compatible with ERC20 * Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events 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, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /** * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } /** * @title COMETUBU * @author COMETUBU * @dev COMETUBU is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract COMETUBU is ERC223, Ownable { using SafeMath for uint256; string public name = "COMETUBU"; string public symbol = "TUBU"; uint8 public decimals = 0; uint256 public totalSupply = 88e8 * 1e0; uint256 public distributeAmount = 0; bool public mintingFinished = false; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ function COMETUBU() public { balanceOf[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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 success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[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 * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e0); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e0); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e0); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn't work */ function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[owner] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) owner.transfer(msg.value); balanceOf[owner] = balanceOf[owner].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); Transfer(owner, msg.sender, distributeAmount); } /** * @dev fallback function */ function() payable public { autoDistribute(); } }
Function that is called when a user or another contract wants to transfer funds/
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; return transferToAddress(_to, _value, _data); } }
1,436,108
./full_match/1/0x44f26a7b2b58621D97240b09350B66803Faa1E1a/sources/contracts/BasicGuildRewardNFT.sol
Checks the validity of the signature for the given params.
function isValidSignature(address receiver, uint256 userId, bytes calldata signature) internal view returns (bool) { if (signature.length != 65) revert IncorrectSignature(); bytes32 message = keccak256(abi.encode(receiver, userId, block.chainid, address(this))) .toEthSignedMessageHash(); return message.recover(signature) == IGuildRewardNFTFactory(factoryProxy).validSigner(); }
4,822,245
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.3; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/FixedPoint.sol"; import "./EtherEmpireTypes.sol"; import "./EtherEmpireStorage.sol"; import "./EtherEmpireDiplomacy.sol"; import "./EtherEmpireCombat.sol"; import "./smart_treaties/SmartTreaty.sol"; // Handles entity creation and core features contract EtherEmpireWorld is Ownable, EtherEmpireStorage { event FarmBuilt(address _owner, uint32 _id, uint16 _locx, uint16 _locy); event WallBuilt(address _owner, uint32 _id, uint16 _locx, uint16 _locy); event ArmyRecruited(address _owner, uint32 _id, uint16 _locx, uint16 _locy); event ArmyMoved(address _owner, uint32 _id, uint16 _locx, uint16 _locy); event HarvestInitiated(address _owner, uint32 _id, uint16 _locx, uint16 _locy, uint64 _completionBlock); // , UniswapV2Pair _lpContractAddress constructor(uint64 _yieldMin_32x32, uint64 _yieldRange_32x32, uint64 _armyToWallTokenRatio_32x32, uint64 _farmOccupationBurnRate_32x32, EtherEmpireToken _tokenContractAddress, uint64 _blocksToDivest) { yieldMin_32x32 = _yieldMin_32x32; yieldRange_32x32 = _yieldRange_32x32; armyToWallTokenRatio_32x32 = _armyToWallTokenRatio_32x32; farmOccupationBurnRate_32x32 = _farmOccupationBurnRate_32x32; globalLandValue_32x32 = 0; spawnedEntitiesCount = 0; tokenContract = _tokenContractAddress; blocksToDivest = _blocksToDivest; // lpContract = _lpContractAddress; } modifier onlyOwnerOf(uint32 _id, address _owner) { requireIsOwner(_id, _owner); _; } modifier emptyAtLayer(uint16 _locx, uint16 _locy, uint8 layer) { require(allEntities[_locx + _locy * map_width + layer * map_width * map_height].entityType == EtherEmpireTypes.EntityType.EMPTY, "This needs to be an empty land!"); _; } function _idAtXY(uint16 _locx, uint16 _locy, uint8 layer) public view returns(uint32) { return _locx + _locy * map_width + map_width * map_height * layer; } function requireIsOwner(uint32 _id, address _owner) internal view { require(entityToOwner[_id] == _owner, "You may only call this function on an entity that you own"); } function _randMod(uint _seed, uint _nonce, uint _mod) internal pure returns(uint) { return uint(keccak256(abi.encodePacked(_seed, _nonce))) % _mod; } // This function can only be called by whoever deployed the contract function populateLand(uint16 _width, uint16 _height, uint _seed) onlyOwner public { require(allEntities[0].entityType == EtherEmpireTypes.EntityType.EMPTY, "Non-empty world"); map_width = _width; map_height = _height; // Declare a local nonce so that the same seed will generate the same map uint nonce = 0; for (uint16 y = 0; y < _width; y++) { for (uint16 x = 0; x < _height; x++) { uint32 index = x + y * map_width; // Currently only generates arable lands EtherEmpireTypes.Entity memory newLand = EtherEmpireTypes.Entity(uint32(index), EtherEmpireTypes.EntityType.TILE, 0, uint64(FixedPoint.add(yieldMin_32x32, _randMod(_seed, nonce++, yieldRange_32x32), 32, 32, 32)), x, y); allEntities[index] = newLand; entityToOwner[index] = address(0); // wilderness } } } // Returns total farm yield at current block number, in the UQ144x112 format. Assumes supply of tokens do not exceed 2**144 - 1 function yieldValue(uint16 _locx, uint16 _locy) view public returns(uint64) { uint32 index = _locx + _locy * map_width + map_height * map_width; EtherEmpireTypes.Entity storage thisFarm = allEntities[index]; require(thisFarm.entityType == EtherEmpireTypes.EntityType.FARM, "No farm built here"); uint64 landValueAtBlock_32x32 = globalLandValue_32x32; uint64 blockNumber = uint64(block.number); uint64 cumulativeYield_32x32 = 0; uint64 lastHarvestable = harvestTimer[index] == 0? blockNumber : (harvestTimer[index] - blocksToDivest - 1); for (uint64 i = blockNumber; i > allEntities[index].qualifier1_32x32; i--) { if (i <= lastHarvestable) { cumulativeYield_32x32 += uint64(FixedPoint.multiply((FixedPoint.divide(thisFarm.qualifier2_32x32, landValueAtBlock_32x32, 32, 32, 32, 32)), tokensBurntAtBlock[i], 32, 0, 32, 32)); } landValueAtBlock_32x32 = uint64(uint(FixedPoint.addSigned(int64(landValueAtBlock_32x32), -1 * int64(landValueAddedAtBlock_32x32[i]), 32, 32, 32))); } return cumulativeYield_32x32; } // Requires implementation of ERC20 function buildFarm(uint16 _locx, uint16 _locy, uint32 tokenStaked) public emptyAtLayer(_locx, _locy, 1) returns(uint32) { uint32 index = _locx + _locy * map_width + map_height * map_width; uint64 blockNumber = uint64(block.number); tokenContract.transferFrom(msg.sender, address(this), tokenStaked); uint64 landValue_32x32 = uint64(FixedPoint.sqrt(uint64(tokenStaked) << 32, 32, 32)); // Added precision uint64 modifier_32x32 = allEntities[_idAtXY(_locx, _locy, 0)].qualifier2_32x32; landValue_32x32 = uint64(FixedPoint.multiply(landValue_32x32, modifier_32x32, 32, 32, 32, 32)); // Include land modifier allEntities[index] = EtherEmpireTypes.Entity(index, EtherEmpireTypes.EntityType.FARM, blockNumber, landValue_32x32, _locx, _locy); landValueAddedAtBlock_32x32[blockNumber] = int64(FixedPoint.addSigned(landValueAddedAtBlock_32x32[blockNumber], int64(landValue_32x32), 32, 32, 32)); globalLandValue_32x32 = uint64(FixedPoint.add(globalLandValue_32x32, landValue_32x32, 32, 32, 32)); entityToOwner[index] = msg.sender; emit FarmBuilt(msg.sender, index, _locx, _locy); return index; } // Requires implementation of ERC20 function buildWall(uint16 _locx, uint16 _locy, uint32 tokenSpent) public emptyAtLayer(_locx, _locy, 1) returns(uint32) { uint32 index = _locx + _locy * map_width + map_height * map_width; uint64 blockNumber = uint64(block.number); tokenContract.transferFrom(msg.sender, address(this), tokenSpent); uint64 wallFortification_32x32 = uint64(tokenSpent) << 32; allEntities[index] = EtherEmpireTypes.Entity(index, EtherEmpireTypes.EntityType.WALL, blockNumber, wallFortification_32x32, _locx, _locy); tokensBurntAtBlock[blockNumber] = tokensBurntAtBlock[blockNumber] + tokenSpent; emit WallBuilt(msg.sender, index, _locx, _locy); return index; } // Requires implementation of ERC20 function buildArmy(uint16 _locx, uint16 _locy, uint32 tokenSpent) public returns(uint32) { EtherEmpireTypes.Entity memory l2 = allEntities[_locx + _locy * map_width + 1 * map_width * map_height]; require(l2.entityType == EtherEmpireTypes.EntityType.FARM, "Must be built on farm!"); require(entityToOwner[l2.id] == msg.sender, "Must be built on your farm!"); uint32 index = spawnedEntitiesCount + 2 * map_width * map_height; uint64 blockNumber = uint64(block.number); tokenContract.transferFrom(msg.sender, address(this), tokenSpent); uint64 armySize_32x32 = uint64(FixedPoint.divide(uint64(tokenSpent) << 32, armyToWallTokenRatio_32x32, 32, 32, 32, 32)); allEntities[index] = EtherEmpireTypes.Entity(index, EtherEmpireTypes.EntityType.ARMY, blockNumber, armySize_32x32, _locx, _locy); tokensBurntAtBlock[blockNumber] = tokensBurntAtBlock[blockNumber] + tokenSpent; entityToOwner[index] = msg.sender; spawnedEntitiesCount += 1; emit ArmyRecruited(msg.sender, index, _locx, _locy); return index; } function harvestFarm(uint16 _locx, uint16 _locy) public returns(bool) { uint32 index = _locx + _locy * map_width + map_width * map_height; requireIsOwner(index, msg.sender); uint64 landValue_32x32 = allEntities[index].qualifier2_32x32; uint64 modifier_32x32 = allEntities[_idAtXY(_locx, _locy, 0)].qualifier2_32x32; uint64 blockNumber = uint64(block.number); if (harvestTimer[index] == 0) { harvestTimer[index] = blockNumber + blocksToDivest; landValueAddedAtBlock_32x32[blockNumber] = int64(FixedPoint.addSigned(landValueAddedAtBlock_32x32[blockNumber], -1 * int64(landValue_32x32), 32, 32, 32)); globalLandValue_32x32 = uint64(uint(FixedPoint.addSigned(int64(globalLandValue_32x32), -1 * int64(landValue_32x32), 32, 32, 32))); emit HarvestInitiated(msg.sender, index, _locx, _locy, harvestTimer[index]); return false; } else if (harvestTimer[index] > uint64(block.number)) { return false; } landValue_32x32 = uint64(FixedPoint.divide(landValue_32x32, modifier_32x32, 32, 32, 32, 32)); // Factor out land modifier uint64 redeemable = uint64(FixedPoint.multiply(landValue_32x32, landValue_32x32, 32, 32, 32, 32)) + yieldValue(_locx, _locy); tokenContract.transfer(msg.sender, redeemable); harvestTimer[index] = 0; EtherEmpireCombat.destroy(index, msg.sender, allEntities, entityToOwner); return true; } function changeEntityOwner(uint32 _id, address _newOwner) public { require(msg.sender == entityToOwner[_id] || authorizedTreaty[entityToOwner[_id]][msg.sender]); entityToOwner[_id] = _newOwner; } function getEntityOwner(uint32 _id) view external returns(address) { return entityToOwner[_id]; } // // To be implemented // function createTreaty(address ref) external { // address newTreaty = SmartTreaty(ref).duplicate(); // authorizedTreaty[msg.sender][newTreaty] = true; // SmartTreaty(newTreaty).sign(msg.sender); // } // function signTreaty(address ref) external { // authorizedTreaty[msg.sender][ref] = true; // SmartTreaty(ref).sign(msg.sender); // } // Relay external calls to specific libraries function armyAttack(uint32 _self, uint32 _other) external onlyOwnerOf(_self, msg.sender) returns(bool) { return EtherEmpireCombat.armyAttack(_self, _other, allEntities, entityToOwner, nonAggression, farmOccupationBurnRate_32x32); } function armyMove(uint32 _id, uint16 _locx, uint16 _locy) external onlyOwnerOf(_id, msg.sender) returns(bool) { bool successfulMovement = EtherEmpireCombat.armyMove(_id, _locx, _locy, allEntities, entityToOwner, access); if (successfulMovement) emit ArmyMoved(msg.sender, _id, _locx, _locy); return successfulMovement; } }
Requires implementation of ERC20
function buildFarm(uint16 _locx, uint16 _locy, uint32 tokenStaked) public emptyAtLayer(_locx, _locy, 1) returns(uint32) { uint32 index = _locx + _locy * map_width + map_height * map_width; uint64 blockNumber = uint64(block.number); tokenContract.transferFrom(msg.sender, address(this), tokenStaked); uint64 modifier_32x32 = allEntities[_idAtXY(_locx, _locy, 0)].qualifier2_32x32; allEntities[index] = EtherEmpireTypes.Entity(index, EtherEmpireTypes.EntityType.FARM, blockNumber, landValue_32x32, _locx, _locy); landValueAddedAtBlock_32x32[blockNumber] = int64(FixedPoint.addSigned(landValueAddedAtBlock_32x32[blockNumber], int64(landValue_32x32), 32, 32, 32)); globalLandValue_32x32 = uint64(FixedPoint.add(globalLandValue_32x32, landValue_32x32, 32, 32, 32)); entityToOwner[index] = msg.sender; emit FarmBuilt(msg.sender, index, _locx, _locy); return index; }
12,991,376
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract BetHandler is AccessControl, Pausable { using SafeERC20 for IERC20; using Counters for Counters.Counter; bytes32 public constant FUNDS_MANAGER_ROLE = keccak256("FUNDS_MANAGER_ROLE"); bytes32 public constant MARKET_MANAGER_ROLE = keccak256("MARKET_MANAGER_ROLE"); uint256 private constant EXP = 1e18; enum Direction {UP, DOWN} enum State { NEW, // Bet is registreted in smart contract (this is also state of not yet placed bets, for them bet.user == address(0)) ACCEPTED, // Bet is executed by Binance Bot CANCEL, // Bet can not be executed and should be returned WIN, // Bet closed and user wins something LOSE // Bet closed and user lost part of his money } event BetPlaced(uint256 indexed id, address indexed user, Direction direction, uint256 amount); event BetAccepted(uint256 indexed id, uint256 startPrice, uint256 winPrice, uint256 losePrice); event BetWon(uint256 indexed id, uint256 closePrice); event BetLost(uint256 indexed id, uint256 closePrice); event BetCanceled(uint256 indexed id); struct Bet { address user; uint256 acceptedTimestamp; Direction direction; uint256 amount; State state; } IERC20 public token; // Token accepted as payment Counters.Counter public nextBetId; mapping(uint256=>Bet) public bets; modifier onlyAdmin(){ require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "!admin"); _; } modifier onlyFundsManager(){ require(hasRole(FUNDS_MANAGER_ROLE, _msgSender()), "!funds manager"); _; } modifier onlyMarketManager(){ require(hasRole(FUNDS_MANAGER_ROLE, _msgSender()), "!market manager"); _; } constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(FUNDS_MANAGER_ROLE, _msgSender()); _setupRole(MARKET_MANAGER_ROLE, _msgSender()); nextBetId.increment(); // Make valid ids starting from 1 } function placeBet(Direction direction, uint256 amount) external whenNotPaused { token.safeTransferFrom(_msgSender(), address(this), amount); uint256 betId = nextBetId.current(); nextBetId.increment(); bets[betId] = Bet({ user: _msgSender(), acceptedTimestamp: 0, direction: direction, amount: amount, state: State.NEW }); emit BetPlaced(betId, _msgSender(), direction, amount); } function betAccepted(uint256 betId, uint256 startPrice, uint256 winPrice, uint256 losePrice) external onlyMarketManager { Bet storage bet = bets[betId]; require(bet.state == State.NEW, "wrong bet state"); bet.state = State.ACCEPTED; emit BetAccepted(betId, startPrice, winPrice, losePrice); } function betCanceled(uint256 betId) external onlyMarketManager { Bet storage bet = bets[betId]; require(bet.state == State.ACCEPTED, "wrong bet state"); bet.state = State.CANCEL; payout(bet.user, bet.amount); emit BetCanceled(betId); } function betWon(uint256 betId, uint256 closePrice, uint256 winAmount) external onlyMarketManager { Bet storage bet = bets[betId]; require(bet.state == State.ACCEPTED, "wrong bet state"); bet.state = State.WIN; // TODO better validate winAmount require( (winAmount >= bet.amount) && (winAmount <= (bet.amount * 2)), "wrong win"); payout(bet.user, winAmount); emit BetWon(betId, closePrice); } function betLost(uint256 betId, uint256 closePrice, uint256 refundAmount) external onlyMarketManager { Bet storage bet = bets[betId]; require(bet.state == State.ACCEPTED, "wrong bet state"); bet.state = State.LOSE; // TODO better validate refundAmount require(refundAmount <= bet.amount, "wrong refund"); payout(bet.user, refundAmount); emit BetLost(betId, closePrice); } function pruneBets(uint256 from, uint256 to) external onlyAdmin { // TODO implement bets pruning } function setToken(IERC20 _token) external onlyAdmin { token = _token; } function pause() external onlyAdmin { _pause(); } function unpause() external onlyAdmin { _unpause(); } function payout(address user, uint256 amount) internal { // TODO implement payout queue token.transfer(user, amount); } }
TODO implement bets pruning
function pruneBets(uint256 from, uint256 to) external onlyAdmin { }
5,465,145
./full_match/84531/0x0c2698D597752E400ecC7f270be0A6fdc2bBe1A1/sources/contracts/DCNT721A.sol
Gets the current minting fee for the specified token. quantity The quantity of tokens used to calculate the minting fee. return fee The current fee for minting the specified token./
function mintFee(uint256 quantity) external view returns (uint256 fee) { if ( feeManager != address(0) ) { (fee, ) = IFeeManager(feeManager).calculateFees(edition.tokenPrice, quantity); } }
14,318,722
/** *Submitted for verification at Etherscan.io on 2022-02-06 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.11; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.11; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.11; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.11; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.11; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.11; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.11; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.11; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.11; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.11; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.11; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.11; /** * @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 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; } } interface IERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } pragma solidity ^0.8.11; /// @title A 10,000 multi-chain PFP project for the travelers. /// @author Project by TripsCommunity, coding by jacmos3 /// @notice The first multichain project for the Travel Industry. First derivative of Traveler Loot in Ethereum. /// @custom:website www.littletraveler.org | www.travelerloot.com contract LittleTraveler is ERC721Enumerable, Ownable, ReentrancyGuard { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint8 public chainNumber; uint8 public counterOwner = 0; uint8 public constant maxMintAmount = 10; uint8 public constant maxPerOwner = 100; uint16 public constant maxThisChain = 1000; uint16 public constant maxSupplyAllChains = 10000; uint256 public cost; uint256 public costTrips; uint256 public floorIndex; uint256 public roofIndex; address public tripsAddress; address public travelerLootAddress; address public treasurerAddress; string private constant ERROR_PAUSED = "Mintings paused."; string private constant ERROR_TOO_MUCH = "Cannot mint so many."; string private constant ERROR_MINT_FINISHED = "Minting is finished."; string private constant ERROR_DONT_OWN_TRAVELER_LOOT = "You do not own any Traveler Loot."; string private constant ERROR_NOT_POSSIBLE_ON_THIS_CHAIN = "This minting method is not available for this chain. Use Another method!"; string private constant ERROR_TOKEN_ID_DOES_NOT_EXISTS = "This tokenId doesnt exist"; bool public paused = true; bool public revealed = false; string public notRevealedUri; event PermanentURI(string _value, uint256 indexed _id); constructor(string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri, uint256 _cost, uint256 _costTrips, uint8 _chainNumber, address _tripsAddress, address _travelerLootAddress, address _treasurerAddress) ERC721(_name, _symbol) { baseURI = _initBaseURI; notRevealedUri = _initNotRevealedUri; cost = _cost; costTrips = _costTrips; tripsAddress = _tripsAddress; travelerLootAddress = _travelerLootAddress; treasurerAddress = _treasurerAddress; chainNumber = _chainNumber; floorIndex = chainNumber * maxThisChain + maxPerOwner; roofIndex = floorIndex + maxThisChain - maxPerOwner; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function _processingMints(uint256 _mintAmount) internal { uint256 baseSupply = totalSupply(); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, floorIndex + baseSupply + i); } } /// @notice Mints Little Traveler by paying native coin. /// @param _mintAmount the number of Little Traveler you want to mint /// @dev check requirements: different chains have different configurations and not in every chains it is possible to mint using this function function mint(uint256 _mintAmount) external payable nonReentrant{ require(!paused, ERROR_PAUSED); require(travelerLootAddress == address(0) || tripsAddress == address(0), ERROR_NOT_POSSIBLE_ON_THIS_CHAIN); require(_mintAmount <= maxMintAmount, ERROR_TOO_MUCH); _mintAmount = _mintAmount > 0 ? _mintAmount : 1; require((floorIndex + totalSupply()) + _mintAmount <= roofIndex, ERROR_MINT_FINISHED); require(msg.value >= cost * _mintAmount); _processingMints(_mintAmount); } /// @notice Mints Little Traveler by holding a Little Traveler. /// @dev This is only thought for ethereum network and it is leaded by a configuration param function mintByTravelerLoot() external nonReentrant{ require(!paused, ERROR_PAUSED); require(travelerLootAddress != address(0), ERROR_NOT_POSSIBLE_ON_THIS_CHAIN); require(IERC721(travelerLootAddress).balanceOf(_msgSender()) > 0, ERROR_DONT_OWN_TRAVELER_LOOT); _processingMints(1); } /// @notice Mints Little Traveler by paying Trips coin. /// @dev check requirements: different chains have different configurations and not in every chains it is possible to mint using this function /// @param _mintAmount the amount of Little Traveler you want to mint function mintWithTrips(uint8 _mintAmount) external nonReentrant{ require(!paused, ERROR_PAUSED); require(tripsAddress != address(0), ERROR_NOT_POSSIBLE_ON_THIS_CHAIN); require(_mintAmount <= maxMintAmount, ERROR_TOO_MUCH); _mintAmount = _mintAmount > 0 ? _mintAmount : 1; IERC20(tripsAddress).transferFrom(msg.sender, treasurerAddress, costTrips * _mintAmount); _processingMints(_mintAmount); } /// @notice Mints Little Traveler by proving to be the owner of the contract /// @dev contract owner has 100 reserved Little Traveler to be used as airdrops or self-funding function mintByOwner() external onlyOwner nonReentrant{ require(!paused, ERROR_PAUSED); uint256 adjustedTokenId = floorIndex - maxPerOwner + counterOwner + 1; require(adjustedTokenId > floorIndex - maxPerOwner && adjustedTokenId <= floorIndex, ERROR_TOO_MUCH); _safeMint(msg.sender, adjustedTokenId); counterOwner++; } /// @notice If you want to check which tokenId owns a particular address. /// @param _owner address of the owner to check /// @return an array of tokenId owned by the input address function walletOfOwner(address _owner) external view returns (uint256[] memory){ uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint16 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } /// @notice Provides URI of the metadata and image. /// @param tokenId the tokenId of the Little Traveler to check /// @return the metadata & image URI json function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ require( _exists(tokenId), ERROR_TOKEN_ID_DOES_NOT_EXISTS); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)): ""; } /// @notice Freeze metadata on opensea /// @dev to call after all the nft are minted function freezeMetadata() external onlyOwner { for (uint256 tokenId = floorIndex - maxPerOwner; tokenId <= roofIndex; tokenId++){ emit PermanentURI(tokenURI(tokenId), tokenId); } } /// @notice Reveal images /// @dev only owner can call it function reveal() external onlyOwner { revealed = true; } /// @notice setter cost variable /// @dev onlyowner can call it /// @param _newCost insert the new native coin cost function setCost(uint256 _newCost) external onlyOwner { cost = _newCost; } /// @notice setter costTrips variable /// @dev onlyowner can call it /// @param _newCostTrips insert the new Trips coin cost function setCostTrips(uint256 _newCostTrips) external onlyOwner { costTrips = _newCostTrips; } /// @notice setter NotRevealedURI variable /// @dev onlyowner can call it /// @param _notRevealedURI insert the new url of the not revealed Little Traveler function setNotRevealedURI(string memory _notRevealedURI) external onlyOwner { notRevealedUri = _notRevealedURI; } /// @notice setter baseURI variable /// @dev onlyowner can call it /// @param _newBaseURI insert the new url of the baseUri function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } /// @notice setter baseExtension variable /// @dev onlyowner can call it /// @param _newBaseExtension insert the new baseExtension function setBaseExtension(string memory _newBaseExtension) external onlyOwner { baseExtension = _newBaseExtension; } /// @notice setter tripsAddress variable /// @dev onlyowner can call it /// @param _tripsAddress insert the tripsAddress function setTripsAddress(address _tripsAddress) external onlyOwner{ tripsAddress = _tripsAddress; } /// @notice setter travelerLootAddress variable /// @dev onlyowner can call it /// @param _travelerLootAddress insert the new travelerLootAddress function setTravelerLootAddress(address _travelerLootAddress) external onlyOwner{ travelerLootAddress = _travelerLootAddress; } /// @notice setter treasurerAddress variable /// @dev onlyowner can call it /// @param _treasurerAddress insert the new treasurerAddress function setTreasurerAddress(address _treasurerAddress) external onlyOwner{ treasurerAddress = _treasurerAddress; } /// @notice pause/unpause the mintings /// @dev onlyowner can call it /// @param _state if true it pauses the mintings, if false it allows new mintings function pause(bool _state) external onlyOwner { paused = _state; } /// @notice withdraw native coin funds from the contract /// @dev onlyowner can call it. NOTE: TRIPS coin are directly going to the treasurerAddress. Never transit from here. function withdraw() external onlyOwner { payable(treasurerAddress).transfer(address(this).balance); } }
If you want to check which tokenId owns a particular address. _owner address of the owner to check return an array of tokenId owned by the input address
function walletOfOwner(address _owner) external view returns (uint256[] memory){ uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint16 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; }
10,511,375
pragma solidity 0.6.12; import "@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol"; import "./CybarToken.sol"; import "./ShotBar.sol"; interface IMigratorBarkeeper { // Perform LP token migration from legacy CybarSwap to CybarSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to CybarSwap LP tokens. // CybarSwap must mint EXACTLY the same amount of CybarSwap LP tokens or // else something bad will happen. Traditional CybarSwap does not // do that so be careful! function migrate(IBEP20 token) external returns (IBEP20); } /* * @notice MasterBarkeeper controls the Cybar token distributed to the different pools. * It can mint new Cybar. * @dev The pool with pool Id = 0 is the Cybar staking pool */ contract MasterBarkeeper is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; struct UserInfo { uint256 amount; uint256 rewardDebt; uint256 lastDepositTime; } struct PoolInfo { IBEP20 lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 accCybarPerShare; uint256 withdrawFeePeriod; uint256 withdrawFee; } CybarToken public cybar; ShotBar public shot; address public devaddr; address public treasury; uint256 public cybarPerBlock; uint256 public BONUS_MULTIPLIER = 1; IMigratorBarkeeper public migrator; PoolInfo[] public poolInfo; mapping(uint256 => mapping(address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; /* * Maximal withdrawal fee parameters. MAX_WITHDRAW_FEE is given in 10**-4 */ uint256 public constant MAX_WITHDRAW_FEE = 200; uint256 public constant MAX_WITHDRAW_FEE_PERIOD = 72 hours; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( CybarToken _cybar, ShotBar _shot, address _devaddr, address _treasury, uint256 _cybarPerBlock, uint256 _startBlock ) public { cybar = _cybar; shot = _shot; devaddr = _devaddr; treasury = _treasury; cybarPerBlock = _cybarPerBlock; startBlock = _startBlock; poolInfo.push( PoolInfo({ lpToken: _cybar, allocPoint: 1000, lastRewardBlock: startBlock, accCybarPerShare: 0, withdrawFeePeriod: 0, withdrawFee: 0 }) ); totalAllocPoint = 1000; } /* * @notice Updates multiplier * @param multiplierNumber: New multiplier number */ function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } /* * @notice returns the number of pools */ function poolLength() external view returns (uint256) { return poolInfo.length; } /* * @notice Adds new LP to the pool. Can only be called by the owner. Do not add the same LP more than once. * @param _allocPoint: Allocation points for that LP pool * @param _lpToken: LP Token to be added * @param _withUpdate: Whether to update all pools */ function add( uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCybarPerShare: 0, withdrawFeePeriod: 0, withdrawFee: 0 }) ); updateStakingPool(); } /* * @notice Sets pool specific parameter * @param _pid: Pool Id of the pool to be updated * @param _allocPoint: Allocation points * @param _withdrawFee: Withdrawal fee for an early withdrawal * @param _withdrawFeePeriod: Time frame in which a withdrawal fee is applied * @param _withUpdate: Whether to update all pools */ function set( uint256 _pid, uint256 _allocPoint, uint256 _withdrawFee, uint256 _withdrawFeePeriod, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } require(_withdrawFee <= MAX_WITHDRAW_FEE, "Withdrawal fee is too large"); require(_withdrawFeePeriod <= MAX_WITHDRAW_FEE_PERIOD, "Withdrawal fee time period is too large"); uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].withdrawFeePeriod = _withdrawFeePeriod; poolInfo[_pid].withdrawFee = _withdrawFee; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add( _allocPoint ); updateStakingPool(); } } /* * @notice Sets allocations points * @param _pid: Pool Id * @param _allocPoint: New allocation points for that pool * @param _withUpdate: Whether to update all pools before setting of allocation points */ function setAllocPoint( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate){ massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } /* * @notice Set time related withdrawal fees * @param _pid: Pool Id * @param _withdrawFee: Withdrawal fee for premature withdrawal * @param _withdrawFeePeriod: Withdrawal fee period */ function setWithdrawal( uint256 _pid, uint256 _withdrawFee, uint256 _withdrawFeePeriod ) public onlyOwner { require(_withdrawFee <= MAX_WITHDRAW_FEE, "Withdrawal fee is too large"); require(_withdrawFeePeriod <= MAX_WITHDRAW_FEE_PERIOD, "Withdrawal fee time period is too large"); poolInfo[_pid].withdrawFee = _withdrawFee; poolInfo[_pid].withdrawFeePeriod = _withdrawFeePeriod; } /* * @notice Updates the allocation points of the staking pool by setting it to a third of all allocation pools in the farms. */ function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add( points ); poolInfo[0].allocPoint = points; } } /* * @notice Sets a new migrator * @dev Can only be called by the owner * @param _migrator: New migrator */ function setMigrator(IMigratorBarkeeper _migrator) public onlyOwner { migrator = _migrator; } /* * @notice Migrates LP token to another LP contract. * @dev Can be called by anyone. Is this intended? * @param _pid: Pool Id of the pool to be migrated */ function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IBEP20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IBEP20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } /* * @notice Returns the multiplier between the _from and _to block * @param _from: Reference start block * @param _to: Reference end block */ function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } /* * @notice Returns the pending Cybar of a user for a pool * @param _pid: Pool Id of the pool * @param _user: User address */ function pendingCybar(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCybarPerShare = pool.accCybarPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cybarReward = multiplier.mul(cybarPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accCybarPerShare = accCybarPerShare.add( cybarReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accCybarPerShare).div(1e12).sub(user.rewardDebt); } /* * @notice Loops through all pools and updates each */ function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } /* * @notice Updates reward variables of a pool given its pool Id * @param _pid: Pool Id of the pool to be updated */ function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cybarReward = multiplier.mul(cybarPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); cybar.mint(devaddr, cybarReward.div(10)); cybar.mint(address(shot), cybarReward); pool.accCybarPerShare = pool.accCybarPerShare.add( cybarReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } /* * @notice Deposit LP tokens to MasterBarkeeper for Cybar allocation * @param _pid: Pool Id * @param _amount: Amount of LP token */ function deposit(uint256 _pid, uint256 _amount) public { require(_pid != 0, "deposit Cybar by staking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCybarPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeCybarTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCybarPerShare).div(1e12); user.lastDepositTime = block.timestamp; emit Deposit(msg.sender, _pid, _amount); } /* * @notice Withdraw from LP pool * @param _pid: Pool Id * @param _amount: Amount of LP tokens to withdraw */ function withdraw(uint256 _pid, uint256 _amount) public { require(_pid != 0, "Withdraw Cybar by unstaking"); require(_amount > 0, "Nothing to withdraw"); 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.accCybarPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeCybarTransfer(msg.sender, pending); } uint256 currentAmount = _amount; user.amount = user.amount.sub(_amount); if(block.timestamp < user.lastDepositTime + pool.withdrawFeePeriod){ uint256 withdrawFee = currentAmount.mul(pool.withdrawFee).div(10000); pool.lpToken.safeTransfer(treasury, withdrawFee); currentAmount = currentAmount.sub(withdrawFee); } pool.lpToken.safeTransfer(address(msg.sender), currentAmount); user.rewardDebt = user.amount.mul(pool.accCybarPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } /* * @notice Stake Cybar tokens to MasterBarkeeper * @param _amount: Amount of Cybar to be staked */ function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCybarPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeCybarTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCybarPerShare).div(1e12); shot.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } /* * @notice Withdraw Cybar token from staking * @param _amount: Amount to be withdrawn from staking */ function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "Withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accCybarPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeCybarTransfer(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.accCybarPerShare).div(1e12); shot.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } /* * @notice Withdraw from pool in case of an emergency. All rewards will be forfeited. * @param _pid: Pool Id */ function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } /* * @notice Safe Cybar transfer function. * @param _to: Address the Cybar is sent to * @param _amount: Amount to be transfered */ function safeCybarTransfer(address _to, uint256 _amount) internal { shot.safeCybarTransfer(_to, _amount); } /* * @notice Update developer address * @dev Can only be called by the current developer * @param _devaddr: New developer address */ function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Deposit LP tokens to MasterBarkeeper for Cybar allocation _pid: Pool Id _amount: Amount of LP token/
function deposit(uint256 _pid, uint256 _amount) public { require(_pid != 0, "deposit Cybar by staking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCybarPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeCybarTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCybarPerShare).div(1e12); user.lastDepositTime = block.timestamp; emit Deposit(msg.sender, _pid, _amount); }
12,965,168
./full_match/5/0xD7698187483Bea1AA1707e3d71e4554C920Eda89/sources/ERC4907.sol
verify that it is a standard erc4907 interface andsupport interfaceinterfaceId knows if our nft is erc4907 See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return interfaceId == type(IERC4907).interfaceId || super.supportsInterface(interfaceId); }
1,868,559
/** *Submitted for verification at Etherscan.io on 2022-03-13 */ // File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.4; interface IRegistry { function inRegistry(address _pool) external view returns(bool); function entries(uint256 _index) external view returns(address); function addBasket(address _basket) external; function removeBasket(uint256 _index) external; function removeBasketByAddress(address _address) external; } pragma solidity 0.6.4; contract BasketRegistry is IRegistry, Ownable { mapping(address => bool) public override inRegistry; address[] public override entries; function addBasket(address _basket) external override onlyOwner { require(!inRegistry[_basket], "Basket is already in Registry"); entries.push(_basket); inRegistry[_basket] = true; } function removeBasket(uint256 _index) public override onlyOwner { address registryAddress = entries[_index]; inRegistry[registryAddress] = false; // Move last to index location entries[_index] = entries[entries.length - 1]; // Pop last one off entries.pop(); } function removeBasketByAddress(address _address) external override onlyOwner { // Search for pool and remove it if found. Otherwise do nothing for(uint256 i = 0; i < entries.length; i ++) { if(_address == entries[i]) { removeBasket(i); break; } } } }
Search for pool and remove it if found. Otherwise do nothing
function removeBasketByAddress(address _address) external override onlyOwner { for(uint256 i = 0; i < entries.length; i ++) { if(_address == entries[i]) { removeBasket(i); break; } } }
10,983,190
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Ownable.sol'; import './ReentrancyGuard.sol'; import './SafeMath.sol'; import './SafeERC20.sol'; import './IERC20.sol'; contract SyrupPool is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The address of the smart chef factory address public POOL_FACTORY; // Whether a limit is set for users bool public hasUserLimit; // Whether it is initialized bool public isInitialized; // Accrued token per share uint256 public accTokenPerShare; // The block number when CAKE mining ends. uint256 public bonusEndBlock; // The block number when CAKE mining starts. uint256 public startBlock; // The block number of the last pool update uint256 public lastRewardBlock; uint256 public totalStaked; // The pool limit (0 if none) uint256 public poolLimitPerUser; // CAKE tokens created per block. uint256 public rewardPerBlock; // The precision factor uint256 public PRECISION_FACTOR; // The reward token IERC20 public rewardToken; // The staked token IERC20 public stakedToken; // Info of each user that stakes tokens (stakedToken) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // How many staked tokens the user has provided uint256 rewardDebt; // Reward debt } event AdminTokenRecovery(address tokenRecovered, uint256 amount); event Deposit(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock); event NewRewardPerBlock(uint256 rewardPerBlock); event NewPoolLimit(uint256 poolLimitPerUser); event RewardsStop(uint256 blockNumber); event RewardPaid(address indexed user, uint256 reward); event Withdraw(address indexed user, uint256 amount); constructor() { POOL_FACTORY = _msgSender(); } function initialize( IERC20 _stakedToken, IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, address _admin) external onlyOwner { require(!isInitialized, "Already initialized"); require(_msgSender() == POOL_FACTORY, "Not Pool factory"); uint256 decimalsRewardToken = uint256(_rewardToken.decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); // Make this contract initialized isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; if (_poolLimitPerUser > 0) { hasUserLimit = true; poolLimitPerUser = _poolLimitPerUser; } // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken))); // Transfer ownership to the admin address who becomes owner of the contract transferOwnership(_admin); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(stakedToken), "Cannot be staked token"); require(_tokenAddress != address(rewardToken), "Cannot be reward token"); IERC20(_tokenAddress).safeTransfer(address(_msgSender()), _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /* * @notice Withdraw staked tokens without caring about rewards rewards * @dev Needs to be for emergency. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[_msgSender()]; uint256 amountToTransfer = user.amount; user.amount = 0; user.rewardDebt = 0; if (amountToTransfer > 0) { stakedToken.safeTransfer(address(_msgSender()), amountToTransfer); totalStaked = totalStaked.sub(amountToTransfer); } emit EmergencyWithdraw(_msgSender(), user.amount); } /* * @notice Stop rewards * @dev Only callable by owner. Needs to be for emergency. */ function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { rewardToken.safeTransfer(address(_msgSender()), _amount); } /* * @notice Stop rewards * @dev Only callable by owner */ function stopReward() external onlyOwner { bonusEndBlock = block.number; } /* * @notice Update pool limit per user * @dev Only callable by owner. * @param _hasUserLimit: whether the limit remains forced * @param _poolLimitPerUser: new pool limit per user */ function updatePoolLimitPerUser(bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner { if (_hasUserLimit) { require(_poolLimitPerUser > poolLimitPerUser, "New limit must be higher"); poolLimitPerUser = _poolLimitPerUser; } else { hasUserLimit = _hasUserLimit; poolLimitPerUser = 0; } emit NewPoolLimit(poolLimitPerUser); } /* * @notice Update reward per block * @dev Only callable by owner. * @param _rewardPerBlock: the reward per block */ function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { require(block.number < startBlock || startBlock == 0, "Pool has started"); rewardPerBlock = _rewardPerBlock; emit NewRewardPerBlock(_rewardPerBlock); } /** * @notice It allows the admin to update start and end blocks * @dev This function is only callable by owner. * @param _startBlock: the new start block * @param _bonusEndBlock: the new end block */ function updateStartAndEndBlocks(uint256 _startBlock, uint256 _bonusEndBlock) external onlyOwner { require(block.number < startBlock || startBlock == 0, "Pool has started"); require(_startBlock < _bonusEndBlock, "New startBlock must be lower than new endBlock"); require(block.number < _startBlock, "New startBlock must be higher than current block"); startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock); } /* * @notice Deposit staked tokens and collect reward tokens (if any) * @param _amount: amount to withdraw (in rewardToken) */ function deposit(uint256 _amount) external nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; if (hasUserLimit) { require(_amount.add(user.amount) <= poolLimitPerUser, "User amount above limit"); } _updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); } } if (_amount > 0) { user.amount = user.amount.add(_amount); totalStaked = totalStaked.add(_amount); stakedToken.safeTransferFrom(address(_msgSender()), address(this), _amount); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); emit Deposit(_msgSender(), _amount); } /* * @notice Withdraw staked tokens and collect reward tokens * @param _amount: amount to withdraw (in rewardToken) */ function withdraw(uint256 _amount) external nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; require(user.amount >= _amount, "Amount to withdraw too high"); _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (_amount > 0) { user.amount = user.amount.sub(_amount); totalStaked = totalStaked.sub(_amount); stakedToken.safeTransfer(address(_msgSender()), _amount); emit Withdraw(_msgSender(), _amount); } if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); emit RewardPaid(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); } function getReward() public nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); emit RewardPaid(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); } /* * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(address _user) external view returns (uint256) { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_user]; uint256 stakedTokenSupply = totalStaked; if (block.number > lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } /* * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } uint256 stakedTokenSupply = totalStaked; if (stakedTokenSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(rewardPerBlock); accTokenPerShare = accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); lastRewardBlock = block.number; } function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from); } if (_from >= bonusEndBlock) { return 0; } return bonusEndBlock.sub(_from); } }
View function to see pending reward on frontend. _user: user address return Pending reward for a given user/
function pendingReward(address _user) external view returns (uint256) { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_user]; uint256 stakedTokenSupply = totalStaked; if (block.number > lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); }
12,614,809
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./zeppelin/token/ERC20/ERC20BurnableUpgradeable.sol"; import "./zeppelin/token/ERC20/ERC20PausableUpgradeable.sol"; import "./zeppelin/token/ERC20/ERC20Upgradeable.sol"; import "./zeppelin/proxy/Initializable.sol"; import "./zeppelin/access/AccessControlUpgradeable.sol"; import "./zeppelin/utils/ContextUpgradeable.sol"; import "./zeppelin/math/SafeMathUpgradeable.sol"; contract ERC20Decrypto is Initializable, ContextUpgradeable, AccessControlUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable { using SafeMathUpgradeable for uint256; /** * @dev Base fee to apply to a transfer */ uint256 public basisPointsRate; /** * @dev Minter rol */ bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /** * @dev Pauser rol */ bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Account owner of feed */ address public addressFee; /** * @dev Multiplier for Split */ uint256 public splitMultiplier; /** * @dev Divider for Split */ uint256 public splitDivider; /** * @dev Emitted when `newFeeds` are sets * */ event FeesChange(uint256 oldFeeBasisPoints, uint256 feeBasisPoints); /** * @dev Emitted when owner fee set * */ event AddressFeeChange(address oldOwnerFee, address newOwnerFee); /** * @dev Emitted when apply split * */ event SplitChange( uint256 oldSplitMultiplier, uint256 newSplitMultiplier, uint256 oldSplitDivider, uint256 newSplitDivider ); bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; /** * @dev initialize contract -- proxy */ function initialize( string memory name, string memory symbol, address owner ) public initializer { __ERC20Decrypto_init(name, symbol, owner); uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this) ) ); } /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. */ function __ERC20Decrypto_init( string memory name, string memory symbol, address owner ) internal initializer { require(owner != address(0), "ERC20: owner coudl not be 0"); addressFee = owner; splitMultiplier = 1; splitDivider = 1; basisPointsRate = 0; //ini context __Context_init_unchained(); //ini access control __AccessControl_init_unchained(); //ini basic info erc20 -- 18 decimals __ERC20_init_unchained(name, symbol); //ini burnegable (empty) //TODO see if remove __ERC20Burnable_init_unchained(); //ini pausable -- set pause to false __Pausable_init_unchained(); //ini erc20Pausable (empty) //TODO see if remove __ERC20Pausable_init_unchained(); //set necessary rols __ERC20Decrypto_init_unchained(owner); } /** * @dev Set admin, minter, fee and pauser rols by sender * Emit RoleAdminChanged and RoleGranted (pauser and minter) */ function __ERC20Decrypto_init_unchained(address owner) internal initializer { //set admin rol -- Emit RoleAdminChanged _setupRole(DEFAULT_ADMIN_ROLE, owner); //set minter, pauser and fee rol -- Emit RoleGranted _setupRole(MINTER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); } /** * @dev Creates `amount` new tokens for `to`. * * Requirements: * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require( hasRole(MINTER_ROLE, _msgSender()), "ERC20: must have minter role to mint" ); uint256 unformattedValue = _unformattedValue(amount); _mint(to, unformattedValue); } /** * @dev Creates `amounts` new tokens for `accounts`. * * Requirements: * - the caller must have the `MINTER_ROLE`. * - the accounts addresses must not be zero. */ function mintBatch(address[] memory accounts, uint256[] memory amounts) public virtual { require( hasRole(MINTER_ROLE, _msgSender()), "ERC20: must have minter role to mint" ); require( accounts.length == amounts.length, "ERC20: accounts and amounts length mismatch" ); for (uint256 i = 0; i < accounts.length; ++i) { uint256 unformattedValue = _unformattedValue(amounts[i]); _mint(accounts[i], unformattedValue); } } /** * @dev Pauses all token transfers. * * Requirements: * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20: must have pauser role to pause" ); _pause(); } /** * @dev Unpauses all token transfers. * * Requirements: * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20: must have pauser role to unpause" ); _unpause(); } /** * @dev Set basic and max fee * * Emits a {FeesChange} event. * Requirements: * - `recipient` cannot be the zero address. * - the caller newBasisPoints not been mayor than 1000 (10%). * - the caller must have the `ADMIN_ROLE`. */ function setFee(uint256 newBasisPoints) public virtual { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20: must have admin role to setFees" ); // Ensure transparency by hardcoding limit beyond which fees can never be added require( newBasisPoints < 1000, "ERC20: newBasisPoints must not been mayor than 1000" ); //set old basisPointRate uint256 oldBasisPointRate = basisPointsRate; //set new values basisPointsRate = newBasisPoints; //emit event emit FeesChange(oldBasisPointRate, basisPointsRate); } /** * @dev Set owner fee * * Emits a {AddressFeeChange} event. * Requirements: * - `newAddressFee` cannot be the zero address. * - the caller must have the `ADMIN_ROLE`. */ function setAddressFee(address newAddressFee) public virtual { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20: must have admin role to setAddressFee" ); // Ensure transparency by hardcoding limit beyond which fees can never be added require( newAddressFee != address(0), "ERC20: newAddressFee could not be 0" ); //set old owner address oldOwner = addressFee; //set new owner addressFee = newAddressFee; //emit event emit AddressFeeChange(oldOwner, addressFee); } /** * @dev Set split * * Emits a {SplitChange} event. * Requirements: * - the caller must have the `ADMIN_ROLE`. */ function split() public virtual { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20: must have admin role to split" ); _setSplit(splitMultiplier.mul(2), splitDivider); } /** * @dev Set halve split * * Emits a {SplitChange} event. * Requirements: * - the caller must have the `ADMIN_ROLE`. */ function reverseSplit() public virtual { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20: must have admin role to reverseSplit" ); _setSplit(splitMultiplier, splitDivider.mul(2)); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _formattedValue(_balances[account]); } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _formattedValue(_allowances[owner][spender]); } /** * @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 override returns (bool) { uint256 formattedValue = _formattedValue(_allowances[_msgSender()][spender]); _approve(_msgSender(), spender, formattedValue.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 override returns (bool) { uint256 formattedValue = _formattedValue(_allowances[_msgSender()][spender]); _approve( _msgSender(), spender, formattedValue.sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _formattedValue(_totalSupply); } /** * @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 formattedAmount = _formattedValue( _allowances[sender][_msgSender()].sub( _unformattedValue(amount), "ERC20: transfer amount exceeds allowance" ) ); _approve(sender, _msgSender(), formattedAmount); return true; } /** * @dev Moves `amount` tokens from `sender` to `recipients` using the * allowance mechanism. `amounts` are then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * */ function transferBatch( address[] memory recipients, uint256[] memory amounts ) public virtual returns (bool) { _transferBatch(_msgSender(), recipients, amounts); return true; } /** * @dev Moves `amounts` tokens from `sender` to `recipients` using the * allowance mechanism. `amounts` are then deducted from the caller's * allowance. * Emits an {Approval} event indicating the updated allowance. * * 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 transferFromBatch( address sender, address[] memory recipients, uint256[] memory amounts ) public virtual returns (bool) { uint256 amountsTotal = _transferBatch(sender, recipients, amounts); uint256 formattedAmount = _formattedValue( _allowances[sender][_msgSender()].sub( _unformattedValue(amountsTotal), "ERC20: transfer amount exceeds allowance" ) ); _approve(sender, _msgSender(), formattedAmount); return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual override { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20: must have admin role to burn" ); _burn(_msgSender(), amount); } /** * @dev Destroys `amounts` tokens from `accounts`, deducting from the caller's * allowance. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFromBatch(address[] memory accounts, uint256[] memory amounts) public virtual { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20: must have admin role to burn" ); require( accounts.length == amounts.length, "ERC20: accounts and amounts length mismatch" ); for (uint256 i = 0; i < accounts.length; ++i) { uint256 decreasedAllowance = allowance(accounts[i], _msgSender()).sub( amounts[i], "ERC20: burn amount exceeds allowance" ); _approve(accounts[i], _msgSender(), decreasedAllowance); _burn(accounts[i], amounts[i]); } } /** * @dev Allows for approvals to be made via secp256k1 signatures * * Requirements: * * - the spender must have signatures for owner and valid deadline. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "ERC20: expired"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "ERC20: invalid signature" ); _approve(owner, spender, value); } /** * @dev Get the underlying value of the split * */ function _unformattedValue(uint256 value) internal view returns (uint256) { return value.mul(splitDivider).div(splitMultiplier); } /** * @dev Get the formatted value of the split * */ function _formattedValue(uint256 value) internal view returns (uint256) { return value.mul(splitMultiplier).div(splitDivider); } /** * @dev Set split divider and multiplier * * Emits a {SplitChange} event. * Requirements: * - `newSplitMultiplier` cannot be the zero. * - `newSplitDivider` cannot be the zero. * - the caller must have the `ADMIN_ROLE`. */ function _setSplit(uint256 newSplitMultiplier, uint256 newSplitDivider) public virtual { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20: must have admin role to _setSplit" ); // Ensure transparency by hardcoding limit beyond which fees can never be added require( newSplitMultiplier != 0, "ERC20: newSplitMultiplier could not be 0" ); require(newSplitDivider != 0, "ERC20: newSplitDivider could not be 0"); //set old owner uint256 oldMultiplier = splitMultiplier; uint256 oldDivider = splitDivider; //set new owner splitMultiplier = newSplitMultiplier; splitDivider = newSplitDivider; //emit event emit SplitChange( oldMultiplier, newSplitMultiplier, oldDivider, newSplitDivider ); } /** * @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 override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); //calculate unerlying amount uint256 unformattedValue = _unformattedValue(amount); //set fee uint256 fee = (unformattedValue.mul(basisPointsRate)).div(10000); //value - fee uint256 sendAmount = unformattedValue.sub(fee); //sub amount in sender balance _balances[sender] = _balances[sender].sub( unformattedValue, "ERC20: transfer amount exceeds balance" ); //add sendAmount in recipent balance _balances[recipient] = _balances[recipient].add(sendAmount); //validate fee if (fee > 0) { _balances[addressFee] = _balances[addressFee].add(fee); emit Transfer(sender, addressFee, fee); } emit Transfer(sender, recipient, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, _unformattedValue(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 override { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = _unformattedValue(amount); emit Approval(owner, spender, 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 override { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 unformattedAmount = _unformattedValue(amount); _balances[account] = _balances[account].sub( unformattedAmount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(unformattedAmount); emit Transfer(account, address(0), amount); } function _transferBatch( address sender, address[] memory recipients, uint256[] memory amounts ) internal virtual returns (uint256) { require(sender != address(0), "ERC20: transfer from the zero address"); require( recipients.length == amounts.length, "ERC20: accounts and amounts length mismatch" ); uint256 totalAmount; for (uint256 i = 0; i < recipients.length; ++i) { address recipient = recipients[i]; require( recipient != address(0), "ERC20: transfer to the zero address" ); _beforeTokenTransfer(address(0), recipient, amounts[i]); uint256 unformattedAmount = _unformattedValue(amounts[i]); //set fee uint256 fee = (unformattedAmount.mul(basisPointsRate)).div(10000); //calculate unerlying amount uint256 unformattedValue = _unformattedValue(amounts[i]); uint256 sendAmount = unformattedValue.sub(fee); //sub amount in sender balance _balances[sender] = _balances[sender].sub( unformattedValue, "ERC20: transfer amount exceeds balance" ); //add sendAmount in recipent balance _balances[recipient] = _balances[recipient].add(sendAmount); //validate fee if (fee > 0) { _balances[addressFee] = _balances[addressFee].add(fee); emit Transfer(sender, addressFee, fee); } emit Transfer(sender, recipients[i], amounts[i]); totalAmount = totalAmount + amounts[i]; } return totalAmount; } }
See {IERC20-balanceOf}./
function balanceOf(address account) public view virtual override returns (uint256) { return _formattedValue(_balances[account]); }
13,016,106
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; // import "@openzeppelin/contracts-upgradeable/math/SignedSafeMathUpgradeable.sol"; // import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/IStakingPoolsVesting.sol"; import "./interfaces/IUniswapV2RouterMinimal.sol"; import "./interfaces/IERC20Minimal.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; // import "hardhat/console.sol"; contract TokenVestingV3 is OwnableUpgradeable { using SafeMathUpgradeable for uint256; struct Schedule { // the total amount that has been vested uint256 totalAmount; // the total amount that has been claimed uint256 claimedAmount; uint256 startTime; uint256 cliffTime; uint256 endTime; uint256 cliffWeeks; // amount of vesting kko staked in the kko staking pool uint256 totalStakedKko; // the amount of eth lp tokens owned by the account uint256 kkoEthLpTokens; // tracks the amount of kko tokens that are in active LP uint256 kkoInLp; } mapping (address => mapping(uint => Schedule)) public schedules; mapping (address => uint) public numberOfSchedules; modifier onlyConfigured() { require(configured, "Vesting: only configured"); _; } /// @dev total kko locked in the contract uint256 public valueLocked; IERC20Minimal private kko; IERC20Minimal private lpToken; IUniswapV2RouterMinimal private router; IStakingPoolsVesting private stakingPools; bool private configured; uint256 public kkoPoolsId; uint256 public kkoLpPoolsId; event Claim(uint amount, address claimer); mapping(address => bool) public blacklist; function initialize(address _kko, address _lpToken, address _router) public initializer { OwnableUpgradeable.__Ownable_init(); kko = IERC20Minimal(_kko); lpToken = IERC20Minimal(_lpToken); router = IUniswapV2RouterMinimal(_router); // approve the router to spend kko require(kko.approve(_router, 2**256-1)); require(lpToken.approve(_router, 2**256-1)); } fallback() external payable {} function setStakingPools(address _contract, uint256 _kkoPoolsId, uint256 _kkoLpPoolsId) external onlyOwner { require(configured == false, "must not be configured"); stakingPools = IStakingPoolsVesting(_contract); kkoPoolsId = _kkoPoolsId; kkoLpPoolsId = _kkoLpPoolsId; configured = true; // todo(bonedaddy): is this optimal? not sure // approve max uint256 value require(kko.approve(_contract, 2**256-1)); require(lpToken.approve(_contract, 2**256-1)); } /** * @notice Sets up a vesting schedule for a set user. * @notice at the moment this only supports staking of the kko staking * @dev adds a new Schedule to the schedules mapping. * @param account the account that a vesting schedule is being set up for. Will be able to claim tokens after * the cliff period. * @param amount the amount of tokens being vested for the user. * @param cliffWeeks the number of weeks that the cliff will be present at. * @param vestingWeeks the number of weeks the tokens will vest over (linearly) */ function setVestingSchedule( address account, uint256 amount, uint256 cliffWeeks, uint256 vestingWeeks, bool danger ) public onlyOwner onlyConfigured { if (danger == false) { require( kko.balanceOf(address(this)).sub(valueLocked) >= amount, "Vesting: amount > tokens leftover" ); } require( vestingWeeks >= cliffWeeks, "Vesting: cliff after vesting period" ); uint256 currentNumSchedules = numberOfSchedules[account]; schedules[account][currentNumSchedules] = Schedule( amount, 0, block.timestamp, block.timestamp.add(cliffWeeks * 1 weeks), block.timestamp.add(vestingWeeks * 1 weeks), cliffWeeks, 0, // amount staked in kko pool 0, // amount of lp tokens 0 // amount of kko lp'd ); numberOfSchedules[account] = currentNumSchedules + 1; valueLocked = valueLocked.add(amount); } /** * @notice Updates the vesting schedule of a user * @param account the account that a vesting schedule is being updated for. * @param scheduleNumber schedule to update. * @param cliffWeeks the number of weeks that the cliff will be present at. * @param vestingWeeks the number of weeks the tokens will vest over (linearly) */ function updateVestingSchedule( address account, uint256 scheduleNumber, uint256 cliffWeeks, uint256 vestingWeeks ) public onlyOwner onlyConfigured { Schedule storage schedule = schedules[account][scheduleNumber]; schedule.cliffTime = cliffWeeks * 1 weeks; schedule.endTime = vestingWeeks * 1 weeks; schedule.cliffWeeks = cliffWeeks; } /// @dev allows staking vesting KKO tokens in the kko single staking pool function stakeSingle(uint256 scheduleNumber, uint256 _amountToStake) public onlyConfigured { Schedule storage schedule = schedules[msg.sender][scheduleNumber]; require( // ensure that the total amount of staked kko including the amount we are staking and lp'ing // is less than the total available amount schedule.totalStakedKko.add(_amountToStake).add(schedule.kkoInLp) <= schedule.totalAmount.sub(schedule.claimedAmount), "Vesting: total staked must be less than or equal to available amount (totalAmount - claimedAmount)" ); schedule.totalStakedKko = schedule.totalStakedKko.add(_amountToStake); require( stakingPools.depositVesting( msg.sender, kkoPoolsId, _amountToStake ), "Vesting: depositVesting failed" ); } function stakePool2( uint256 scheduleNumber, uint256 _amountKko, uint256 _amountEther, uint256 _amountTokenMin, uint256 _amountETHMin, uint _deadline ) public payable onlyConfigured { Schedule storage schedule = schedules[msg.sender][scheduleNumber]; require( schedule.totalStakedKko.add(_amountKko).add(schedule.kkoInLp) <= schedule.totalAmount.sub(schedule.claimedAmount), "Vesting: total staked must be less than or equal to available amount (totalAmount - claimedAmount)" ); require(msg.value == _amountEther, "Vesting: sending not supplying enough ether"); schedule.kkoInLp = schedule.kkoInLp.add(_amountKko); // amountToken = The amount of token sent to the pool. // amountETH = The amount of ETH converted to WETH and sent to the pool. // liquidity = The amount of liquidity tokens minted. (uint amountToken, uint amountETH, uint liquidity) = router.addLiquidityETH{value: msg.value}( address(kko), _amountKko, // the amount of token to add as liquidity if the WETH/token price is <= msg.value/amountTokenDesired (token depreciates). _amountTokenMin, // Bounds the extent to which the WETH/token price can go up before the transaction reverts. Must be <= amountTokenDesired. _amountETHMin, // Bounds the extent to which the token/WETH price can go up before the transaction reverts. Must be <= msg.value. address(this), _deadline ); // if we didnt add the fully amount requested, reduce the amount staked if (amountToken < _amountKko) { schedule.kkoInLp = schedule.kkoInLp.sub(amountToken); } schedule.kkoEthLpTokens = schedule.kkoEthLpTokens.add(liquidity); require( stakingPools.depositVesting( msg.sender, kkoLpPoolsId, liquidity ), "Vesting: depositVesting failed" ); if (amountETH < _amountEther) { msg.sender.transfer(_amountEther.sub(amountETH)); } } function exitStakePool2( uint256 scheduleNumber, uint256 _amountLpTokens, uint256 _amountTokenMin, uint256 _amountETHMin, uint _deadline ) public payable onlyConfigured { Schedule storage schedule = schedules[msg.sender][scheduleNumber]; require( _amountLpTokens <= schedule.kkoEthLpTokens, "Vesting: insufficient lp token balance" ); (bool ok,) = stakingPools.withdrawOrClaimOrExitVesting( msg.sender, kkoLpPoolsId, 0, true, true ); require(ok, "Vesting exitStakePool2 failed"); // amountToken is the amount of tokens received // amountETH is the maount of ETH received (uint256 amountToken, uint256 amountETH) = router.removeLiquidityETH( address(kko), schedule.kkoEthLpTokens, _amountTokenMin, _amountETHMin, address(this), _deadline ); bool claimBlacklisted = blacklist[msg.sender]; // due to lp fees they may be withdrawing more kko than they originally deposited // in this case we will send the difference directly to their wallet if (amountToken > schedule.kkoInLp) { uint256 difference = amountToken.sub(schedule.kkoInLp); schedule.kkoInLp = 0; if (claimBlacklisted == false) { require(kko.transfer(msg.sender, difference)); } } else { schedule.kkoInLp = schedule.kkoInLp.sub(amountToken); } msg.sender.transfer(amountETH); } /// @dev used to exit from the single staking pool /// @dev this does not transfer the unstaked tokens to the msg.sender, but rather this contract function exitStakeSingle(uint256 scheduleNumber) public onlyConfigured { Schedule storage schedule = schedules[msg.sender][scheduleNumber]; (bool ok, uint256 reward) = stakingPools.withdrawOrClaimOrExitVesting( msg.sender, kkoPoolsId, 0, // we are exiting the pool so withdrawing all kko true, true ); require(ok, "Vesting: exitStakeSingle failed"); bool claimBlacklisted = blacklist[msg.sender]; if (claimBlacklisted == false) { require(kko.transfer(msg.sender, reward)); } uint256 totalStaked = schedule.totalStakedKko; // we're exiting this pool so set to 0 schedule.totalStakedKko = schedule.totalStakedKko.sub(totalStaked); } /// @dev allows claiming staking rewards without exiting the staking pool function claimStakingRewards(uint256 _poolId) public onlyConfigured { require(_poolId == kkoPoolsId || _poolId == kkoLpPoolsId); bool claimBlacklisted = blacklist[msg.sender]; require(claimBlacklisted == false, "Claim blacklisted"); (bool ok, uint256 reward) = stakingPools.withdrawOrClaimOrExitVesting( msg.sender, _poolId, 0, // we are solely claiming rewards false, false ); require(ok); require(kko.transfer(msg.sender, reward)); } /** * @notice allows users to claim vested tokens if the cliff time has passed. * @notice needs to handle claiming from kko and kkoeth-lp staking */ function claim(uint256 scheduleNumber) public onlyConfigured { Schedule storage schedule = schedules[msg.sender][scheduleNumber]; require( schedule.cliffTime <= block.timestamp, "Vesting: cliffTime not reached" ); require(schedule.totalAmount > 0, "Vesting: No claimable tokens"); // Get the amount to be distributed uint amount = calcDistribution(schedule.totalAmount, block.timestamp, schedule.startTime, schedule.endTime); // Cap the amount at the total amount amount = amount > schedule.totalAmount ? schedule.totalAmount : amount; uint amountToTransfer = amount.sub(schedule.claimedAmount); // set the previous amount claimed uint prevClaimed = schedule.claimedAmount; schedule.claimedAmount = amount; // set new claimed amount based off the curve // if the amount that is unstaked is smaller than the amount being transffered // destake first require( // amountToTransfer < (schedule.claimedAmount - (schedule.totalStakedKkoPool2 + schedule.totalStakedKkoSingle)), amountToTransfer <= (schedule.totalAmount - prevClaimed), "Vesting: amount unstaked too small for claim please destake" ); require(kko.transfer(msg.sender, amountToTransfer)); // todo(bonedaddy): this might need some updating // as it doesnt factor in staking rewards emit Claim(amount, msg.sender); } /** * @notice returns the total amount and total claimed amount of a users vesting schedule. * @param account the user to retrieve the vesting schedule for. */ function getVesting(address account, uint256 scheduleId) public view returns (uint256, uint256, uint256, uint256) { Schedule memory schedule = schedules[account][scheduleId]; return (schedule.totalAmount, schedule.claimedAmount, schedule.kkoInLp, schedule.totalStakedKko); } /** * @notice calculates the amount of tokens to distribute to an account at any instance in time, based off some * total claimable amount. * @param amount the total outstanding amount to be claimed for this vesting schedule. * @param currentTime the current timestamp. * @param startTime the timestamp this vesting schedule started. * @param endTime the timestamp this vesting schedule ends. */ function calcDistribution(uint amount, uint currentTime, uint startTime, uint endTime) public pure returns(uint256) { return amount.mul(currentTime.sub(startTime)).div(endTime.sub(startTime)); } /** * @notice this doesn't handle withdrawing from staking pools * @notice Withdraws KKO tokens from the contract. * @dev blocks withdrawing locked tokens. * @notice if danger is set to true, then all amount checking is witdhrawn * @notice this could potentially have bad implications so use with caution */ function withdraw(uint amount, bool danger) public onlyOwner { if (danger == false) { require( kko.balanceOf(address(this)).sub(valueLocked) >= amount, "Vesting: amount > tokens leftover" ); } require(kko.transfer(msg.sender, amount)); } /// used to update the amount of tokens an account is vesting function updateVestingAmount( address account, uint256 amount, uint256 scheduleNumber ) public onlyOwner onlyConfigured { Schedule storage schedule = schedules[account][scheduleNumber]; uint256 prevAmountTotal = schedule.totalAmount; schedule.totalAmount = amount; // we are decreasing the amount they are vesting uint256 difference = prevAmountTotal.sub(amount); // subtract the difference from value locked valueLocked = valueLocked.sub(difference); // transfer the difference back to the caller require(kko.transfer(msg.sender, difference)); } function toggleBlacklist( address account ) public onlyOwner onlyConfigured { blacklist[account] = !blacklist[account]; } } // 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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } pragma solidity ^0.7.0; /// @title interfaces used by the vesting contract interface IStakingPoolsVesting { function depositVesting(address _account, uint256 _poolId, uint256 _depositAmount) external returns (bool); function withdrawOrClaimOrExitVesting(address _account, uint256 _poolId, uint256 _withdrawAmount, bool _doWithdraw, bool _doExit) external returns (bool, uint256); } pragma solidity ^0.7.0; interface IUniswapV2RouterMinimal { function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); } pragma solidity ^0.7.0; interface IERC20Minimal { function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
used to update the amount of tokens an account is vesting we are decreasing the amount they are vesting subtract the difference from value locked transfer the difference back to the caller
function updateVestingAmount( address account, uint256 amount, uint256 scheduleNumber ) public onlyOwner onlyConfigured { Schedule storage schedule = schedules[account][scheduleNumber]; uint256 prevAmountTotal = schedule.totalAmount; schedule.totalAmount = amount; uint256 difference = prevAmountTotal.sub(amount); valueLocked = valueLocked.sub(difference); require(kko.transfer(msg.sender, difference)); }
273,787
./full_match/11155111/0x1A1F1D20C404D9C2399a56166256d25fe3e2A93D/sources/contracts/SubscriptionsCollection.sol
Disables the sale of the collection./
function disableSale() external onlyMerchant() { onSale = false; }
3,804,113
pragma solidity 0.4.24; // ERC20 Token with ERC223 Token compatibility // SafeMath from OpenZeppelin Standard // Added burn functions from Ethereum Token // - https://theethereum.wiki/w/index.php/ERC20_Token_Standard // - https://github.com/Dexaran/ERC23-tokens/blob/Recommended/ERC223_Token.sol // - https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol // - https://www.ethereum.org/token (uncontrolled, non-standard) // ERC223 interface ContractReceiver { function tokenFallback( address from, uint value, bytes data ) external; } // SafeMath contract SafeMath2 { function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract RUNEToken is SafeMath2 { // Rune Characteristics string public name = "Rune"; string public symbol = "RUNE"; uint256 public decimals = 18; uint256 public totalSupply = 1000000000 * (10 ** decimals); // Mapping mapping( address => uint256 ) balances_; mapping( address => mapping(address => uint256) ) allowances_; // Minting event function RUNEToken() public { balances_[msg.sender] = totalSupply; emit Transfer( address(0), msg.sender, totalSupply ); } function() public payable { revert(); } // does not accept money // ERC20 event Approval( address indexed owner, address indexed spender, uint value ); event Transfer( address indexed from, address indexed to, uint256 value ); // ERC20 function balanceOf( address owner ) public constant returns (uint) { return balances_[owner]; } // ERC20 function approve( address spender, uint256 value ) public returns (bool success) { allowances_[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } // recommended fix for known attack on any ERC20 function safeApprove( address _spender, uint256 _currentValue, uint256 _value ) public returns (bool success) { // If current allowance for _spender is equal to _currentValue, then // overwrite it with _value and return true, otherwise return false. if (allowances_[msg.sender][_spender] == _currentValue) return approve(_spender, _value); return false; } // ERC20 function allowance( address owner, address spender ) public constant returns (uint256 remaining) { return allowances_[owner][spender]; } // ERC20 function transfer(address to, uint256 value) public returns (bool success) { bytes memory empty; // null _transfer( msg.sender, to, value, empty ); return true; } // ERC20 function transferFrom( address from, address to, uint256 value ) public returns (bool success) { require( value <= allowances_[from][msg.sender] ); allowances_[from][msg.sender] -= value; bytes memory empty; _transfer( from, to, value, empty ); return true; } // ERC223 Transfer and invoke specified callback function transfer( address to, uint value, bytes data, string custom_fallback ) public returns (bool success) { _transfer( msg.sender, to, value, data ); if ( isContract(to) ) { ContractReceiver rx = ContractReceiver( to ); require( address(rx).call.value(0)(bytes4(keccak256(custom_fallback)), msg.sender, value, data) ); } return true; } // ERC223 Transfer to a contract or externally-owned account function transfer( address to, uint value, bytes data ) public returns (bool success) { if (isContract(to)) { return transferToContract( to, value, data ); } _transfer( msg.sender, to, value, data ); return true; } // ERC223 Transfer to contract and invoke tokenFallback() method function transferToContract( address to, uint value, bytes data ) private returns (bool success) { _transfer( msg.sender, to, value, data ); ContractReceiver rx = ContractReceiver(to); rx.tokenFallback( msg.sender, value, data ); return true; } // ERC223 fetch contract size (must be nonzero to be a contract) function isContract( address _addr ) private constant returns (bool) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } function _transfer( address from, address to, uint value, bytes data ) internal { require( to != 0x0 ); require( balances_[from] >= value ); require( balances_[to] + value > balances_[to] ); // catch overflow balances_[from] -= value; balances_[to] += value; //Transfer( from, to, value, data ); ERC223-compat version bytes memory empty; empty = data; emit Transfer( from, to, value ); // ERC20-compat version } // Ethereum Token event Burn( address indexed from, uint256 value ); // Ethereum Token function burn( uint256 value ) public returns (bool success) { require( balances_[msg.sender] >= value ); balances_[msg.sender] -= value; totalSupply -= value; emit Burn( msg.sender, value ); return true; } // Ethereum Token function burnFrom( address from, uint256 value ) public returns (bool success) { require( balances_[from] >= value ); require( value <= allowances_[from][msg.sender] ); balances_[from] -= value; allowances_[from][msg.sender] -= value; totalSupply -= value; emit Burn( from, value ); return true; } } /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } contract THORChain721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; bytes4 retval; bool reverts; constructor(bytes4 _retval, bool _reverts) public { retval = _retval; reverts = _reverts; } event Received( address _operator, address _from, uint256 _tokenId, bytes _data, uint256 _gas ); function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4) { require(!reverts); emit Received( _operator, _from, _tokenId, _data, gasleft() ); return retval; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _account address of the account to check * @return whether the target address is a contract */ function isContract(address _account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_account) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 _tokenId) internal view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = THORChain721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(_exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(_exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } contract THORChain721 is ERC721Token { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } constructor () public ERC721Token("testTC1", "testTC1") { owner = msg.sender; } // Revert any transaction to this contract. function() public payable { revert(); } function mint(address _to, uint256 _tokenId) public onlyOwner { super._mint(_to, _tokenId); } function burn(uint256 _tokenId) public onlyOwner { super._burn(ownerOf(_tokenId), _tokenId); } function setTokenURI(uint256 _tokenId, string _uri) public onlyOwner { super._setTokenURI(_tokenId, _uri); } function _removeTokenFrom(address _from, uint256 _tokenId) public { super.removeTokenFrom(_from, _tokenId); } } contract Whitelist { address public owner; mapping(address => bool) public whitelistAdmins; mapping(address => bool) public whitelist; constructor () public { owner = msg.sender; whitelistAdmins[owner] = true; } modifier onlyOwner () { require(msg.sender == owner, "Only owner"); _; } modifier onlyWhitelistAdmin () { require(whitelistAdmins[msg.sender], "Only whitelist admin"); _; } function isWhitelisted(address _addr) public view returns (bool) { return whitelist[_addr]; } function addWhitelistAdmin(address _admin) public onlyOwner { whitelistAdmins[_admin] = true; } function removeWhitelistAdmin(address _admin) public onlyOwner { require(_admin != owner, "Cannot remove contract owner"); whitelistAdmins[_admin] = false; } function whitelistAddress(address _user) public onlyWhitelistAdmin { whitelist[_user] = true; } function whitelistAddresses(address[] _users) public onlyWhitelistAdmin { for (uint256 i = 0; i < _users.length; i++) { whitelist[_users[i]] = true; } } function unWhitelistAddress(address _user) public onlyWhitelistAdmin { whitelist[_user] = false; } function unWhitelistAddresses(address[] _users) public onlyWhitelistAdmin { for (uint256 i = 0; i < _users.length; i++) { whitelist[_users[i]] = false; } } } contract Sale1 is Whitelist { using SafeMath for uint256; uint256 public maximumNonWhitelistAmount = 12500 * 50 ether; // in minimum units of rune // in minimum units of rune (1000 = 0.000000000000001000 RUNE per WEI) // note that this only works if the amount of rune per wei is more than 1 uint256 public runeToWeiRatio = 12500; bool public withdrawalsAllowed = false; bool public tokensWithdrawn = false; address public owner; address public proceedsAddress = 0xd46cac034f44ac93049f8f1109b6b74f79b3e5e6; RUNEToken public RuneToken = RUNEToken(0xdEE02D94be4929d26f67B64Ada7aCf1914007F10); Whitelist public WhitelistContract = Whitelist(0x395Eb47d46F7fFa7Dd4b27e1B64FC6F21d5CC4C7); THORChain721 public ERC721Token = THORChain721(0x953d066d809dc71b8809dafb8fb55b01bc23a6e0); uint256 public CollectibleIndex0 = 0; uint256 public CollectibleIndex1 = 1; uint256 public CollectibleIndex2 = 2; uint256 public CollectibleIndex3 = 3; uint256 public CollectibleIndex4 = 4; uint256 public CollectibleIndex5 = 5; uint public winAmount0 = 666.666666666666666667 ether; uint public winAmount1 = 1333.333333333333333333 ether; uint public winAmount2 = 2000.0 ether; uint public winAmount3 = 2666.666666666666666667 ether; uint public winAmount4 = 3333.333333333333333333 ether; uint public winAmount5 = 4000.0 ether; mapping (uint256 => address) public collectibleAllocation; mapping (address => uint256) public runeAllocation; uint256 public totalRunePurchased; uint256 public totalRuneWithdrawn; event TokenWon(uint256 tokenId, address winner); modifier onlyOwner () { require(owner == msg.sender, "Only the owner can use this function"); _; } constructor () public { owner = msg.sender; } function () public payable { require(!tokensWithdrawn, "Tokens withdrawn. No more purchases possible."); // Make sure we have enough tokens to sell uint runeRemaining = (RuneToken.balanceOf(this).add(totalRuneWithdrawn)).sub(totalRunePurchased); uint toForward = msg.value; uint weiToReturn = 0; uint purchaseAmount = msg.value * runeToWeiRatio; if(runeRemaining < purchaseAmount) { purchaseAmount = runeRemaining; uint price = purchaseAmount.div(runeToWeiRatio); weiToReturn = msg.value.sub(price); toForward = toForward.sub(weiToReturn); } // Assign NFTs uint ethBefore = totalRunePurchased.div(runeToWeiRatio); uint ethAfter = ethBefore.add(toForward); if(ethBefore <= winAmount0 && ethAfter > winAmount0) { collectibleAllocation[CollectibleIndex0] = msg.sender; emit TokenWon(CollectibleIndex0, msg.sender); } if(ethBefore < winAmount1 && ethAfter >= winAmount1) { collectibleAllocation[CollectibleIndex1] = msg.sender; emit TokenWon(CollectibleIndex1, msg.sender); } if(ethBefore < winAmount2 && ethAfter >= winAmount2) { collectibleAllocation[CollectibleIndex2] = msg.sender; emit TokenWon(CollectibleIndex2, msg.sender); } if(ethBefore < winAmount3 && ethAfter >= winAmount3) { collectibleAllocation[CollectibleIndex3] = msg.sender; emit TokenWon(CollectibleIndex3, msg.sender); } if(ethBefore < winAmount4 && ethAfter >= winAmount4) { collectibleAllocation[CollectibleIndex4] = msg.sender; emit TokenWon(CollectibleIndex4, msg.sender); } if(ethBefore < winAmount5 && ethAfter >= winAmount5) { collectibleAllocation[CollectibleIndex5] = msg.sender; emit TokenWon(CollectibleIndex5, msg.sender); } runeAllocation[msg.sender] = runeAllocation[msg.sender].add(purchaseAmount); totalRunePurchased = totalRunePurchased.add(purchaseAmount); // Withdraw ETH proceedsAddress.transfer(toForward); if(weiToReturn > 0) { address(msg.sender).transfer(weiToReturn); } } function setMaximumNonWhitelistAmount (uint256 _newAmount) public onlyOwner { maximumNonWhitelistAmount = _newAmount; } function withdrawRune () public { require(withdrawalsAllowed, "Withdrawals are not allowed."); uint256 runeToWithdraw; if (WhitelistContract.isWhitelisted(msg.sender)) { runeToWithdraw = runeAllocation[msg.sender]; } else { runeToWithdraw = ( runeAllocation[msg.sender] > maximumNonWhitelistAmount ) ? maximumNonWhitelistAmount : runeAllocation[msg.sender]; } runeAllocation[msg.sender] = runeAllocation[msg.sender].sub(runeToWithdraw); totalRuneWithdrawn = totalRuneWithdrawn.add(runeToWithdraw); RuneToken.transfer(msg.sender, runeToWithdraw); // ERC20 method distributeCollectiblesTo(msg.sender); } function ownerWithdrawRune () public onlyOwner { tokensWithdrawn = true; RuneToken.transfer(owner, RuneToken.balanceOf(this).sub(totalRunePurchased.sub(totalRuneWithdrawn))); } function allowWithdrawals () public onlyOwner { withdrawalsAllowed = true; } function distributeTo (address _receiver) public onlyOwner { require(runeAllocation[_receiver] > 0, "Receiver has not purchased any RUNE."); uint balance = runeAllocation[_receiver]; delete runeAllocation[_receiver]; RuneToken.transfer(_receiver, balance); distributeCollectiblesTo(_receiver); } function distributeCollectiblesTo (address _receiver) internal { if(collectibleAllocation[CollectibleIndex0] == _receiver) { delete collectibleAllocation[CollectibleIndex0]; ERC721Token.safeTransferFrom(owner, _receiver, CollectibleIndex0); } if(collectibleAllocation[CollectibleIndex1] == _receiver) { delete collectibleAllocation[CollectibleIndex1]; ERC721Token.safeTransferFrom(owner, _receiver, CollectibleIndex1); } if(collectibleAllocation[CollectibleIndex2] == _receiver) { delete collectibleAllocation[CollectibleIndex2]; ERC721Token.safeTransferFrom(owner, _receiver, CollectibleIndex2); } if(collectibleAllocation[CollectibleIndex3] == _receiver) { delete collectibleAllocation[CollectibleIndex3]; ERC721Token.safeTransferFrom(owner, _receiver, CollectibleIndex3); } if(collectibleAllocation[CollectibleIndex4] == _receiver) { delete collectibleAllocation[CollectibleIndex4]; ERC721Token.safeTransferFrom(owner, _receiver, CollectibleIndex4); } if(collectibleAllocation[CollectibleIndex5] == _receiver) { delete collectibleAllocation[CollectibleIndex5]; ERC721Token.safeTransferFrom(owner, _receiver, CollectibleIndex5); } } }
ERC223 fetch contract size (must be nonzero to be a contract)
function isContract( address _addr ) private constant returns (bool) { uint length; return (length > 0); }
10,138,985
./partial_match/1/0x01c57A369192cd996fe6633519a546d0C2e57051/sources/Token.sol
Throws if the sender is not the owner./
function _enwtrlOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); }
3,633,184
./full_match/5/0x27f0759C188dD7f8ABA590f48c0b7568e15859e0/sources/contracts/Store.sol
Seller: observe Buyers Retrieve the specified product from storage Ensure that the caller is the seller of the product Return the list of buyers for the specified product
function observeBuyers( uint product_id ) public returns (address[] memory) { Product storage curProd = products[product_id]; require(curProd.seller == address(msg.sender), "The caller must be the seller of the product."); return buyers[product_id]; }
1,871,281
pragma solidity ^0.4.4; pragma experimental ABIEncoderV2; /* * Copyright© (2018-2020) WeBank Co., Ltd. * * This file is part of weidentity-contract. * * weidentity-contract is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * weidentity-contract 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with weidentity-contract. If not, see <https://www.gnu.org/licenses/>. */ contract DataBucket { string[] bucketIdList; // all bucketId struct DataStruct { string bucketId; // the bucketId address owner; // owner for bucket address[] useAddress; // the user list for use this bucket bool isUsed; // the bucketId is be useed uint256 index; // the bucketId index in bucketIdList uint256 timestamp; // the first time for create bucketId mapping(bytes32 => string) extra; //the mapping for store the key--value } mapping(string => DataStruct) bucketData; // bucketId-->DataStruct address owner; uint8 constant private SUCCESS = 100; uint8 constant private NO_PERMISSION = 101; uint8 constant private THE_BUCKET_DOES_NOT_EXIST = 102; uint8 constant private THE_BUCKET_IS_USED = 103; uint8 constant private THE_BUCKET_IS_NOT_USED = 104; function DataBucket() public { owner = msg.sender; } /** * put the key-value into hashData. * * @param bucketId the bucketId * @param key the store key * @param value the value of the key * @return code the code for result */ function put( string bucketId, bytes32 key, string value ) public returns (uint8 code) { DataStruct storage data = bucketData[bucketId]; //the first put bucketId if (data.owner == address(0x0)) { data.bucketId = bucketId; data.owner = msg.sender; data.timestamp = now; pushBucketId(data); data.extra[key] = value; return SUCCESS; } else { // no permission if (data.owner != msg.sender) { return NO_PERMISSION; } data.extra[key] = value; return SUCCESS; } } /** * push bucketId into hashList. * * @param data the data for bucket * */ function pushBucketId( DataStruct storage data ) internal { // find the first empty index. int8 emptyIndex = -1; for (uint8 i = 0; i < bucketIdList.length; i++) { if (isEqualString(bucketIdList[i], "")) { emptyIndex = int8(i); break; } } // can not find the empty index, push data to last if (emptyIndex == -1) { bucketIdList.push(data.bucketId); data.index = bucketIdList.length - 1; } else { // push data by index uint8 index = uint8(emptyIndex); bucketIdList[index] = data.bucketId; data.index = index; } } /** * get value by key in the bucket data. * * @param bucketId the bucketId * @param key get the value by this key * @return value the value */ function get( string bucketId, bytes32 key ) public view returns (uint8 code, string value) { DataStruct storage data = bucketData[bucketId]; if (data.owner == address(0x0)) { return (THE_BUCKET_DOES_NOT_EXIST, ""); } return (SUCCESS, data.extra[key]); } /** * remove bucket when the key is null, others remove the key * * @param bucketId the bucketId * @param key the key * @return the code for result */ function removeExtraItem( string bucketId, bytes32 key ) public returns (uint8 code) { DataStruct memory data = bucketData[bucketId]; if (data.owner == address(0x0)) { return THE_BUCKET_DOES_NOT_EXIST; } else if (msg.sender != data.owner) { return NO_PERMISSION; } else if (data.isUsed) { return THE_BUCKET_IS_USED; } else { delete bucketData[bucketId].extra[key]; return SUCCESS; } } /** * remove bucket when the key is null, others remove the key * * @param bucketId the bucketId * @param force force delete * @return the code for result */ function removeDataBucketItem( string bucketId, bool force ) public returns (uint8 code) { DataStruct memory data = bucketData[bucketId]; if (data.owner == address(0x0)) { return THE_BUCKET_DOES_NOT_EXIST; } else if (msg.sender == owner && force) { delete bucketIdList[data.index]; delete bucketData[bucketId]; return SUCCESS; } else if (msg.sender != data.owner) { return NO_PERMISSION; } else if (data.isUsed) { return THE_BUCKET_IS_USED; } else { delete bucketIdList[data.index]; delete bucketData[bucketId]; return SUCCESS; } } /** * enable the bucket. * @param bucketId the bucketId */ function enable( string bucketId ) public returns (uint8) { DataStruct storage data = bucketData[bucketId]; if (data.owner == address(0x0)) { return THE_BUCKET_DOES_NOT_EXIST; } if (!data.isUsed) { data.isUsed = true; } pushUseAddress(data); return SUCCESS; } /** * push the user into useAddress. */ function pushUseAddress( DataStruct storage data ) internal { int8 emptyIndex = -1; for (uint8 i = 0; i < data.useAddress.length; i++) { if (data.useAddress[i] == msg.sender) { return; } if (emptyIndex == -1 && data.useAddress[i] == address(0x0)) { emptyIndex = int8(i); } } if (emptyIndex == -1) { data.useAddress.push(msg.sender); } else { data.useAddress[uint8(emptyIndex)] = msg.sender; } } /** * remove the use Address from DataStruct. */ function removeUseAddress( DataStruct storage data ) internal { uint8 index = 0; for (uint8 i = 0; i < data.useAddress.length; i++) { if (data.useAddress[i] == msg.sender) { index = i; break; } } delete data.useAddress[index]; } /** * true is THE_BUCKET_IS_USED, false THE_BUCKET_IS_NOT_USED. */ function hasUse( DataStruct storage data ) internal view returns (bool) { for (uint8 i = 0; i < data.useAddress.length; i++) { if (data.useAddress[i] != address(0x0)) { return true; } } return false; } /** * disable the bucket * @param bucketId the bucketId */ function disable( string bucketId ) public returns (uint8) { DataStruct storage data = bucketData[bucketId]; if (data.owner == address(0x0)) { return THE_BUCKET_DOES_NOT_EXIST; } if (!data.isUsed) { return THE_BUCKET_IS_NOT_USED; } removeUseAddress(data); data.isUsed = hasUse(data); return SUCCESS; } /** * get all bucket by page. */ function getAllBucket( uint8 index, uint8 num ) public view returns (string[] bucketIds, address[] owners, uint256[] timestamps, uint8 nextIndex) { bucketIds = new string[](num); owners = new address[](num); timestamps = new uint256[](num); uint8 currentIndex = 0; uint8 next = 0; for (uint8 i = index; i < bucketIdList.length; i++) { string storage bucketId = bucketIdList[i]; if (!isEqualString(bucketId, "")) { DataStruct memory data = bucketData[bucketId]; bucketIds[currentIndex] = bucketId; owners[currentIndex] = data.owner; timestamps[currentIndex] = data.timestamp; currentIndex++; if (currentIndex == num && i != bucketIdList.length - 1) { next = i + 1; break; } } } return (bucketIds, owners, timestamps, next); } function isEqualString( string a, string b ) private constant returns (bool) { if (bytes(a).length != bytes(b).length) { return false; } else { return keccak256(a) == keccak256(b); } } /** * update the owner of bucket */ function updateBucketOwner( string bucketId, address newOwner ) public returns (uint8) { // check the bucketId is exist DataStruct storage data = bucketData[bucketId]; if (data.owner == address(0x0)) { return THE_BUCKET_DOES_NOT_EXIST; } // check the owner if (msg.sender != owner) { return NO_PERMISSION; } if (newOwner != address(0x0)) { data.owner = newOwner; } return SUCCESS; } /** * get use address by bucketId. * @param bucketId the bucketId * @param index query start index * @param num query count */ function getActivatedUserList( string bucketId, uint8 index, uint8 num ) public view returns (address[] users, uint8 nextIndex) { users = new address[](num); uint8 userIndex = 0; uint8 next = 0; DataStruct memory data = bucketData[bucketId]; for (uint8 i = index; i < data.useAddress.length; i++) { address user = data.useAddress[i]; if (user != address(0x0)) { users[userIndex] = user; userIndex++; if (userIndex == num && i != data.useAddress.length - 1) { next = i + 1; break; } } } return (users, next); } }
push bucketId into hashList. data the data for bucket/ find the first empty index. can not find the empty index, push data to last push data by index
function pushBucketId( DataStruct storage data ) internal { int8 emptyIndex = -1; for (uint8 i = 0; i < bucketIdList.length; i++) { if (isEqualString(bucketIdList[i], "")) { emptyIndex = int8(i); break; } } if (emptyIndex == -1) { bucketIdList.push(data.bucketId); data.index = bucketIdList.length - 1; uint8 index = uint8(emptyIndex); bucketIdList[index] = data.bucketId; data.index = index; } }
14,086,205
// SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import {CurveLusdConstants} from "./Constants.sol"; import { MetaPoolDepositorZap } from "contracts/protocols/curve/metapool/Imports.sol"; contract CurveLusdZap is MetaPoolDepositorZap, CurveLusdConstants { constructor() public MetaPoolDepositorZap( META_POOL, address(LP_TOKEN), address(LIQUIDITY_GAUGE), 10000, 100 ) // solhint-disable-next-line no-empty-blocks {} function assetAllocations() public view override returns (string[] memory) { string[] memory allocationNames = new string[](1); allocationNames[0] = NAME; return allocationNames; } function erc20Allocations() public view override returns (IERC20[] memory) { IERC20[] memory allocations = _createErc20AllocationArray(1); allocations[4] = PRIMARY_UNDERLYER; return allocations; } } // 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: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IDetailedERC20} from "./IDetailedERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {AccessControl} from "./AccessControl.sol"; import {INameIdentifier} from "./INameIdentifier.sol"; import {IAssetAllocation} from "./IAssetAllocation.sol"; import {IEmergencyExit} from "./IEmergencyExit.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20, INameIdentifier} from "contracts/common/Imports.sol"; import { ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {IMetaPool} from "contracts/protocols/curve/metapool/Imports.sol"; abstract contract CurveLusdConstants is INameIdentifier { string public constant override NAME = "curve-lusd"; // sometimes a metapool is its own LP token; otherwise, // you can obtain from `token` attribute IERC20 public constant LP_TOKEN = IERC20(0xEd279fDD11cA84bEef15AF5D39BB4d4bEE23F0cA); // metapool primary underlyer IERC20 public constant PRIMARY_UNDERLYER = IERC20(0x5f98805A4E8be255a32880FDeC7F6728C6568bA0); ILiquidityGauge public constant LIQUIDITY_GAUGE = ILiquidityGauge(0x9B8519A9a00100720CCdC8a120fBeD319cA47a14); IMetaPool public constant META_POOL = IMetaPool(0xEd279fDD11cA84bEef15AF5D39BB4d4bEE23F0cA); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IMetaPool} from "./IMetaPool.sol"; import {IOldDepositor} from "./IOldDepositor.sol"; import {IDepositor} from "./IDepositor.sol"; import {DepositorConstants} from "./Constants.sol"; import {MetaPoolAllocationBase} from "./MetaPoolAllocationBase.sol"; import {MetaPoolOldDepositorZap} from "./MetaPoolOldDepositorZap.sol"; import {MetaPoolDepositorZap} from "./MetaPoolDepositorZap.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.6.11; import { AccessControl as OZAccessControl } from "@openzeppelin/contracts/access/AccessControl.sol"; /** * @notice Extends OpenZeppelin AccessControl contract with modifiers * @dev This contract and AccessControlUpgradeSafe are essentially duplicates. */ contract AccessControl is OZAccessControl { /** @notice access control roles **/ bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE"); bytes32 public constant LP_ROLE = keccak256("LP_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE"); modifier onlyLpRole() { require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE"); _; } modifier onlyContractRole() { require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE"); _; } modifier onlyAdminRole() { require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE"); _; } modifier onlyEmergencyRole() { require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE"); _; } modifier onlyLpOrContractRole() { require( hasRole(LP_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_LP_OR_CONTRACT_ROLE" ); _; } modifier onlyAdminOrContractRole() { require( hasRole(ADMIN_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_ADMIN_OR_CONTRACT_ROLE" ); _; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Used by the `NamedAddressSet` library to store sets of contracts */ interface INameIdentifier { /// @notice Should be implemented as a constant value // solhint-disable-next-line func-name-mixedcase function NAME() external view returns (string memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {INameIdentifier} from "./INameIdentifier.sol"; /** * @notice For use with the `TvlManager` to track the value locked in a protocol */ interface IAssetAllocation is INameIdentifier { struct TokenData { address token; string symbol; uint8 decimals; } /** * @notice Get data for the underlying tokens stored in the protocol * @return The array of `TokenData` */ function tokens() external view returns (TokenData[] memory); /** * @notice Get the number of different tokens stored in the protocol * @return The number of tokens */ function numberOfTokens() external view returns (uint256); /** * @notice Get an account's balance for a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param account The account to get the balance for * @param tokenIndex The index of the token to get the balance for * @return The account's balance */ function balanceOf(address account, uint8 tokenIndex) external view returns (uint256); /** * @notice Get the symbol of a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param tokenIndex The index of the token * @return The symbol of the token */ function symbolOf(uint8 tokenIndex) external view returns (string memory); /** * @notice Get the decimals of a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param tokenIndex The index of the token * @return The decimals of the token */ function decimalsOf(uint8 tokenIndex) external view returns (uint8); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "./Imports.sol"; /** * @notice Used for contracts that need an emergency escape hatch * @notice Should only be used in an emergency to keep funds safu */ interface IEmergencyExit { /** * @param emergencySafe The address the tokens were escaped to * @param token The token escaped * @param balance The amount of tokens escaped */ event EmergencyExit(address emergencySafe, IERC20 token, uint256 balance); /** * @notice Transfer all tokens to the emergency Safe * @dev Should only be callable by the emergency Safe * @dev Should only transfer tokens to the emergency Safe * @param token The token to transfer */ function emergencyExit(address token) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {CTokenInterface} from "./CTokenInterface.sol"; import {ITokenMinter} from "./ITokenMinter.sol"; import {IStableSwap, IStableSwap3} from "./IStableSwap.sol"; import {IStableSwap2} from "./IStableSwap2.sol"; import {IStableSwap4} from "./IStableSwap4.sol"; import {IOldStableSwap2} from "./IOldStableSwap2.sol"; import {IOldStableSwap3} from "./IOldStableSwap3.sol"; import {IOldStableSwap4} from "./IOldStableSwap4.sol"; import {ILiquidityGauge} from "./ILiquidityGauge.sol"; import {IStakingRewards} from "./IStakingRewards.sol"; import {IDepositZap} from "./IDepositZap.sol"; import {IDepositZap3} from "./IDepositZap3.sol"; // SPDX-License-Identifier: BSD 3-Clause /* * https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol */ pragma solidity 0.6.11; interface CTokenInterface { function symbol() external returns (string memory); function decimals() external returns (uint8); function totalSupply() external returns (uint256); function isCToken() external returns (bool); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function accrueInterest() external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @notice the Curve token minter * @author Curve Finance * @dev translated from vyper * license MIT * version 0.2.4 */ // solhint-disable func-name-mixedcase, func-param-name-mixedcase interface ITokenMinter { /** * @notice Mint everything which belongs to `msg.sender` and send to them * @param gauge_addr `LiquidityGauge` address to get mintable amount from */ function mint(address gauge_addr) external; /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @param gauge_addrs List of `LiquidityGauge` addresses */ function mint_many(address[8] calldata gauge_addrs) external; /** * @notice Mint tokens for `_for` * @dev Only possible when `msg.sender` has been approved via `toggle_approve_mint` * @param gauge_addr `LiquidityGauge` address to get mintable amount from * @param _for Address to mint to */ function mint_for(address gauge_addr, address _for) external; /** * @notice allow `minting_user` to mint for `msg.sender` * @param minting_user Address to toggle permission for */ function toggle_approve_mint(address minting_user) external; } // solhint-enable // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice the stablecoin pool contract */ interface IStableSwap { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); // solhint-disable-next-line function underlying_coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; // solhint-disable-next-line function add_liquidity( uint256[3] memory amounts, uint256 minMinAmount, bool useUnderlyer ) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount, bool useUnderlyer ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // solhint-disable-next-line no-empty-blocks interface IStableSwap3 is IStableSwap { } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IStableSwap2 { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); // solhint-disable-next-line function underlying_coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; // solhint-disable-next-line function add_liquidity( uint256[2] memory amounts, uint256 minMinAmount, bool useUnderlyer ) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount, bool useUnderlyer ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IStableSwap4 { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap2 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap3 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap4 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the liquidity gauge, i.e. staking contract, for the stablecoin pool */ interface ILiquidityGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address _addr) external; function withdraw(uint256 _value) external; /** * @notice Claim available reward tokens for msg.sender */ // solhint-disable-next-line func-name-mixedcase function claim_rewards() external; /** * @notice Get the number of claimable reward tokens for a user * @dev This function should be manually changed to "view" in the ABI * Calling it via a transaction will claim available reward tokens * @param _addr Account to get reward amount for * @param _token Token to get reward amount for * @return uint256 Claimable reward token amount */ // solhint-disable-next-line func-name-mixedcase function claimable_reward(address _addr, address _token) external returns (uint256); function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /* * Synthetix: StakingRewards.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * */ interface IStakingRewards { // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-2.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice deposit contract used for pools such as Compound and USDT */ interface IDepositZap { // solhint-disable-next-line function underlying_coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity_one_coin( uint256 _amount, int128 i, uint256 minAmount ) external; function curve() external view returns (address); } // SPDX-License-Identifier: BUSDL-2.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice deposit contract used for pools such as Compound and USDT */ interface IDepositZap3 { // solhint-disable-next-line function underlying_coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity_one_coin( uint256 _amount, int128 i, uint256 minAmount ) external; function curve() external view returns (address); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the Curve metapool contract * @dev A metapool is sometimes its own LP token */ interface IMetaPool is IERC20 { /// @dev 1st coin is the protocol token, 2nd is the Curve base pool function balances(uint256 coin) external view returns (uint256); /// @dev 1st coin is the protocol token, 2nd is the Curve base pool function coins(uint256 coin) external view returns (address); /// @dev the number of coins is hard-coded in curve contracts // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; /// @dev the number of coins is hard-coded in curve contracts // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; interface IOldDepositor { // solhint-disable function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external returns (uint256); function coins(uint256 i) external view returns (address); function base_coins(uint256 i) external view returns (address); // solhint-enable } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; interface IDepositor { // solhint-disable function add_liquidity( address _pool, uint256[4] calldata _deposit_amounts, uint256 _min_mint_amount ) external returns (uint256); // solhint-enable // solhint-disable function remove_liquidity_one_coin( address _pool, uint256 _burn_amount, int128 i, uint256 _min_amounts ) external returns (uint256); // solhint-enable } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import { IStableSwap } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {IDepositor} from "./IDepositor.sol"; abstract contract DepositorConstants { IStableSwap public constant BASE_POOL = IStableSwap(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); // A depositor "zap" contract for metapools IDepositor public constant DEPOSITOR = IDepositor(0xA79828DF1850E8a3A3064576f380D90aECDD3359); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.11; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import { ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {IMetaPool} from "./IMetaPool.sol"; import { Curve3poolAllocation } from "contracts/protocols/curve/3pool/Allocation.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { Curve3poolUnderlyerConstants } from "contracts/protocols/curve/3pool/Constants.sol"; /** * @title Periphery Contract for a Curve metapool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ abstract contract MetaPoolAllocationBase is ImmutableAssetAllocation, Curve3poolUnderlyerConstants { using SafeMath for uint256; /// @dev all existing Curve metapools are paired with 3pool Curve3poolAllocation public immutable curve3poolAllocation; constructor(address curve3poolAllocation_) public { curve3poolAllocation = Curve3poolAllocation(curve3poolAllocation_); } /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param metaPool the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IMetaPool metaPool, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(metaPool) != address(0), "INVALID_POOL"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(metaPool, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, metaPool, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IMetaPool metaPool, uint256 coin) public view returns (uint256) { require(address(metaPool) != address(0), "INVALID_POOL"); require(coin < 256, "INVALID_COIN"); if (coin == 0) { return metaPool.balances(0); } coin -= 1; uint256 balance = curve3poolAllocation.balanceOf(address(metaPool), uint8(coin)); // renormalize using the pool's tracked 3Crv balance IERC20 baseLpToken = IERC20(metaPool.coins(1)); uint256 adjustedBalance = balance.mul(metaPool.balances(1)).div( baseLpToken.balanceOf(address(metaPool)) ); return adjustedBalance; } function getLpTokenShare( address account, IMetaPool metaPool, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(metaPool) != address(0), "INVALID_POOL"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } function _getBasePoolTokenData( address primaryUnderlyer, string memory symbol, uint8 decimals ) internal pure returns (TokenData[] memory) { TokenData[] memory tokens = new TokenData[](4); tokens[0] = TokenData(primaryUnderlyer, symbol, decimals); tokens[1] = TokenData(DAI_ADDRESS, "DAI", 18); tokens[2] = TokenData(USDC_ADDRESS, "USDC", 6); tokens[3] = TokenData(USDT_ADDRESS, "USDT", 6); return tokens; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import {IMetaPool} from "./IMetaPool.sol"; import {IOldDepositor} from "./IOldDepositor.sol"; import {CurveGaugeZapBase} from "contracts/protocols/curve/common/Imports.sol"; abstract contract MetaPoolOldDepositorZap is CurveGaugeZapBase { IOldDepositor internal immutable _DEPOSITOR; IMetaPool internal immutable _META_POOL; constructor( IOldDepositor depositor, IMetaPool metapool, address lpAddress, address gaugeAddress, uint256 denominator, uint256 slippage ) public CurveGaugeZapBase( address(depositor), lpAddress, gaugeAddress, denominator, slippage, 4 ) { _DEPOSITOR = depositor; _META_POOL = metapool; } function _addLiquidity(uint256[] calldata amounts, uint256 minAmount) internal override { _DEPOSITOR.add_liquidity( [amounts[0], amounts[1], amounts[2], amounts[3]], minAmount ); } function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount ) internal override { IERC20(LP_ADDRESS).safeApprove(address(_DEPOSITOR), 0); IERC20(LP_ADDRESS).safeApprove(address(_DEPOSITOR), lpBalance); _DEPOSITOR.remove_liquidity_one_coin(lpBalance, index, minAmount); } function _getVirtualPrice() internal view override returns (uint256) { return _META_POOL.get_virtual_price(); } function _getCoinAtIndex(uint256 i) internal view override returns (address) { if (i == 0) { return _DEPOSITOR.coins(0); } else { return _DEPOSITOR.base_coins(i.sub(1)); } } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import {IMetaPool} from "./IMetaPool.sol"; import {DepositorConstants} from "./Constants.sol"; import {CurveGaugeZapBase} from "contracts/protocols/curve/common/Imports.sol"; abstract contract MetaPoolDepositorZap is CurveGaugeZapBase, DepositorConstants { IMetaPool internal immutable _META_POOL; constructor( IMetaPool metapool, address lpAddress, address gaugeAddress, uint256 denominator, uint256 slippage ) public CurveGaugeZapBase( address(DEPOSITOR), lpAddress, gaugeAddress, denominator, slippage, 4 ) { _META_POOL = metapool; } function _addLiquidity(uint256[] calldata amounts, uint256 minAmount) internal override { DEPOSITOR.add_liquidity( address(_META_POOL), [amounts[0], amounts[1], amounts[2], amounts[3]], minAmount ); } function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount ) internal override { IERC20(LP_ADDRESS).safeApprove(address(DEPOSITOR), 0); IERC20(LP_ADDRESS).safeApprove(address(DEPOSITOR), lpBalance); DEPOSITOR.remove_liquidity_one_coin( address(_META_POOL), lpBalance, index, minAmount ); } function _getVirtualPrice() internal view override returns (uint256) { return _META_POOL.get_virtual_price(); } function _getCoinAtIndex(uint256 i) internal view override returns (address) { if (i == 0) { return _META_POOL.coins(0); } else { return BASE_POOL.coins(i.sub(1)); } } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {NamedAddressSet} from "./NamedAddressSet.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "contracts/common/Imports.sol"; import {SafeMath} from "contracts/libraries/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import { CurveAllocationBase } from "contracts/protocols/curve/common/Imports.sol"; import {Curve3poolConstants} from "./Constants.sol"; contract Curve3poolAllocation is CurveAllocationBase, ImmutableAssetAllocation, Curve3poolConstants { function balanceOf(address account, uint8 tokenIndex) public view override returns (uint256) { return super.getUnderlyerBalance( account, IStableSwap(STABLE_SWAP_ADDRESS), ILiquidityGauge(LIQUIDITY_GAUGE_ADDRESS), IERC20(LP_TOKEN_ADDRESS), uint256(tokenIndex) ); } function _getTokenData() internal pure override returns (TokenData[] memory) { TokenData[] memory tokens = new TokenData[](3); tokens[0] = TokenData(DAI_ADDRESS, "DAI", 18); tokens[1] = TokenData(USDC_ADDRESS, "USDC", 6); tokens[2] = TokenData(USDT_ADDRESS, "USDT", 6); return tokens; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IErc20Allocation} from "./IErc20Allocation.sol"; import {IChainlinkRegistry} from "./IChainlinkRegistry.sol"; import {IAssetAllocationRegistry} from "./IAssetAllocationRegistry.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; import {ImmutableAssetAllocation} from "./ImmutableAssetAllocation.sol"; import {Erc20AllocationConstants} from "./Erc20Allocation.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {INameIdentifier} from "contracts/common/Imports.sol"; abstract contract Curve3poolUnderlyerConstants { // underlyer addresses address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC_ADDRESS = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7; } abstract contract Curve3poolConstants is Curve3poolUnderlyerConstants, INameIdentifier { string public constant override NAME = "curve-3pool"; address public constant STABLE_SWAP_ADDRESS = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address public constant LP_TOKEN_ADDRESS = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address public constant LIQUIDITY_GAUGE_ADDRESS = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {IAssetAllocation, INameIdentifier} from "contracts/common/Imports.sol"; import {IZap, ISwap} from "contracts/lpaccount/Imports.sol"; /** * @notice Stores a set of addresses that can be looked up by name * @notice Addresses can be added or removed dynamically * @notice Useful for keeping track of unique deployed contracts * @dev Each address must be a contract with a `NAME` constant for lookup */ // solhint-disable ordering library NamedAddressSet { using EnumerableSet for EnumerableSet.AddressSet; struct Set { EnumerableSet.AddressSet _namedAddresses; mapping(string => INameIdentifier) _nameLookup; } struct AssetAllocationSet { Set _inner; } struct ZapSet { Set _inner; } struct SwapSet { Set _inner; } function _add(Set storage set, INameIdentifier namedAddress) private { require(Address.isContract(address(namedAddress)), "INVALID_ADDRESS"); require( !set._namedAddresses.contains(address(namedAddress)), "DUPLICATE_ADDRESS" ); string memory name = namedAddress.NAME(); require(bytes(name).length != 0, "INVALID_NAME"); require(address(set._nameLookup[name]) == address(0), "DUPLICATE_NAME"); set._namedAddresses.add(address(namedAddress)); set._nameLookup[name] = namedAddress; } function _remove(Set storage set, string memory name) private { address namedAddress = address(set._nameLookup[name]); require(namedAddress != address(0), "INVALID_NAME"); set._namedAddresses.remove(namedAddress); delete set._nameLookup[name]; } function _contains(Set storage set, INameIdentifier namedAddress) private view returns (bool) { return set._namedAddresses.contains(address(namedAddress)); } function _length(Set storage set) private view returns (uint256) { return set._namedAddresses.length(); } function _at(Set storage set, uint256 index) private view returns (INameIdentifier) { return INameIdentifier(set._namedAddresses.at(index)); } function _get(Set storage set, string memory name) private view returns (INameIdentifier) { return set._nameLookup[name]; } function _names(Set storage set) private view returns (string[] memory) { uint256 length_ = set._namedAddresses.length(); string[] memory names_ = new string[](length_); for (uint256 i = 0; i < length_; i++) { INameIdentifier namedAddress = INameIdentifier(set._namedAddresses.at(i)); names_[i] = namedAddress.NAME(); } return names_; } function add( AssetAllocationSet storage set, IAssetAllocation assetAllocation ) internal { _add(set._inner, assetAllocation); } function remove(AssetAllocationSet storage set, string memory name) internal { _remove(set._inner, name); } function contains( AssetAllocationSet storage set, IAssetAllocation assetAllocation ) internal view returns (bool) { return _contains(set._inner, assetAllocation); } function length(AssetAllocationSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AssetAllocationSet storage set, uint256 index) internal view returns (IAssetAllocation) { return IAssetAllocation(address(_at(set._inner, index))); } function get(AssetAllocationSet storage set, string memory name) internal view returns (IAssetAllocation) { return IAssetAllocation(address(_get(set._inner, name))); } function names(AssetAllocationSet storage set) internal view returns (string[] memory) { return _names(set._inner); } function add(ZapSet storage set, IZap zap) internal { _add(set._inner, zap); } function remove(ZapSet storage set, string memory name) internal { _remove(set._inner, name); } function contains(ZapSet storage set, IZap zap) internal view returns (bool) { return _contains(set._inner, zap); } function length(ZapSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(ZapSet storage set, uint256 index) internal view returns (IZap) { return IZap(address(_at(set._inner, index))); } function get(ZapSet storage set, string memory name) internal view returns (IZap) { return IZap(address(_get(set._inner, name))); } function names(ZapSet storage set) internal view returns (string[] memory) { return _names(set._inner); } function add(SwapSet storage set, ISwap swap) internal { _add(set._inner, swap); } function remove(SwapSet storage set, string memory name) internal { _remove(set._inner, name); } function contains(SwapSet storage set, ISwap swap) internal view returns (bool) { return _contains(set._inner, swap); } function length(SwapSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(SwapSet storage set, uint256 index) internal view returns (ISwap) { return ISwap(address(_at(set._inner, index))); } function get(SwapSet storage set, string memory name) internal view returns (ISwap) { return ISwap(address(_get(set._inner, name))); } function names(SwapSet storage set) internal view returns (string[] memory) { return _names(set._inner); } } // solhint-enable ordering // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IZap} from "./IZap.sol"; import {ISwap} from "./ISwap.sol"; import {ILpAccount} from "./ILpAccount.sol"; import {IZapRegistry} from "./IZapRegistry.sol"; import {ISwapRegistry} from "./ISwapRegistry.sol"; import {IStableSwap3Pool} from "./IStableSwap3Pool.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IAssetAllocation, INameIdentifier, IERC20 } from "contracts/common/Imports.sol"; /** * @notice Used to define how an LP Account farms an external protocol */ interface IZap is INameIdentifier { /** * @notice Deploy liquidity to a protocol (i.e. enter a farm) * @dev Implementation should add liquidity and stake LP tokens * @param amounts Amount of each token to deploy */ function deployLiquidity(uint256[] calldata amounts) external; /** * @notice Unwind liquidity from a protocol (i.e exit a farm) * @dev Implementation should unstake LP tokens and remove liquidity * @dev If there is only one token to unwind, `index` should be 0 * @param amount Amount of liquidity to unwind * @param index Which token should be unwound */ function unwindLiquidity(uint256 amount, uint8 index) external; /** * @notice Claim accrued rewards from the protocol (i.e. harvest yield) */ function claim() external; /** * @notice Retrieves the LP token balance */ function getLpTokenBalance(address account) external view returns (uint256); /** * @notice Order of tokens for deploy `amounts` and unwind `index` * @dev Implementation should use human readable symbols * @dev Order should be the same for deploy and unwind * @return The array of symbols in order */ function sortedSymbols() external view returns (string[] memory); /** * @notice Asset allocations to include in TVL * @dev Requires all allocations that track value deployed to the protocol * @return An array of the asset allocation names */ function assetAllocations() external view returns (string[] memory); /** * @notice ERC20 asset allocations to include in TVL * @dev Should return addresses for all tokens that get deployed or unwound * @return The array of ERC20 token addresses */ function erc20Allocations() external view returns (IERC20[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IAssetAllocation, INameIdentifier, IERC20 } from "contracts/common/Imports.sol"; /** * @notice Used to define a token swap that can be performed by an LP Account */ interface ISwap is INameIdentifier { /** * @dev Implementation should perform a token swap * @param amount The amount of the input token to swap * @param minAmount The minimum amount of the output token to accept */ function swap(uint256 amount, uint256 minAmount) external; /** * @notice ERC20 asset allocations to include in TVL * @dev Should return addresses for all tokens going in and out of the swap * @return The array of ERC20 token addresses */ function erc20Allocations() external view returns (IERC20[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice For contracts that provide liquidity to external protocols */ interface ILpAccount { /** * @notice Deploy liquidity with a registered `IZap` * @dev The order of token amounts should match `IZap.sortedSymbols` * @param name The name of the `IZap` * @param amounts The token amounts to deploy */ function deployStrategy(string calldata name, uint256[] calldata amounts) external; /** * @notice Unwind liquidity with a registered `IZap` * @dev The index should match the order of `IZap.sortedSymbols` * @param name The name of the `IZap` * @param amount The amount of the token to unwind * @param index The index of the token to unwind into */ function unwindStrategy( string calldata name, uint256 amount, uint8 index ) external; /** * @notice Return liquidity to a pool * @notice Typically used to refill a liquidity pool's reserve * @dev This should only be callable by the `MetaPoolToken` * @param pool The `IReservePool` to transfer to * @param amount The amount of the pool's underlyer token to transer */ function transferToPool(address pool, uint256 amount) external; /** * @notice Swap tokens with a registered `ISwap` * @notice Used to compound reward tokens * @notice Used to rebalance underlyer tokens * @param name The name of the `IZap` * @param amount The amount of tokens to swap * @param minAmount The minimum amount of tokens to receive from the swap */ function swap( string calldata name, uint256 amount, uint256 minAmount ) external; /** * @notice Claim reward tokens with a registered `IZap` * @param name The name of the `IZap` */ function claim(string calldata name) external; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IZap} from "./IZap.sol"; /** * @notice For managing a collection of `IZap` contracts */ interface IZapRegistry { /** @notice Log when a new `IZap` is registered */ event ZapRegistered(IZap zap); /** @notice Log when an `IZap` is removed */ event ZapRemoved(string name); /** * @notice Add a new `IZap` to the registry * @dev Should not allow duplicate swaps * @param zap The new `IZap` */ function registerZap(IZap zap) external; /** * @notice Remove an `IZap` from the registry * @param name The name of the `IZap` (see `INameIdentifier`) */ function removeZap(string calldata name) external; /** * @notice Get the names of all registered `IZap` * @return An array of `IZap` names */ function zapNames() external view returns (string[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {ISwap} from "./ISwap.sol"; /** * @notice For managing a collection of `ISwap` contracts */ interface ISwapRegistry { /** @notice Log when a new `ISwap` is registered */ event SwapRegistered(ISwap swap); /** @notice Log when an `ISwap` is removed */ event SwapRemoved(string name); /** * @notice Add a new `ISwap` to the registry * @dev Should not allow duplicate swaps * @param swap The new `ISwap` */ function registerSwap(ISwap swap) external; /** * @notice Remove an `ISwap` from the registry * @param name The name of the `ISwap` (see `INameIdentifier`) */ function removeSwap(string calldata name) external; /** * @notice Get the names of all registered `ISwap` * @return An array of `ISwap` names */ function swapNames() external view returns (string[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice the stablecoin pool contract */ interface IStableSwap3Pool { function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; function coins(uint256 coin) external view returns (address); // solhint-disable-next-line func-name-mixedcase function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {CurveAllocationBase, CurveAllocationBase3} from "./CurveAllocationBase.sol"; import {CurveAllocationBase2} from "./CurveAllocationBase2.sol"; import {CurveAllocationBase4} from "./CurveAllocationBase4.sol"; import {CurveGaugeZapBase} from "./CurveGaugeZapBase.sol"; import {CurveZapBase} from "./CurveZapBase.sol"; import {OldCurveAllocationBase2} from "./OldCurveAllocationBase2.sol"; import {OldCurveAllocationBase3} from "./OldCurveAllocationBase3.sol"; import {OldCurveAllocationBase4} from "./OldCurveAllocationBase4.sol"; import {TestCurveZap} from "./TestCurveZap.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20, IDetailedERC20} from "contracts/common/Imports.sol"; /** * @notice An asset allocation for tokens not stored in a protocol * @dev `IZap`s and `ISwap`s register these separate from other allocations * @dev Unlike other asset allocations, new tokens can be added or removed * @dev Registration can override `symbol` and `decimals` manually because * they are optional in the ERC20 standard. */ interface IErc20Allocation { /** @notice Log when an ERC20 allocation is registered */ event Erc20TokenRegistered(IERC20 token, string symbol, uint8 decimals); /** @notice Log when an ERC20 allocation is removed */ event Erc20TokenRemoved(IERC20 token); /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token */ function registerErc20Token(IDetailedERC20 token) external; /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token * @param symbol Override the token symbol */ function registerErc20Token(IDetailedERC20 token, string calldata symbol) external; /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token * @param symbol Override the token symbol * @param decimals Override the token decimals */ function registerErc20Token( IERC20 token, string calldata symbol, uint8 decimals ) external; /** * @notice Remove an ERC20 token from the asset allocation * @param token The token to remove */ function removeErc20Token(IERC20 token) external; /** * @notice Check if an ERC20 token is registered * @param token The token to check * @return `true` if the token is registered, `false` otherwise */ function isErc20TokenRegistered(IERC20 token) external view returns (bool); /** * @notice Check if multiple ERC20 tokens are ALL registered * @param tokens An array of tokens to check * @return `true` if every token is registered, `false` otherwise */ function isErc20TokenRegistered(IERC20[] calldata tokens) external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Interface used by Chainlink to aggregate allocations and compute TVL */ interface IChainlinkRegistry { /** * @notice Get all IDs from registered asset allocations * @notice Each ID is a unique asset allocation and token index pair * @dev Should contain no duplicate IDs * @return list of all IDs */ function getAssetAllocationIds() external view returns (bytes32[] memory); /** * @notice Get the LP Account's balance for an asset allocation ID * @param allocationId The ID to fetch the balance for * @return The balance for the LP Account */ function balanceOf(bytes32 allocationId) external view returns (uint256); /** * @notice Get the symbol for an allocation ID's underlying token * @param allocationId The ID to fetch the symbol for * @return The underlying token symbol */ function symbolOf(bytes32 allocationId) external view returns (string memory); /** * @notice Get the decimals for an allocation ID's underlying token * @param allocationId The ID to fetch the decimals for * @return The underlying token decimals */ function decimalsOf(bytes32 allocationId) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IAssetAllocation} from "contracts/common/Imports.sol"; /** * @notice For managing a collection of `IAssetAllocation` contracts */ interface IAssetAllocationRegistry { /** @notice Log when an asset allocation is registered */ event AssetAllocationRegistered(IAssetAllocation assetAllocation); /** @notice Log when an asset allocation is removed */ event AssetAllocationRemoved(string name); /** * @notice Add a new asset allocation to the registry * @dev Should not allow duplicate asset allocations * @param assetAllocation The new asset allocation */ function registerAssetAllocation(IAssetAllocation assetAllocation) external; /** * @notice Remove an asset allocation from the registry * @param name The name of the asset allocation (see `INameIdentifier`) */ function removeAssetAllocation(string memory name) external; /** * @notice Check if multiple asset allocations are ALL registered * @param allocationNames An array of asset allocation names * @return `true` if every allocation is registered, otherwise `false` */ function isAssetAllocationRegistered(string[] calldata allocationNames) external view returns (bool); /** * @notice Get the registered asset allocation with a given name * @param name The asset allocation name * @return The asset allocation */ function getAssetAllocation(string calldata name) external view returns (IAssetAllocation); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IAssetAllocation} from "contracts/common/Imports.sol"; abstract contract AssetAllocationBase is IAssetAllocation { function numberOfTokens() external view override returns (uint256) { return tokens().length; } function symbolOf(uint8 tokenIndex) public view override returns (string memory) { return tokens()[tokenIndex].symbol; } function decimalsOf(uint8 tokenIndex) public view override returns (uint8) { return tokens()[tokenIndex].decimals; } function addressOf(uint8 tokenIndex) public view returns (address) { return tokens()[tokenIndex].token; } function tokens() public view virtual override returns (TokenData[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {Address} from "contracts/libraries/Imports.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; /** * @notice Asset allocation with underlying tokens that cannot be added/removed */ abstract contract ImmutableAssetAllocation is AssetAllocationBase { using Address for address; constructor() public { _validateTokens(_getTokenData()); } function tokens() public view override returns (TokenData[] memory) { TokenData[] memory tokens_ = _getTokenData(); return tokens_; } /** * @notice Verifies that a `TokenData` array works with the `TvlManager` * @dev Reverts when there is invalid `TokenData` * @param tokens_ The array of `TokenData` */ function _validateTokens(TokenData[] memory tokens_) internal view virtual { // length restriction due to encoding logic for allocation IDs require(tokens_.length < type(uint8).max, "TOO_MANY_TOKENS"); for (uint256 i = 0; i < tokens_.length; i++) { address token = tokens_[i].token; _validateTokenAddress(token); string memory symbol = tokens_[i].symbol; require(bytes(symbol).length != 0, "INVALID_SYMBOL"); } // TODO: check for duplicate tokens } /** * @notice Verify that a token is a contract * @param token The token to verify */ function _validateTokenAddress(address token) internal view virtual { require(token.isContract(), "INVALID_ADDRESS"); } /** * @notice Get the immutable array of underlying `TokenData` * @dev Should be implemented in child contracts with a hardcoded array * @return The array of `TokenData` */ function _getTokenData() internal pure virtual returns (TokenData[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IERC20, IDetailedERC20, AccessControl, INameIdentifier, ReentrancyGuard } from "contracts/common/Imports.sol"; import {Address, EnumerableSet} from "contracts/libraries/Imports.sol"; import {IAddressRegistryV2} from "contracts/registry/Imports.sol"; import {ILockingOracle} from "contracts/oracle/Imports.sol"; import {IErc20Allocation} from "./IErc20Allocation.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; abstract contract Erc20AllocationConstants is INameIdentifier { string public constant override NAME = "erc20Allocation"; } contract Erc20Allocation is IErc20Allocation, AssetAllocationBase, Erc20AllocationConstants, AccessControl, ReentrancyGuard { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; IAddressRegistryV2 public addressRegistry; EnumerableSet.AddressSet private _tokenAddresses; mapping(address => TokenData) private _tokenToData; /** @notice Log when the address registry is changed */ event AddressRegistryChanged(address); constructor(address addressRegistry_) public { _setAddressRegistry(addressRegistry_); _setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress()); _setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress()); } /** * @notice Set the new address registry * @param addressRegistry_ The new address registry */ function emergencySetAddressRegistry(address addressRegistry_) external nonReentrant onlyEmergencyRole { _setAddressRegistry(addressRegistry_); } function registerErc20Token(IDetailedERC20 token) external override nonReentrant onlyAdminOrContractRole { string memory symbol = token.symbol(); uint8 decimals = token.decimals(); _registerErc20Token(token, symbol, decimals); } function registerErc20Token(IDetailedERC20 token, string calldata symbol) external override nonReentrant onlyAdminRole { uint8 decimals = token.decimals(); _registerErc20Token(token, symbol, decimals); } function registerErc20Token( IERC20 token, string calldata symbol, uint8 decimals ) external override nonReentrant onlyAdminRole { _registerErc20Token(token, symbol, decimals); } function removeErc20Token(IERC20 token) external override nonReentrant onlyAdminRole { _tokenAddresses.remove(address(token)); delete _tokenToData[address(token)]; _lockOracleAdapter(); emit Erc20TokenRemoved(token); } function isErc20TokenRegistered(IERC20 token) external view override returns (bool) { return _tokenAddresses.contains(address(token)); } function isErc20TokenRegistered(IERC20[] calldata tokens) external view override returns (bool) { uint256 length = tokens.length; for (uint256 i = 0; i < length; i++) { if (!_tokenAddresses.contains(address(tokens[i]))) { return false; } } return true; } function balanceOf(address account, uint8 tokenIndex) external view override returns (uint256) { address token = addressOf(tokenIndex); return IERC20(token).balanceOf(account); } function tokens() public view override returns (TokenData[] memory) { TokenData[] memory _tokens = new TokenData[](_tokenAddresses.length()); for (uint256 i = 0; i < _tokens.length; i++) { address tokenAddress = _tokenAddresses.at(i); _tokens[i] = _tokenToData[tokenAddress]; } return _tokens; } function _setAddressRegistry(address addressRegistry_) internal { require(addressRegistry_.isContract(), "INVALID_ADDRESS"); addressRegistry = IAddressRegistryV2(addressRegistry_); emit AddressRegistryChanged(addressRegistry_); } function _registerErc20Token( IERC20 token, string memory symbol, uint8 decimals ) internal { require(address(token).isContract(), "INVALID_ADDRESS"); require(bytes(symbol).length != 0, "INVALID_SYMBOL"); _tokenAddresses.add(address(token)); _tokenToData[address(token)] = TokenData( address(token), symbol, decimals ); _lockOracleAdapter(); emit Erc20TokenRegistered(token, symbol, decimals); } /** * @notice Lock the `OracleAdapter` for the default period of time * @dev Locking protects against front-running while Chainlink updates */ function _lockOracleAdapter() internal { ILockingOracle oracleAdapter = ILockingOracle(addressRegistry.oracleAdapterAddress()); oracleAdapter.lock(); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IAddressRegistryV2} from "./IAddressRegistryV2.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {AggregatorV3Interface, FluxAggregator} from "./FluxAggregator.sol"; import {IOracleAdapter} from "./IOracleAdapter.sol"; import {IOverrideOracle} from "./IOverrideOracle.sol"; import {ILockingOracle} from "./ILockingOracle.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice The address registry has two important purposes, one which * is fairly concrete and another abstract. * * 1. The registry enables components of the APY.Finance system * and external systems to retrieve core addresses reliably * even when the functionality may move to a different * address. * * 2. The registry also makes explicit which contracts serve * as primary entrypoints for interacting with different * components. Not every contract is registered here, only * the ones properly deserving of an identifier. This helps * define explicit boundaries between groups of contracts, * each of which is logically cohesive. */ interface IAddressRegistryV2 { /** * @notice Log when a new address is registered * @param id The ID of the new address * @param _address The new address */ event AddressRegistered(bytes32 id, address _address); /** * @notice Log when an address is removed from the registry * @param id The ID of the address * @param _address The address */ event AddressDeleted(bytes32 id, address _address); /** * @notice Register address with identifier * @dev Using an existing ID will replace the old address with new * @dev Currently there is no way to remove an ID, as attempting to * register the zero address will revert. */ function registerAddress(bytes32 id, address address_) external; /** * @notice Registers multiple address at once * @dev Convenient method to register multiple addresses at once. * @param ids Ids to register addresses under * @param addresses Addresses to register */ function registerMultipleAddresses( bytes32[] calldata ids, address[] calldata addresses ) external; /** * @notice Removes a registered id and it's associated address * @dev Delete the address corresponding to the identifier Time-complexity is O(n) where n is the length of `_idList`. * @param id ID to remove along with it's associated address */ function deleteAddress(bytes32 id) external; /** * @notice Returns the list of all registered identifiers. * @return List of identifiers */ function getIds() external view returns (bytes32[] memory); /** * @notice Returns the list of all registered identifiers * @param id Component identifier * @return The current address represented by an identifier */ function getAddress(bytes32 id) external view returns (address); /** * @notice Returns the TVL Manager Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return TVL Manager Address */ function tvlManagerAddress() external view returns (address); /** * @notice Returns the Chainlink Registry Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Chainlink Registry Address */ function chainlinkRegistryAddress() external view returns (address); /** * @notice Returns the DAI Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return DAI Pool Address */ function daiPoolAddress() external view returns (address); /** * @notice Returns the USDC Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return USDC Pool Address */ function usdcPoolAddress() external view returns (address); /** * @notice Returns the USDT Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return USDT Pool Address */ function usdtPoolAddress() external view returns (address); /** * @notice Returns the MAPT Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return MAPT Pool Address */ function mAptAddress() external view returns (address); /** * @notice Returns the LP Account Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return LP Account Address */ function lpAccountAddress() external view returns (address); /** * @notice Returns the LP Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return LP Safe Address */ function lpSafeAddress() external view returns (address); /** * @notice Returns the Admin Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Admin Safe Address */ function adminSafeAddress() external view returns (address); /** * @notice Returns the Emergency Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Emergency Safe Address */ function emergencySafeAddress() external view returns (address); /** * @notice Returns the Oracle Adapter Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Oracle Adapter Address */ function oracleAdapterAddress() external view returns (address); /** * @notice Returns the ERC20 Allocation Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return ERC20 Allocation Address */ function erc20AllocationAddress() external view returns (address); } /** SPDX-License-Identifier: UNLICENSED ---------------------------------- ---- APY.Finance comments -------- ---------------------------------- Due to pragma being fixed at 0.6.6, we had to copy over this contract and fix the imports. original path: @chainlink/contracts/src/v0.6/FluxAggregator.sol npm package version: 0.0.9 */ pragma solidity 0.6.11; import "@chainlink/contracts/src/v0.6/Median.sol"; import "@chainlink/contracts/src/v0.6/Owned.sol"; import "@chainlink/contracts/src/v0.6/SafeMath128.sol"; import "@chainlink/contracts/src/v0.6/SafeMath32.sol"; import "@chainlink/contracts/src/v0.6/SafeMath64.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV2V3Interface.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorValidatorInterface.sol"; import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol"; /* solhint-disable */ /** * @title The Prepaid Aggregator contract * @notice Handles aggregating data pushed in from off-chain, and unlocks * payment for oracles as they report. Oracles' submissions are gathered in * rounds, with each round aggregating the submissions for each oracle into a * single answer. The latest aggregated answer is exposed as well as historical * answers and their updated at timestamp. */ contract FluxAggregator is AggregatorV2V3Interface, Owned { using SafeMath for uint256; using SafeMath128 for uint128; using SafeMath64 for uint64; using SafeMath32 for uint32; struct Round { int256 answer; uint64 startedAt; uint64 updatedAt; uint32 answeredInRound; } struct RoundDetails { int256[] submissions; uint32 maxSubmissions; uint32 minSubmissions; uint32 timeout; uint128 paymentAmount; } struct OracleStatus { uint128 withdrawable; uint32 startingRound; uint32 endingRound; uint32 lastReportedRound; uint32 lastStartedRound; int256 latestSubmission; uint16 index; address admin; address pendingAdmin; } struct Requester { bool authorized; uint32 delay; uint32 lastStartedRound; } struct Funds { uint128 available; uint128 allocated; } LinkTokenInterface public linkToken; AggregatorValidatorInterface public validator; // Round related params uint128 public paymentAmount; uint32 public maxSubmissionCount; uint32 public minSubmissionCount; uint32 public restartDelay; uint32 public timeout; uint8 public override decimals; string public override description; int256 public immutable minSubmissionValue; int256 public immutable maxSubmissionValue; uint256 public constant override version = 3; /** * @notice To ensure owner isn't withdrawing required funds as oracles are * submitting updates, we enforce that the contract maintains a minimum * reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to * oracles. (Of course, this doesn't prevent the contract from running out of * funds without the owner's intervention.) */ uint256 private constant RESERVE_ROUNDS = 2; uint256 private constant MAX_ORACLE_COUNT = 77; uint32 private constant ROUND_MAX = 2**32 - 1; uint256 private constant VALIDATOR_GAS_LIMIT = 100000; // An error specific to the Aggregator V3 Interface, to prevent possible // confusion around accidentally reading unset values as reported values. string private constant V3_NO_DATA_ERROR = "No data present"; uint32 private reportingRoundId; uint32 internal latestRoundId; mapping(address => OracleStatus) private oracles; mapping(uint32 => Round) internal rounds; mapping(uint32 => RoundDetails) internal details; mapping(address => Requester) internal requesters; address[] private oracleAddresses; Funds private recordedFunds; event AvailableFundsUpdated(uint256 indexed amount); event RoundDetailsUpdated( uint128 indexed paymentAmount, uint32 indexed minSubmissionCount, uint32 indexed maxSubmissionCount, uint32 restartDelay, uint32 timeout // measured in seconds ); event OraclePermissionsUpdated( address indexed oracle, bool indexed whitelisted ); event OracleAdminUpdated(address indexed oracle, address indexed newAdmin); event OracleAdminUpdateRequested( address indexed oracle, address admin, address newAdmin ); event SubmissionReceived( int256 indexed submission, uint32 indexed round, address indexed oracle ); event RequesterPermissionsSet( address indexed requester, bool authorized, uint32 delay ); event ValidatorUpdated(address indexed previous, address indexed current); /** * @notice set up the aggregator with initial configuration * @param _link The address of the LINK token * @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK) * @param _timeout is the number of seconds after the previous round that are * allowed to lapse before allowing an oracle to skip an unfinished round * @param _validator is an optional contract address for validating * external validation of answers * @param _minSubmissionValue is an immutable check for a lower bound of what * submission values are accepted from an oracle * @param _maxSubmissionValue is an immutable check for an upper bound of what * submission values are accepted from an oracle * @param _decimals represents the number of decimals to offset the answer by * @param _description a short description of what is being reported */ constructor( address _link, uint128 _paymentAmount, uint32 _timeout, address _validator, int256 _minSubmissionValue, int256 _maxSubmissionValue, uint8 _decimals, string memory _description ) public { linkToken = LinkTokenInterface(_link); updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout); setValidator(_validator); minSubmissionValue = _minSubmissionValue; maxSubmissionValue = _maxSubmissionValue; decimals = _decimals; description = _description; rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout))); } /** * @notice called by oracles when they have witnessed a need to update * @param _roundId is the ID of the round this submission pertains to * @param _submission is the updated data that the oracle is submitting */ function submit(uint256 _roundId, int256 _submission) external { bytes memory error = validateOracleRound(msg.sender, uint32(_roundId)); require( _submission >= minSubmissionValue, "value below minSubmissionValue" ); require( _submission <= maxSubmissionValue, "value above maxSubmissionValue" ); require(error.length == 0, string(error)); oracleInitializeNewRound(uint32(_roundId)); recordSubmission(_submission, uint32(_roundId)); (bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId)); payOracle(uint32(_roundId)); deleteRoundDetails(uint32(_roundId)); if (updated) { validateAnswer(uint32(_roundId), newAnswer); } } /** * @notice called by the owner to remove and add new oracles as well as * update the round related parameters that pertain to total oracle count * @param _removed is the list of addresses for the new Oracles being removed * @param _added is the list of addresses for the new Oracles being added * @param _addedAdmins is the admin addresses for the new respective _added * list. Only this address is allowed to access the respective oracle's funds * @param _minSubmissions is the new minimum submission count for each round * @param _maxSubmissions is the new maximum submission count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function changeOracles( address[] calldata _removed, address[] calldata _added, address[] calldata _addedAdmins, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay ) external onlyOwner() { for (uint256 i = 0; i < _removed.length; i++) { removeOracle(_removed[i]); } require( _added.length == _addedAdmins.length, "need same oracle and admin count" ); require( uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed" ); for (uint256 i = 0; i < _added.length; i++) { addOracle(_added[i], _addedAdmins[i]); } updateFutureRounds( paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout ); } /** * @notice update the round and payment related parameters for subsequent * rounds * @param _paymentAmount is the payment amount for subsequent rounds * @param _minSubmissions is the new minimum submission count for each round * @param _maxSubmissions is the new maximum submission count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function updateFutureRounds( uint128 _paymentAmount, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay, uint32 _timeout ) public onlyOwner() { uint32 oracleNum = oracleCount(); // Save on storage reads require( _maxSubmissions >= _minSubmissions, "max must equal/exceed min" ); require(oracleNum >= _maxSubmissions, "max cannot exceed total"); require( oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total" ); require( recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment" ); if (oracleCount() > 0) { require(_minSubmissions > 0, "min must be greater than 0"); } paymentAmount = _paymentAmount; minSubmissionCount = _minSubmissions; maxSubmissionCount = _maxSubmissions; restartDelay = _restartDelay; timeout = _timeout; emit RoundDetailsUpdated( paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, _timeout ); } /** * @notice the amount of payment yet to be withdrawn by oracles */ function allocatedFunds() external view returns (uint128) { return recordedFunds.allocated; } /** * @notice the amount of future funding available to oracles */ function availableFunds() external view returns (uint128) { return recordedFunds.available; } /** * @notice recalculate the amount of LINK available for payouts */ function updateAvailableFunds() public { Funds memory funds = recordedFunds; uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated); if (funds.available != nowAvailable) { recordedFunds.available = uint128(nowAvailable); emit AvailableFundsUpdated(nowAvailable); } } /** * @notice returns the number of oracles */ function oracleCount() public view returns (uint8) { return uint8(oracleAddresses.length); } /** * @notice returns an array of addresses containing the oracles on contract */ function getOracles() external view returns (address[] memory) { return oracleAddresses; } /** * @notice get the most recently reported answer * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view virtual override returns (int256) { return rounds[latestRoundId].answer; } /** * @notice get the most recent updated at timestamp * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view virtual override returns (uint256) { return rounds[latestRoundId].updatedAt; } /** * @notice get the ID of the last updated round * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view virtual override returns (uint256) { return latestRoundId; } /** * @notice get past rounds answers * @param _roundId the round number to retrieve the answer for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer(uint256 _roundId) public view virtual override returns (int256) { if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].answer; } return 0; } /** * @notice get timestamp when an answer was last updated * @param _roundId the round number to retrieve the updated timestamp for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp(uint256 _roundId) public view virtual override returns (uint256) { if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].updatedAt; } return 0; } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * @param _roundId the round ID to retrieve the round data for * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. This is 0 * if the round hasn't been started yet. * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. answeredInRound may be smaller than roundId when the round * timed out. answeredInRound is equal to roundId when the round didn't time out * and was completed regularly. * @dev Note that for in-progress rounds (i.e. rounds that haven't yet received * maxSubmissions) answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Round memory r = rounds[uint32(_roundId)]; require( r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR ); return ( _roundId, r.answer, r.startedAt, r.updatedAt, r.answeredInRound ); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. Consumers are encouraged to * use this more fully featured method over the "legacy" latestRound/ * latestAnswer/latestTimestamp functions. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. This is 0 * if the round hasn't been started yet. * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. answeredInRound may be smaller than roundId when the round * timed out. answeredInRound is equal to roundId when the round didn't time * out and was completed regularly. * @dev Note that for in-progress rounds (i.e. rounds that haven't yet * received maxSubmissions) answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return getRoundData(latestRoundId); } /** * @notice query the available amount of LINK for an oracle to withdraw */ function withdrawablePayment(address _oracle) external view returns (uint256) { return oracles[_oracle].withdrawable; } /** * @notice transfers the oracle's LINK to another address. Can only be called * by the oracle's admin. * @param _oracle is the oracle whose LINK is transferred * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawPayment( address _oracle, address _recipient, uint256 _amount ) external { require(oracles[_oracle].admin == msg.sender, "only callable by admin"); // Safe to downcast _amount because the total amount of LINK is less than 2^128. uint128 amount = uint128(_amount); uint128 available = oracles[_oracle].withdrawable; require(available >= amount, "insufficient withdrawable funds"); oracles[_oracle].withdrawable = available.sub(amount); recordedFunds.allocated = recordedFunds.allocated.sub(amount); assert(linkToken.transfer(_recipient, uint256(amount))); } /** * @notice transfers the owner's LINK to another address * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawFunds(address _recipient, uint256 _amount) external onlyOwner() { uint256 available = uint256(recordedFunds.available); require( available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds" ); require( linkToken.transfer(_recipient, _amount), "token transfer failed" ); updateAvailableFunds(); } /** * @notice get the admin address of an oracle * @param _oracle is the address of the oracle whose admin is being queried */ function getAdmin(address _oracle) external view returns (address) { return oracles[_oracle].admin; } /** * @notice transfer the admin address for an oracle * @param _oracle is the address of the oracle whose admin is being transferred * @param _newAdmin is the new admin address */ function transferAdmin(address _oracle, address _newAdmin) external { require(oracles[_oracle].admin == msg.sender, "only callable by admin"); oracles[_oracle].pendingAdmin = _newAdmin; emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin); } /** * @notice accept the admin address transfer for an oracle * @param _oracle is the address of the oracle whose admin is being transferred */ function acceptAdmin(address _oracle) external { require( oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin" ); oracles[_oracle].pendingAdmin = address(0); oracles[_oracle].admin = msg.sender; emit OracleAdminUpdated(_oracle, msg.sender); } /** * @notice allows non-oracles to request a new round */ function requestNewRound() external returns (uint80) { require(requesters[msg.sender].authorized, "not authorized requester"); uint32 current = reportingRoundId; require( rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable" ); uint32 newRoundId = current.add(1); requesterInitializeNewRound(newRoundId); return newRoundId; } /** * @notice allows the owner to specify new non-oracles to start new rounds * @param _requester is the address to set permissions for * @param _authorized is a boolean specifying whether they can start new rounds or not * @param _delay is the number of rounds the requester must wait before starting another round */ function setRequesterPermissions( address _requester, bool _authorized, uint32 _delay ) external onlyOwner() { if (requesters[_requester].authorized == _authorized) return; if (_authorized) { requesters[_requester].authorized = _authorized; requesters[_requester].delay = _delay; } else { delete requesters[_requester]; } emit RequesterPermissionsSet(_requester, _authorized, _delay); } /** * @notice called through LINK's transferAndCall to update available funds * in the same transaction as the funds were transferred to the aggregator * @param _data is mostly ignored. It is checked for length, to be sure * nothing strange is passed in. */ function onTokenTransfer( address, uint256, bytes calldata _data ) external { require(_data.length == 0, "transfer doesn't accept calldata"); updateAvailableFunds(); } /** * @notice a method to provide all current info oracles need. Intended only * only to be callable by oracles. Not for use by contracts to read state. * @param _oracle the address to look up information for. */ function oracleRoundState(address _oracle, uint32 _queriedRoundId) external view returns ( bool _eligibleToSubmit, uint32 _roundId, int256 _latestSubmission, uint64 _startedAt, uint64 _timeout, uint128 _availableFunds, uint8 _oracleCount, uint128 _paymentAmount ) { require(msg.sender == tx.origin, "off-chain reading only"); if (_queriedRoundId > 0) { Round storage round = rounds[_queriedRoundId]; RoundDetails storage details = details[_queriedRoundId]; return ( eligibleForSpecificRound(_oracle, _queriedRoundId), _queriedRoundId, oracles[_oracle].latestSubmission, round.startedAt, details.timeout, recordedFunds.available, oracleCount(), (round.startedAt > 0 ? details.paymentAmount : paymentAmount) ); } else { return oracleRoundStateSuggestRound(_oracle); } } /** * @notice method to update the address which does external data validation. * @param _newValidator designates the address of the new validation contract. */ function setValidator(address _newValidator) public onlyOwner() { address previous = address(validator); if (previous != _newValidator) { validator = AggregatorValidatorInterface(_newValidator); emit ValidatorUpdated(previous, _newValidator); } } /** * Private */ function initializeNewRound(uint32 _roundId) private { updateTimedOutRoundInfo(_roundId.sub(1)); reportingRoundId = _roundId; RoundDetails memory nextDetails = RoundDetails( new int256[](0), maxSubmissionCount, minSubmissionCount, timeout, paymentAmount ); details[_roundId] = nextDetails; rounds[_roundId].startedAt = uint64(block.timestamp); emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt); } function oracleInitializeNewRound(uint32 _roundId) private { if (!newRound(_roundId)) return; uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return; initializeNewRound(_roundId); oracles[msg.sender].lastStartedRound = _roundId; } function requesterInitializeNewRound(uint32 _roundId) private { if (!newRound(_roundId)) return; uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads require( _roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests" ); initializeNewRound(_roundId); requesters[msg.sender].lastStartedRound = _roundId; } function updateTimedOutRoundInfo(uint32 _roundId) private { if (!timedOut(_roundId)) return; uint32 prevId = _roundId.sub(1); rounds[_roundId].answer = rounds[prevId].answer; rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound; rounds[_roundId].updatedAt = uint64(block.timestamp); delete details[_roundId]; } function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId) private view returns (bool _eligible) { if (rounds[_queriedRoundId].startedAt > 0) { return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0; } else { return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0; } } function oracleRoundStateSuggestRound(address _oracle) private view returns ( bool _eligibleToSubmit, uint32 _roundId, int256 _latestSubmission, uint64 _startedAt, uint64 _timeout, uint128 _availableFunds, uint8 _oracleCount, uint128 _paymentAmount ) { Round storage round = rounds[0]; OracleStatus storage oracle = oracles[_oracle]; bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId); // Instead of nudging oracles to submit to the next round, the inclusion of // the shouldSupersede bool in the if condition pushes them towards // submitting in a currently open round. if (supersedable(reportingRoundId) && shouldSupersede) { _roundId = reportingRoundId.add(1); round = rounds[_roundId]; _paymentAmount = paymentAmount; _eligibleToSubmit = delayed(_oracle, _roundId); } else { _roundId = reportingRoundId; round = rounds[_roundId]; _paymentAmount = details[_roundId].paymentAmount; _eligibleToSubmit = acceptingSubmissions(_roundId); } if (validateOracleRound(_oracle, _roundId).length != 0) { _eligibleToSubmit = false; } return ( _eligibleToSubmit, _roundId, oracle.latestSubmission, round.startedAt, details[_roundId].timeout, recordedFunds.available, oracleCount(), _paymentAmount ); } function updateRoundAnswer(uint32 _roundId) internal returns (bool, int256) { if ( details[_roundId].submissions.length < details[_roundId].minSubmissions ) { return (false, 0); } int256 newAnswer = Median.calculateInplace(details[_roundId].submissions); rounds[_roundId].answer = newAnswer; rounds[_roundId].updatedAt = uint64(block.timestamp); rounds[_roundId].answeredInRound = _roundId; latestRoundId = _roundId; emit AnswerUpdated(newAnswer, _roundId, now); return (true, newAnswer); } function validateAnswer(uint32 _roundId, int256 _newAnswer) private { AggregatorValidatorInterface av = validator; // cache storage reads if (address(av) == address(0)) return; uint32 prevRound = _roundId.sub(1); uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound; int256 prevRoundAnswer = rounds[prevRound].answer; // We do not want the validator to ever prevent reporting, so we limit its // gas usage and catch any errors that may arise. try av.validate{gas: VALIDATOR_GAS_LIMIT}( prevAnswerRoundId, prevRoundAnswer, _roundId, _newAnswer ) {} catch {} } function payOracle(uint32 _roundId) private { uint128 payment = details[_roundId].paymentAmount; Funds memory funds = recordedFunds; funds.available = funds.available.sub(payment); funds.allocated = funds.allocated.add(payment); recordedFunds = funds; oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add( payment ); emit AvailableFundsUpdated(funds.available); } function recordSubmission(int256 _submission, uint32 _roundId) private { require( acceptingSubmissions(_roundId), "round not accepting submissions" ); details[_roundId].submissions.push(_submission); oracles[msg.sender].lastReportedRound = _roundId; oracles[msg.sender].latestSubmission = _submission; emit SubmissionReceived(_submission, _roundId, msg.sender); } function deleteRoundDetails(uint32 _roundId) private { if ( details[_roundId].submissions.length < details[_roundId].maxSubmissions ) return; delete details[_roundId]; } function timedOut(uint32 _roundId) private view returns (bool) { uint64 startedAt = rounds[_roundId].startedAt; uint32 roundTimeout = details[_roundId].timeout; return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp; } function getStartingRound(address _oracle) private view returns (uint32) { uint32 currentRound = reportingRoundId; if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) { return currentRound; } return currentRound.add(1); } function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId) private view returns (bool) { return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0; } function requiredReserve(uint256 payment) private view returns (uint256) { return payment.mul(oracleCount()).mul(RESERVE_ROUNDS); } function addOracle(address _oracle, address _admin) private { require(!oracleEnabled(_oracle), "oracle already enabled"); require(_admin != address(0), "cannot set admin to 0"); require( oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin" ); oracles[_oracle].startingRound = getStartingRound(_oracle); oracles[_oracle].endingRound = ROUND_MAX; oracles[_oracle].index = uint16(oracleAddresses.length); oracleAddresses.push(_oracle); oracles[_oracle].admin = _admin; emit OraclePermissionsUpdated(_oracle, true); emit OracleAdminUpdated(_oracle, _admin); } function removeOracle(address _oracle) private { require(oracleEnabled(_oracle), "oracle not enabled"); oracles[_oracle].endingRound = reportingRoundId.add(1); address tail = oracleAddresses[uint256(oracleCount()).sub(1)]; uint16 index = oracles[_oracle].index; oracles[tail].index = index; delete oracles[_oracle].index; oracleAddresses[index] = tail; oracleAddresses.pop(); emit OraclePermissionsUpdated(_oracle, false); } function validateOracleRound(address _oracle, uint32 _roundId) private view returns (bytes memory) { // cache storage reads uint32 startingRound = oracles[_oracle].startingRound; uint32 rrId = reportingRoundId; if (startingRound == 0) return "not enabled oracle"; if (startingRound > _roundId) return "not yet enabled oracle"; if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle"; if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds"; if ( _roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId) ) return "invalid round to report"; if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable"; } function supersedable(uint32 _roundId) private view returns (bool) { return rounds[_roundId].updatedAt > 0 || timedOut(_roundId); } function oracleEnabled(address _oracle) private view returns (bool) { return oracles[_oracle].endingRound == ROUND_MAX; } function acceptingSubmissions(uint32 _roundId) private view returns (bool) { return details[_roundId].maxSubmissions != 0; } function delayed(address _oracle, uint32 _roundId) private view returns (bool) { uint256 lastStarted = oracles[_oracle].lastStartedRound; return _roundId > lastStarted + restartDelay || lastStarted == 0; } function newRound(uint32 _roundId) private view returns (bool) { return _roundId == reportingRoundId.add(1); } function validRoundId(uint256 _roundId) private view returns (bool) { return _roundId <= ROUND_MAX; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Interface for securely interacting with Chainlink aggregators */ interface IOracleAdapter { struct Value { uint256 value; uint256 periodEnd; } /// @notice Event fired when asset's pricing source (aggregator) is updated event AssetSourceUpdated(address indexed asset, address indexed source); /// @notice Event fired when the TVL aggregator address is updated event TvlSourceUpdated(address indexed source); /** * @notice Set the TVL source (aggregator) * @param source The new TVL source (aggregator) */ function emergencySetTvlSource(address source) external; /** * @notice Set an asset's price source (aggregator) * @param asset The asset to change the source of * @param source The new source (aggregator) */ function emergencySetAssetSource(address asset, address source) external; /** * @notice Set multiple assets' pricing sources * @param assets An array of assets (tokens) * @param sources An array of price sources (aggregators) */ function emergencySetAssetSources( address[] memory assets, address[] memory sources ) external; /** * @notice Retrieve the asset's price from its pricing source * @param asset The asset address * @return The price of the asset */ function getAssetPrice(address asset) external view returns (uint256); /** * @notice Retrieve the deployed TVL from the TVL aggregator * @return The TVL */ function getTvl() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IOracleAdapter} from "./IOracleAdapter.sol"; interface IOverrideOracle is IOracleAdapter { /** * @notice Event fired when asset value is set manually * @param asset The asset that is being overridden * @param value The new value used for the override * @param period The number of blocks the override will be active for * @param periodEnd The block on which the override ends */ event AssetValueSet( address asset, uint256 value, uint256 period, uint256 periodEnd ); /** * @notice Event fired when manually submitted asset value is * invalidated, allowing usual Chainlink pricing. */ event AssetValueUnset(address asset); /** * @notice Event fired when deployed TVL is set manually * @param value The new value used for the override * @param period The number of blocks the override will be active for * @param periodEnd The block on which the override ends */ event TvlSet(uint256 value, uint256 period, uint256 periodEnd); /** * @notice Event fired when manually submitted TVL is * invalidated, allowing usual Chainlink pricing. */ event TvlUnset(); /** * @notice Manually override the asset pricing source with a value * @param asset The asset that is being overriden * @param value asset value to return instead of from Chainlink * @param period length of time, in number of blocks, to use manual override */ function emergencySetAssetValue( address asset, uint256 value, uint256 period ) external; /** * @notice Revoke manually set value, allowing usual Chainlink pricing * @param asset address of asset to price */ function emergencyUnsetAssetValue(address asset) external; /** * @notice Manually override the TVL source with a value * @param value TVL to return instead of from Chainlink * @param period length of time, in number of blocks, to use manual override */ function emergencySetTvl(uint256 value, uint256 period) external; /// @notice Revoke manually set value, allowing usual Chainlink pricing function emergencyUnsetTvl() external; /// @notice Check if TVL has active manual override function hasTvlOverride() external view returns (bool); /** * @notice Check if asset has active manual override * @param asset address of the asset * @return `true` if manual override is active */ function hasAssetOverride(address asset) external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IOracleAdapter} from "./IOracleAdapter.sol"; /** * @notice For an `IOracleAdapter` that can be locked and unlocked */ interface ILockingOracle is IOracleAdapter { /// @notice Event fired when using the default lock event DefaultLocked(address locker, uint256 defaultPeriod, uint256 lockEnd); /// @notice Event fired when using a specified lock period event Locked(address locker, uint256 activePeriod, uint256 lockEnd); /// @notice Event fired when changing the default locking period event DefaultLockPeriodChanged(uint256 newPeriod); /// @notice Event fired when unlocking the adapter event Unlocked(); /// @notice Event fired when updating the threshold for stale data event ChainlinkStalePeriodUpdated(uint256 period); /// @notice Block price/value retrieval for the default locking duration function lock() external; /** * @notice Block price/value retrieval for the specified duration. * @param period number of blocks to block retrieving values */ function lockFor(uint256 period) external; /** * @notice Unblock price/value retrieval. Should only be callable * by the Emergency Safe. */ function emergencyUnlock() external; /** * @notice Set the length of time before values can be retrieved. * @param newPeriod number of blocks before values can be retrieved */ function setDefaultLockPeriod(uint256 newPeriod) external; /** * @notice Set the length of time before an agg value is considered stale. * @param chainlinkStalePeriod_ the length of time in seconds */ function setChainlinkStalePeriod(uint256 chainlinkStalePeriod_) external; /** * @notice Get the length of time, in number of blocks, before values * can be retrieved. */ function defaultLockPeriod() external returns (uint256 period); /// @notice Check if the adapter is blocked from retrieving values. function isLocked() external view returns (bool); } pragma solidity ^0.6.0; import "./vendor/SafeMath.sol"; import "./SignedSafeMath.sol"; library Median { using SignedSafeMath for int256; int256 constant INT_MAX = 2**255-1; /** * @notice Returns the sorted middle, or the average of the two middle indexed items if the * array has an even number of elements. * @dev The list passed as an argument isn't modified. * @dev This algorithm has expected runtime O(n), but for adversarially chosen inputs * the runtime is O(n^2). * @param list The list of elements to compare */ function calculate(int256[] memory list) internal pure returns (int256) { return calculateInplace(copy(list)); } /** * @notice See documentation for function calculate. * @dev The list passed as an argument may be permuted. */ function calculateInplace(int256[] memory list) internal pure returns (int256) { require(0 < list.length, "list must not be empty"); uint256 len = list.length; uint256 middleIndex = len / 2; if (len % 2 == 0) { int256 median1; int256 median2; (median1, median2) = quickselectTwo(list, 0, len - 1, middleIndex - 1, middleIndex); return SignedSafeMath.avg(median1, median2); } else { return quickselect(list, 0, len - 1, middleIndex); } } /** * @notice Maximum length of list that shortSelectTwo can handle */ uint256 constant SHORTSELECTTWO_MAX_LENGTH = 7; /** * @notice Select the k1-th and k2-th element from list of length at most 7 * @dev Uses an optimal sorting network */ function shortSelectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) private pure returns (int256 k1th, int256 k2th) { // Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network) // for lists of length 7. Network layout is taken from // http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg uint256 len = hi + 1 - lo; int256 x0 = list[lo + 0]; int256 x1 = 1 < len ? list[lo + 1] : INT_MAX; int256 x2 = 2 < len ? list[lo + 2] : INT_MAX; int256 x3 = 3 < len ? list[lo + 3] : INT_MAX; int256 x4 = 4 < len ? list[lo + 4] : INT_MAX; int256 x5 = 5 < len ? list[lo + 5] : INT_MAX; int256 x6 = 6 < len ? list[lo + 6] : INT_MAX; if (x0 > x1) {(x0, x1) = (x1, x0);} if (x2 > x3) {(x2, x3) = (x3, x2);} if (x4 > x5) {(x4, x5) = (x5, x4);} if (x0 > x2) {(x0, x2) = (x2, x0);} if (x1 > x3) {(x1, x3) = (x3, x1);} if (x4 > x6) {(x4, x6) = (x6, x4);} if (x1 > x2) {(x1, x2) = (x2, x1);} if (x5 > x6) {(x5, x6) = (x6, x5);} if (x0 > x4) {(x0, x4) = (x4, x0);} if (x1 > x5) {(x1, x5) = (x5, x1);} if (x2 > x6) {(x2, x6) = (x6, x2);} if (x1 > x4) {(x1, x4) = (x4, x1);} if (x3 > x6) {(x3, x6) = (x6, x3);} if (x2 > x4) {(x2, x4) = (x4, x2);} if (x3 > x5) {(x3, x5) = (x5, x3);} if (x3 > x4) {(x3, x4) = (x4, x3);} uint256 index1 = k1 - lo; if (index1 == 0) {k1th = x0;} else if (index1 == 1) {k1th = x1;} else if (index1 == 2) {k1th = x2;} else if (index1 == 3) {k1th = x3;} else if (index1 == 4) {k1th = x4;} else if (index1 == 5) {k1th = x5;} else if (index1 == 6) {k1th = x6;} else {revert("k1 out of bounds");} uint256 index2 = k2 - lo; if (k1 == k2) {return (k1th, k1th);} else if (index2 == 0) {return (k1th, x0);} else if (index2 == 1) {return (k1th, x1);} else if (index2 == 2) {return (k1th, x2);} else if (index2 == 3) {return (k1th, x3);} else if (index2 == 4) {return (k1th, x4);} else if (index2 == 5) {return (k1th, x5);} else if (index2 == 6) {return (k1th, x6);} else {revert("k2 out of bounds");} } /** * @notice Selects the k-th ranked element from list, looking only at indices between lo and hi * (inclusive). Modifies list in-place. */ function quickselect(int256[] memory list, uint256 lo, uint256 hi, uint256 k) private pure returns (int256 kth) { require(lo <= k); require(k <= hi); while (lo < hi) { if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) { int256 ignore; (kth, ignore) = shortSelectTwo(list, lo, hi, k, k); return kth; } uint256 pivotIndex = partition(list, lo, hi); if (k <= pivotIndex) { // since pivotIndex < (original hi passed to partition), // termination is guaranteed in this case hi = pivotIndex; } else { // since (original lo passed to partition) <= pivotIndex, // termination is guaranteed in this case lo = pivotIndex + 1; } } return list[lo]; } /** * @notice Selects the k1-th and k2-th ranked elements from list, looking only at indices between * lo and hi (inclusive). Modifies list in-place. */ function quickselectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) internal // for testing pure returns (int256 k1th, int256 k2th) { require(k1 < k2); require(lo <= k1 && k1 <= hi); require(lo <= k2 && k2 <= hi); while (true) { if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) { return shortSelectTwo(list, lo, hi, k1, k2); } uint256 pivotIdx = partition(list, lo, hi); if (k2 <= pivotIdx) { hi = pivotIdx; } else if (pivotIdx < k1) { lo = pivotIdx + 1; } else { assert(k1 <= pivotIdx && pivotIdx < k2); k1th = quickselect(list, lo, pivotIdx, k1); k2th = quickselect(list, pivotIdx + 1, hi, k2); return (k1th, k2th); } } } /** * @notice Partitions list in-place using Hoare's partitioning scheme. * Only elements of list between indices lo and hi (inclusive) will be modified. * Returns an index i, such that: * - lo <= i < hi * - forall j in [lo, i]. list[j] <= list[i] * - forall j in [i, hi]. list[i] <= list[j] */ function partition(int256[] memory list, uint256 lo, uint256 hi) private pure returns (uint256) { // We don't care about overflow of the addition, because it would require a list // larger than any feasible computer's memory. int256 pivot = list[(lo + hi) / 2]; lo -= 1; // this can underflow. that's intentional. hi += 1; while (true) { do { lo += 1; } while (list[lo] < pivot); do { hi -= 1; } while (list[hi] > pivot); if (lo < hi) { (list[lo], list[hi]) = (list[hi], list[lo]); } else { // Let orig_lo and orig_hi be the original values of lo and hi passed to partition. // Then, hi < orig_hi, because hi decreases *strictly* monotonically // in each loop iteration and // - either list[orig_hi] > pivot, in which case the first loop iteration // will achieve hi < orig_hi; // - or list[orig_hi] <= pivot, in which case at least two loop iterations are // needed: // - lo will have to stop at least once in the interval // [orig_lo, (orig_lo + orig_hi)/2] // - (orig_lo + orig_hi)/2 < orig_hi return hi; } } } /** * @notice Makes an in-memory copy of the array passed in * @param list Reference to the array to be copied */ function copy(int256[] memory list) private pure returns(int256[] memory) { int256[] memory list2 = new int256[](list.length); for (uint256 i = 0; i < list.length; i++) { list2[i] = list[i]; } return list2; } } pragma solidity ^0.6.0; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() public { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 128 bit integers. */ library SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b) internal pure returns (uint128) { require(b <= a, "SafeMath: subtraction overflow"); uint128 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint128 a, uint128 b) internal pure returns (uint128) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint128 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint128 a, uint128 b) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint128 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint128 a, uint128 b) internal pure returns (uint128) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 32 bit integers. */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint32 a, uint32 b) internal pure returns (uint32) { require(b <= a, "SafeMath: subtraction overflow"); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 64 bit integers. */ library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } pragma solidity ^0.6.0; interface AggregatorValidatorInterface { function validate( uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer ) external returns (bool); } pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.6.0; library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } /** * @notice Computes average of two signed integers, ensuring that the computation * doesn't overflow. * @dev If the result is not an integer, it is rounded towards zero. For example, * avg(-3, -4) = -3 */ function avg(int256 _a, int256 _b) internal pure returns (int256) { if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) { return add(_a, _b) / 2; } int256 remainder = (_a % 2 + _b % 2) / 2; return add(add(_a / 2, _b / 2), remainder); } } pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // solhint-disable-next-line no-empty-blocks contract CurveAllocationBase3 is CurveAllocationBase { } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap2, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase2 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap2 stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap4, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase4 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap4 stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IZap} from "contracts/lpaccount/Imports.sol"; import { IAssetAllocation, IERC20, IDetailedERC20 } from "contracts/common/Imports.sol"; import {SafeERC20} from "contracts/libraries/Imports.sol"; import { ILiquidityGauge, ITokenMinter } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {CurveZapBase} from "contracts/protocols/curve/common/CurveZapBase.sol"; abstract contract CurveGaugeZapBase is IZap, CurveZapBase { using SafeERC20 for IERC20; address internal constant MINTER_ADDRESS = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address internal immutable LP_ADDRESS; address internal immutable GAUGE_ADDRESS; constructor( address swapAddress, address lpAddress, address gaugeAddress, uint256 denominator, uint256 slippage, uint256 nCoins ) public CurveZapBase(swapAddress, denominator, slippage, nCoins) // solhint-disable-next-line no-empty-blocks { LP_ADDRESS = lpAddress; GAUGE_ADDRESS = gaugeAddress; } function getLpTokenBalance(address account) external view override returns (uint256) { return ILiquidityGauge(GAUGE_ADDRESS).balanceOf(account); } function _depositToGauge() internal override { ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS); uint256 lpBalance = IERC20(LP_ADDRESS).balanceOf(address(this)); IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, 0); IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, lpBalance); liquidityGauge.deposit(lpBalance); } function _withdrawFromGauge(uint256 amount) internal override returns (uint256) { ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS); liquidityGauge.withdraw(amount); //lpBalance return IERC20(LP_ADDRESS).balanceOf(address(this)); } function _claim() internal override { // claim CRV ITokenMinter(MINTER_ADDRESS).mint(GAUGE_ADDRESS); // claim protocol-specific rewards _claimRewards(); } // solhint-disable-next-line no-empty-blocks function _claimRewards() internal virtual {} } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath, SafeERC20} from "contracts/libraries/Imports.sol"; import {IZap} from "contracts/lpaccount/Imports.sol"; import { IAssetAllocation, IDetailedERC20, IERC20 } from "contracts/common/Imports.sol"; import { Curve3poolUnderlyerConstants } from "contracts/protocols/curve/3pool/Constants.sol"; abstract contract CurveZapBase is Curve3poolUnderlyerConstants, IZap { using SafeMath for uint256; using SafeERC20 for IERC20; address internal constant CRV_ADDRESS = 0xD533a949740bb3306d119CC777fa900bA034cd52; address internal immutable SWAP_ADDRESS; uint256 internal immutable DENOMINATOR; uint256 internal immutable SLIPPAGE; uint256 internal immutable N_COINS; constructor( address swapAddress, uint256 denominator, uint256 slippage, uint256 nCoins ) public { SWAP_ADDRESS = swapAddress; DENOMINATOR = denominator; SLIPPAGE = slippage; N_COINS = nCoins; } /// @param amounts array of underlyer amounts function deployLiquidity(uint256[] calldata amounts) external override { require(amounts.length == N_COINS, "INVALID_AMOUNTS"); uint256 totalNormalizedDeposit = 0; for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] == 0) continue; uint256 deposit = amounts[i]; address underlyerAddress = _getCoinAtIndex(i); uint8 decimals = IDetailedERC20(underlyerAddress).decimals(); uint256 normalizedDeposit = deposit.mul(10**uint256(18)).div(10**uint256(decimals)); totalNormalizedDeposit = totalNormalizedDeposit.add( normalizedDeposit ); IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, 0); IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, amounts[i]); } uint256 minAmount = _calcMinAmount(totalNormalizedDeposit, _getVirtualPrice()); _addLiquidity(amounts, minAmount); _depositToGauge(); } /** * @param amount LP token amount * @param index underlyer index */ function unwindLiquidity(uint256 amount, uint8 index) external override { require(index < N_COINS, "INVALID_INDEX"); uint256 lpBalance = _withdrawFromGauge(amount); address underlyerAddress = _getCoinAtIndex(index); uint8 decimals = IDetailedERC20(underlyerAddress).decimals(); uint256 minAmount = _calcMinAmountUnderlyer(lpBalance, _getVirtualPrice(), decimals); _removeLiquidity(lpBalance, index, minAmount); } function claim() external override { _claim(); } function sortedSymbols() public view override returns (string[] memory) { // N_COINS is not available as a public function // so we have to hardcode the number here string[] memory symbols = new string[](N_COINS); for (uint256 i = 0; i < symbols.length; i++) { address underlyerAddress = _getCoinAtIndex(i); symbols[i] = IDetailedERC20(underlyerAddress).symbol(); } return symbols; } function _getVirtualPrice() internal view virtual returns (uint256); function _getCoinAtIndex(uint256 i) internal view virtual returns (address); function _addLiquidity(uint256[] calldata amounts_, uint256 minAmount) internal virtual; function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount ) internal virtual; function _depositToGauge() internal virtual; function _withdrawFromGauge(uint256 amount) internal virtual returns (uint256); function _claim() internal virtual; /** * @dev normalizedDepositAmount the amount in same units as virtual price (18 decimals) * @dev virtualPrice the "price", in 18 decimals, per big token unit of the LP token * @return required minimum amount of LP token (in token wei) */ function _calcMinAmount( uint256 normalizedDepositAmount, uint256 virtualPrice ) internal view returns (uint256) { uint256 idealLpTokenAmount = normalizedDepositAmount.mul(1e18).div(virtualPrice); // allow some slippage/MEV return idealLpTokenAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR); } /** * @param lpTokenAmount the amount in the same units as Curve LP token (18 decimals) * @param virtualPrice the "price", in 18 decimals, per big token unit of the LP token * @param decimals the number of decimals for underlyer token * @return required minimum amount of underlyer (in token wei) */ function _calcMinAmountUnderlyer( uint256 lpTokenAmount, uint256 virtualPrice, uint8 decimals ) internal view returns (uint256) { // TODO: grab LP Token decimals explicitly? uint256 normalizedUnderlyerAmount = lpTokenAmount.mul(virtualPrice).div(1e18); uint256 underlyerAmount = normalizedUnderlyerAmount.mul(10**uint256(decimals)).div( 10**uint256(18) ); // allow some slippage/MEV return underlyerAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR); } function _createErc20AllocationArray(uint256 extraAllocations) internal pure returns (IERC20[] memory) { IERC20[] memory allocations = new IERC20[](extraAllocations.add(4)); allocations[0] = IERC20(CRV_ADDRESS); allocations[1] = IERC20(DAI_ADDRESS); allocations[2] = IERC20(USDC_ADDRESS); allocations[3] = IERC20(USDT_ADDRESS); return allocations; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IOldStableSwap2, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase2 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap2 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import {IOldStableSwap3, ILiquidityGauge} from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase3 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap3 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare( account, stableSwap, gauge, lpToken ); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap3 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap3 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IOldStableSwap4, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase4 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap4 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import { CurveGaugeZapBase } from "contracts/protocols/curve/common/CurveGaugeZapBase.sol"; contract TestCurveZap is CurveGaugeZapBase { string public constant override NAME = "TestCurveZap"; address[] private _underlyers; constructor( address swapAddress, address lpTokenAddress, address liquidityGaugeAddress, uint256 denominator, uint256 slippage, uint256 numOfCoins ) public CurveGaugeZapBase( swapAddress, lpTokenAddress, liquidityGaugeAddress, denominator, slippage, numOfCoins ) // solhint-disable-next-line no-empty-blocks {} function setUnderlyers(address[] calldata underlyers) external { _underlyers = underlyers; } function getSwapAddress() external view returns (address) { return SWAP_ADDRESS; } function getLpTokenAddress() external view returns (address) { return address(LP_ADDRESS); } function getGaugeAddress() external view returns (address) { return GAUGE_ADDRESS; } function getDenominator() external view returns (uint256) { return DENOMINATOR; } function getSlippage() external view returns (uint256) { return SLIPPAGE; } function getNumberOfCoins() external view returns (uint256) { return N_COINS; } function calcMinAmount(uint256 totalAmount, uint256 virtualPrice) external view returns (uint256) { return _calcMinAmount(totalAmount, virtualPrice); } function calcMinAmountUnderlyer( uint256 totalAmount, uint256 virtualPrice, uint8 decimals ) external view returns (uint256) { return _calcMinAmountUnderlyer(totalAmount, virtualPrice, decimals); } function assetAllocations() public view override returns (string[] memory) { string[] memory allocationNames = new string[](1); return allocationNames; } function erc20Allocations() public view override returns (IERC20[] memory) { IERC20[] memory allocations = new IERC20[](0); return allocations; } function _getVirtualPrice() internal view override returns (uint256) { return 1; } function _getCoinAtIndex(uint256 i) internal view override returns (address) { return _underlyers[i]; } function _addLiquidity(uint256[] calldata amounts, uint256 minAmount) internal override // solhint-disable-next-line no-empty-blocks { } function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount // solhint-disable-next-line no-empty-blocks ) internal override {} }
Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./
function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
53,250
./full_match/5/0xd82bAb38045cAf86271b933478bA508E01264DAF/sources/contracts/CDAO.sol
remove limits after token is stable
function removeLimits() external onlyOwner { limitsInEffect = false; }
1,866,423
./full_match/7672/0xFfb937647c9a2ff42556D78FBC6dA2baA8804C98/sources/contracts/Bridge.sol
Set the sentEventId for the contract to start with
function setSentEventId(uint _newId) external onlyOwner { sentEventId = _newId; emit SentEventIdUpdated(_newId); }
16,296,225
./full_match/80001/0x887D63FFa6Ab6e4797E6C89cf8939B3185ea4Fa6/sources/_thirdweb-dev/contracts/base/ERC1155LazyMint.sol
See {IERC1155-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public override(ERC1155) onlyAllowedOperator(from) { super.safeTransferFrom(from, to, id, amount, data); }
867,554
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/Constants.sol"; import { PoolParams } from "./interfaces/Types.sol"; import "./interfaces/IVestingPools.sol"; import "./utils/Claimable.sol"; import "./utils/DefaultOwnable.sol"; import { DefaultOwnerAddress, TokenAddress, VestingPoolsAddress } from "./utils/Linking.sol"; import "./utils/ProxyFactory.sol"; import "./utils/SafeUints.sol"; /** * @title PoolStakes * @notice The contract claims (ERC-20) token from the "VestingPools" contract * and then let "stakeholders" withdraw token amounts prorate to their stakes. * @dev A few copy of this contract (i.e. proxies created via the {createProxy} * method) are supposed to run. Every proxy distributes its own "vesting pool", * so it (the proxy) must be registered with the "VestingPools" contract as the * "wallet" for that "vesting pool". */ contract PoolStakes is Claimable, SafeUints, ProxyFactory, DefaultOwnable, Constants { // @dev "Stake" of a "stakeholder" in the "vesting pool" struct Stake { // token amount allocated for the stakeholder uint96 allocated; // token amount released to the stakeholder so far uint96 released; } /// @notice ID of the vesting pool this contract is the "wallet" for uint16 public poolId; /// @notice Token amount the vesting pool is set to vest uint96 public allocation; /// @notice Token amount allocated from {allocation} to stakeholders so far /// @dev It is the total amount of all {stakes[..].allocated} uint96 public allocated; /// @notice Token amount released to stakeholders so far /// @dev It is the total amount of all {stakes[..].released} uint96 public released; /// @notice Share of vested amount attributable to 1 unit of {allocation} /// @dev Stakeholder "h" may withdraw from the contract this token amount: /// factor/SCALE * stakes[h].allocated - stakes[h].released uint160 public factor; // mapping from stakeholder address to stake mapping(address => Stake) public stakes; event VestingClaimed(uint256 amount); event Released(address indexed holder, uint256 amount); event StakeAdded(address indexed holder, uint256 allocated); event StakeSplit( address indexed holder, uint256 allocated, uint256 released ); /// @notice Returns address of the token being vested function token() external view returns (address) { return address(_getToken()); } /// @notice Returns address of the {VestingPool} smart contract function vestingPools() external view returns (address) { return address(_getVestingPools()); } /// @notice Returns token amount the specified stakeholder may withdraw now function releasableAmount(address holder) external view returns (uint256) { Stake memory stake = _getStake(holder); return _releasableAmount(stake, uint256(factor)); } /// @notice Returns token amount the specified stakeholder may withdraw now /// on top of the {releasableAmount} should {claimVesting} be called function unclaimedShare(address holder) external view returns (uint256) { Stake memory stake = _getStake(holder); uint256 unclaimed = _getVestingPools().releasableAmount(poolId); return (unclaimed * uint256(stake.allocated)) / allocation; } /// @notice Claims vesting to this contract from the vesting pool function claimVesting() external { _claimVesting(); } ///////////////////// //// StakeHolder //// ///////////////////// /// @notice Sends the releasable amount to the message sender /// @dev Stakeholder only may call function withdraw() external { _withdraw(msg.sender); // throws if msg.sender is not a stakeholder } /// @notice Calls {claimVesting} and sends the releasable amount to the message sender /// @dev Stakeholder only may call function claimAndWithdraw() external { _claimVesting(); _withdraw(msg.sender); // throws if msg.sender is not a stakeholder } /// @notice Allots a new stake out of the stake of the message sender /// @dev Stakeholder only may call function splitStake(address newHolder, uint256 newAmount) external { address holder = msg.sender; require(newHolder != holder, "PStakes: duplicated address"); Stake memory stake = _getStake(holder); require(newAmount <= stake.allocated, "PStakes: too large allocated"); uint256 updAmount = uint256(stake.allocated) - newAmount; uint256 updReleased = (uint256(stake.released) * updAmount) / uint256(stake.allocated); stakes[holder] = Stake(_safe96(updAmount), _safe96(updReleased)); emit StakeSplit(holder, updAmount, updReleased); uint256 newVested = uint256(stake.released) - updReleased; stakes[newHolder] = Stake(_safe96(newAmount), _safe96(newVested)); emit StakeSplit(newHolder, newAmount, newVested); } ////////////////// //// Owner //// ////////////////// /// @notice Inits the contract and adds stakes /// @dev Owner only may call on a proxy (but not on the implementation) function addStakes( uint256 _poolId, address[] calldata holders, uint256[] calldata allocations, uint256 unallocated ) external onlyOwner { if (allocation == 0) { _init(_poolId); } else { require(_poolId == poolId, "PStakes: pool mismatch"); } uint256 nEntries = holders.length; require(nEntries == allocations.length, "PStakes: length mismatch"); uint256 updAllocated = uint256(allocated); for (uint256 i = 0; i < nEntries; i++) { _throwZeroHolderAddress(holders[i]); require( stakes[holders[i]].allocated == 0, "PStakes: holder exists" ); require(allocations[i] > 0, "PStakes: zero allocation"); updAllocated += allocations[i]; stakes[holders[i]] = Stake(_safe96(allocations[i]), 0); emit StakeAdded(holders[i], allocations[i]); } require( updAllocated + unallocated == allocation, "PStakes: invalid allocation" ); allocated = _safe96(updAllocated); } /// @notice Calls {claimVesting} and sends releasable tokens to specified stakeholders /// @dev Owner may call only function massWithdraw(address[] calldata holders) external onlyOwner { _claimVesting(); for (uint256 i = 0; i < holders.length; i++) { _withdraw(holders[i]); } } /// @notice Withdraws accidentally sent token from this contract /// @dev Owner may call only function claimErc20( address claimedToken, address to, uint256 amount ) external onlyOwner nonReentrant { IERC20 vestedToken = IERC20(address(_getToken())); if (claimedToken == address(vestedToken)) { uint256 balance = vestedToken.balanceOf(address(this)); require( balance - amount >= allocation - released, "PStakes: too big amount" ); } _claimErc20(claimedToken, to, amount); } /// @notice Removes the contract from blockchain when tokens are released /// @dev Owner only may call on a proxy (but not on the implementation) function removeContract() external onlyOwner { // avoid accidental removing of the implementation _throwImplementation(); require(allocation == released, "PStakes: unpaid stakes"); IERC20 vestedToken = IERC20(address(_getToken())); uint256 balance = vestedToken.balanceOf(address(this)); require(balance == 0, "PStakes: non-zero balance"); selfdestruct(payable(msg.sender)); } ////////////////// //// Internal //// ////////////////// /// @dev Returns the address of the default owner // (declared `view` rather than `pure` to facilitate testing) function _defaultOwner() internal view virtual override returns (address) { return address(DefaultOwnerAddress); } /// @dev Returns Token contract address // (declared `view` rather than `pure` to facilitate testing) function _getToken() internal view virtual returns (IERC20) { return IERC20(address(TokenAddress)); } /// @dev Returns VestingPools contract address // (declared `view` rather than `pure` to facilitate testing) function _getVestingPools() internal view virtual returns (IVestingPools) { return IVestingPools(address(VestingPoolsAddress)); } /// @dev Returns the stake of the specified stakeholder reverting on errors function _getStake(address holder) internal view returns (Stake memory) { _throwZeroHolderAddress(holder); Stake memory stake = stakes[holder]; require(stake.allocated != 0, "PStakes: unknown stake"); return stake; } /// @notice Initialize the contract /// @dev May be called on a proxy only (but not on the implementation) function _init(uint256 _poolId) internal { _throwImplementation(); require(_poolId < 2**16, "PStakes:unsafePoolId"); IVestingPools pools = _getVestingPools(); address wallet = pools.getWallet(_poolId); require(wallet == address(this), "PStakes:invalidPool"); PoolParams memory pool = pools.getPool(_poolId); require(pool.sAllocation != 0, "PStakes:zeroPool"); poolId = uint16(_poolId); allocation = _safe96(uint256(pool.sAllocation) * SCALE); } /// @dev Returns amount that may be released for the given stake and factor function _releasableAmount(Stake memory stake, uint256 _factor) internal pure returns (uint256) { uint256 share = (_factor * uint256(stake.allocated)) / SCALE; if (share > stake.allocated) { // imprecise division safeguard share = uint256(stake.allocated); } return share - uint256(stake.released); } /// @dev Claims vesting to this contract from the vesting pool function _claimVesting() internal { // (reentrancy attack impossible - known contract called) uint256 justVested = _getVestingPools().release(poolId, 0); factor += uint160((justVested * SCALE) / uint256(allocation)); emit VestingClaimed(justVested); } /// @dev Sends the releasable amount of the specified placeholder function _withdraw(address holder) internal { Stake memory stake = _getStake(holder); uint256 releasable = _releasableAmount(stake, uint256(factor)); require(releasable > 0, "PStakes: nothing to withdraw"); stakes[holder].released = _safe96(uint256(stake.released) + releasable); released = _safe96(uint256(released) + releasable); // (reentrancy attack impossible - known contract called) require(_getToken().transfer(holder, releasable), "PStakes:E1"); emit Released(holder, releasable); } function _throwZeroHolderAddress(address holder) private pure { require(holder != address(0), "PStakes: zero holder address"); } } // 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; contract Constants { // $ZKP token max supply uint256 internal constant MAX_SUPPLY = 1e27; // Scaling factor in token amount calculations uint256 internal constant SCALE = 1e12; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev To save gas, params are packed to fit into a single storage slot. * Some amounts are scaled (divided) by {SCALE} - note names starting with * the letter "s" (stands for "scaled") followed by a capital letter. */ struct PoolParams { // if `true`, allocation gets pre-minted, otherwise minted when vested bool isPreMinted; // if `true`, the owner may change {start} and {duration} bool isAdjustable; // (UNIX) time when vesting starts uint32 start; // period in days (since the {start}) of vesting uint16 vestingDays; // scaled total amount to (ever) vest from the pool uint48 sAllocation; // out of {sAllocation}, amount (also scaled) to be unlocked on the {start} uint48 sUnlocked; // amount vested from the pool so far (without scaling) uint96 vested; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { PoolParams } from "./Types.sol"; interface IVestingPools { /** * @notice Returns Token address. */ function token() external view returns (address); /** * @notice Returns the wallet address of the specified pool. */ function getWallet(uint256 poolId) external view returns (address); /** * @notice Returns parameters of the specified pool. */ function getPool(uint256 poolId) external view returns (PoolParams memory); /** * @notice Returns the amount that may be vested now from the given pool. */ function releasableAmount(uint256 poolId) external view returns (uint256); /** * @notice Returns the amount that has been vested from the given pool */ function vestedAmount(uint256 poolId) external view returns (uint256); /** * @notice Vests the specified amount from the given pool to the pool wallet. * If the amount is zero, it vests the entire "releasable" amount. * @dev Pool wallet may call only. * @return released - Amount released. */ function release(uint256 poolId, uint256 amount) external returns (uint256 released); /** * @notice Vests the specified amount from the given pool to the given address. * If the amount is zero, it vests the entire "releasable" amount. * @dev Pool wallet may call only. * @return released - Amount released. */ function releaseTo( uint256 poolId, address account, uint256 amount ) external returns (uint256 released); /** * @notice Updates the wallet for the given pool. * @dev (Current) wallet may call only. */ function updatePoolWallet(uint256 poolId, address newWallet) external; /** * @notice Adds new vesting pools with given wallets and parameters. * @dev Owner may call only. */ function addVestingPools( address[] memory wallets, PoolParams[] memory params ) external; /** * @notice Update `start` and `duration` for the given pool. * @param start - new (UNIX) time vesting starts at * @param vestingDays - new period in days, when vesting lasts * @dev Owner may call only. */ function updatePoolTime( uint256 poolId, uint32 start, uint16 vestingDays ) external; /// @notice Emitted on an amount vesting. event Released(uint256 indexed poolId, address to, uint256 amount); /// @notice Emitted on a pool wallet update. event WalletUpdated(uint256 indexedpoolId, address indexed newWallet); /// @notice Emitted on a new pool added. event PoolAdded( uint256 indexed poolId, address indexed wallet, uint256 allocation ); /// @notice Emitted on a pool params update. event PoolUpdated( uint256 indexed poolId, uint256 start, uint256 vestingDays ); } // SPDX-License-Identifier: MIT pragma solidity >0.8.0; /** * @title Claimable * @notice It withdraws accidentally sent tokens from this contract. * @dev It provides reentrancy guard. The code borrowed from openzeppelin-contracts. * Unlike original code, this version does not require `constructor` call. */ contract Claimable { bytes4 private constant SELECTOR_TRANSFER = bytes4(keccak256(bytes("transfer(address,uint256)"))); uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _reentrancyStatus; /// @dev Withdraws ERC20 tokens from this contract /// (take care of reentrancy attack risk mitigation) function _claimErc20( address token, address to, uint256 amount ) internal { // solhint-disable avoid-low-level-calls (bool success, bytes memory data) = token.call( abi.encodeWithSelector(SELECTOR_TRANSFER, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "claimErc20: TRANSFER_FAILED" ); } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_reentrancyStatus != _ENTERED, "claimErc20: reentrant call"); // Any calls to nonReentrant after this point will fail _reentrancyStatus = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _reentrancyStatus = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * Inspired and borrowed by/from the openzeppelin/contracts` {Ownable}. * Unlike openzeppelin` version: * - by default, the owner account is the one returned by the {_defaultOwner} * function, but not the deployer address; * - this contract has no constructor and may run w/o initialization; * - the {renounceOwnership} function removed. * * 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. * The child contract must define the {_defaultOwner} function. */ abstract contract DefaultOwnable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev Returns the current owner address, if it's defined, or the default owner address otherwise. function owner() public view virtual returns (address) { return _owner == address(0) ? _defaultOwner() : _owner; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /// @dev Transfers ownership of the contract to the `newOwner`. The owner can only call. function transferOwnership(address newOwner) external virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ function _defaultOwner() internal view virtual returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This file contains fake libs just for static linking. * These fake libs' code is assumed to never run. * On compilation of dependant contracts, instead of fake libs addresses, * indicate addresses of deployed real contracts (or accounts). */ /// @dev Address of the ZKPToken contract ('../ZKPToken.sol') instance library TokenAddress { function neverCallIt() external pure { revert("FAKE"); } } /// @dev Address of the VestingPools ('../VestingPools.sol') instance library VestingPoolsAddress { function neverCallIt() external pure { revert("FAKE"); } } /// @dev Address of the PoolStakes._defaultOwner // (NB: if it's not a multisig, transfer ownership to a Multisig contract) library DefaultOwnerAddress { function neverCallIt() external pure { revert("FAKE"); } } // SPDX-License-Identifier: MIT // solhint-disable no-inline-assembly pragma solidity >0.8.0; /** * @title ProxyFactory * @notice It "clones" the (child) contract deploying EIP-1167 proxies * @dev Generated proxies: * - being the EIP-1167 proxy, DELEGATECALL this (child) contract * - support EIP-1967 specs for the "implementation slot" * (it gives explorers/wallets more chances to "understand" it's a proxy) */ abstract contract ProxyFactory { // Storage slot that the EIP-1967 defines for the "implementation" address // (`uint256(keccak256('eip1967.proxy.implementation')) - 1`) bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /// @dev Emits when a new proxy is created event NewProxy(address proxy); /** * @notice Returns `true` if called on a proxy (rather than implementation) */ function isProxy() external view returns (bool) { return _isProxy(); } /** * @notice Deploys a new proxy instance that DELEGATECALLs this contract * @dev Must be called on the implementation (reverts if a proxy is called) */ function createProxy() external returns (address proxy) { _throwProxy(); // CREATE an EIP-1167 proxy instance with the target being this contract bytes20 target = bytes20(address(this)); assembly { let initCode := mload(0x40) mstore( initCode, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(initCode, 0x14), target) mstore( add(initCode, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) // note, 0x37 (55 bytes) is the init bytecode length // while the deployed bytecode length is 0x2d (45 bytes) only proxy := create(0, initCode, 0x37) } // Write this contract address into the proxy' "implementation" slot // (reentrancy attack impossible - this contract called) ProxyFactory(proxy).initProxy(address(this)); emit NewProxy(proxy); } /** * @dev Writes given address into the "implementation" slot of a new proxy. * !!! It MUST (and may only) be called: * - via the implementation instance with the {createProxy} method * - on a newly deployed proxy only * It reverts if called on the implementation or on initialized proxies. */ function initProxy(address impl) external { _throwImplementation(); require( _getImplementation() == address(0), "ProxyFactory:ALREADY_INITIALIZED" ); // write into the "implementation" slot bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, impl) } } /// @dev Returns true if called on a proxy instance function _isProxy() internal view virtual returns (bool) { // for a DELEGATECALLed contract, `this` and `extcodesize` // are the address and the code size of the calling contract // (for a CALLed contract, they are ones of that called contract) uint256 _size; address _this = address(this); assembly { _size := extcodesize(_this) } // shall be the same as the one the `createProxy` generates return _size == 45; } /// @dev Returns the address stored in the "implementation" slot function _getImplementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /// @dev Throws if called on the implementation function _throwImplementation() internal view { require(_isProxy(), "ProxyFactory:IMPL_CALLED"); } /// @dev Throws if called on a proxy function _throwProxy() internal view { require(!_isProxy(), "ProxyFactory:PROXY_CALLED"); } } // SPDX-License-Identifier: MIT pragma solidity >0.8.0; /** * @title SafeUints * @notice Util functions which throws if a uint256 can't fit into smaller uints. */ contract SafeUints { // @dev Checks if the given uint256 does not overflow uint96 function _safe96(uint256 n) internal pure returns (uint96) { require(n < 2**96, "VPools: Unsafe96"); return uint96(n); } }
Initialize the contract May be called on a proxy only (but not on the implementation)
function _init(uint256 _poolId) internal { _throwImplementation(); require(_poolId < 2**16, "PStakes:unsafePoolId"); IVestingPools pools = _getVestingPools(); address wallet = pools.getWallet(_poolId); require(wallet == address(this), "PStakes:invalidPool"); PoolParams memory pool = pools.getPool(_poolId); require(pool.sAllocation != 0, "PStakes:zeroPool"); poolId = uint16(_poolId); allocation = _safe96(uint256(pool.sAllocation) * SCALE); }
12,762,089
./partial_match/1/0x518d26405Ca06435227BB3E8de567a16fA8F8125/sources/Users/petr/ankr/aws-smart-contracts/legacy/contracts/upgrades/FETH_R20.sol
make sure user has enough balance calc swap fee
function unlockShares(uint256 shares) external { address account = address(msg.sender); require(_shares[account] >= shares, "insufficient balance"); uint256 fee = shares.mul(_swapFeeRatio).div(1e18); if (msg.sender == _swapFeeOperator) { fee = 0; } uint256 sharesWithFee = shares.sub(fee); emit UnlockedV2(account, sharesWithFee, fee); }
2,884,020
/** *Submitted for verification at Etherscan.io on 2021-03-12 */ // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <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 () { 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; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/utils/Counters.sol pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: contracts/DeekHash.sol pragma solidity >=0.7.0 <0.8.0; contract DeekHash is ERC721, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter private _tokenIds; uint256 public constant INITIAL_REG_DEEKS_CAP = 10000; uint256 private _saleBeginTime = 1615561200; // 12 March 2021, 10:00 GMT-5 (NY time) uint256 private _regularDeeksCap = INITIAL_REG_DEEKS_CAP; uint256 private _superDeeksBorn = 0; address private safeAddress; struct Deek { string name; string dna; } Deek[] private Deeks; /* * Mapping for passphrases hashes for superDeeks * True means active , not redeemed yet * False would mean promocode is invalid or already redeemed */ mapping (bytes32 => bool) private superHashToRedeemStatus; constructor(address _safeAddress, string memory myBase) ERC721("DEEKHASH", "DKHSH") { _setBaseURI(myBase); safeAddress = _safeAddress; } /** * @dev Sets new maximum for the Regular Deeks to be born. It can't be more than INITIAL_REG_DEEKS_CAP */ function setNewRegularDeeksCap(uint256 _newRegularDeeksCap) public onlyOwner { require(_newRegularDeeksCap <= INITIAL_REG_DEEKS_CAP, "Regular Deeks capacity cant be higher than INITIAL_REG_DEEKS_CAP"); _regularDeeksCap = _newRegularDeeksCap; } /************************************************************************* * REGULAR DEEKS GENESIS BLOCK *************************************************************************/ /** * @dev Gets current Deek price. Hard borders are incremented by superHeroesBorn * in case some superheroes will born before sale ends */ function getDeekPrice() public view returns (uint256) { require(block.timestamp >= _saleBeginTime, "Too early, guys"); require(totalSupply() < getTotalCurrCapacity(), "All Deeks were born"); uint currentSupply = totalSupply(); if (currentSupply >= 8400 + getSuperDeeksBorn()) { return 500000000000000000; // 8400 - 9999 0.5 ETH } else if (currentSupply >= 5000 + getSuperDeeksBorn()) { return 400000000000000000; // 5000 - 8399 0.4 ETH } else if (currentSupply >= 1600 + getSuperDeeksBorn()) { return 300000000000000000; // 1600 - 4999 0.3 ETH } else if (currentSupply >= 250 + getSuperDeeksBorn()) { return 200000000000000000; // 250 - 1599 0.2 ETH } else { return 100000000000000000; // 0 - 249 0.1 ETH } } /** * @dev Mints a token * @param _name = string to hash by user from frontend * @param _dna = Deek's dna generated by frontend from _name hash */ function createDeek(string memory _name, string memory _dna) public payable returns (uint256) { require(totalSupply() < getTotalCurrCapacity(), "All Deeks were born"); require(msg.value == getDeekPrice(), "Ether value sent is not correct"); // set the tokenId for token we are going to mint uint256 newItemId = _tokenIds.current(); _safeMint(msg.sender, newItemId); // we fill Deek name and dna which are going to be stored on-chain Deeks.push(Deek(_name, _dna)); // increment counter. _tokenIds.increment(); return newItemId; } /************************************************************************* * SUPERDEEKS GENESIS BLOCK *************************************************************************/ /** * @dev Adds a hash of a promocode to get the SuperDeek */ function addSuperHash(string memory _promoCode) external onlyOwner { superHashToRedeemStatus[keccak256(abi.encodePacked(_promoCode))] = true; } function removeSuperHash(string memory _promoCode) external onlyOwner { superHashToRedeemStatus[keccak256(abi.encodePacked(_promoCode))] = false; } /** * @dev Checks if there is a hash corresponding to a user entered promocode in * the array of the correct promocode hashes */ function isPromoCodeValid(string memory _userPromoCode) internal view returns(bool) { bool _superDeekValid = superHashToRedeemStatus[keccak256(abi.encodePacked(_userPromoCode))]; return (_superDeekValid); } /** * @dev Mints a superDeek */ function createSuperDeek (string memory _name, string memory _dna, string memory _userPromoCode) public returns (uint256) { require(block.timestamp >= _saleBeginTime, "Too early, guys"); require(isPromoCodeValid(_userPromoCode), "Your spell is not valid or already used"); // set the tokenId for token we are going to mint uint256 newItemId = _tokenIds.current(); _safeMint(msg.sender, newItemId); // we fill Deek name and dna which are going to be stored on-chain Deeks.push(Deek(_name, _dna)); // increment counter and _superDeeksBorn value _tokenIds.increment(); _superDeeksBorn = _superDeeksBorn.add(1); // mark Promocode as not active superHashToRedeemStatus[keccak256(abi.encodePacked(_userPromoCode))] = false; return newItemId; } /************************************************************************** * Working with URIs **************************************************************************/ /** * @dev sets new base URI in case old is broken * baseURI is an URI for the json with the metadata for a token */ function _setNewBaseURI(string memory _newBaseURI) external onlyOwner { _setBaseURI(_newBaseURI); } /* * baseURI() function which returns private _baseURI variable is defined in ERC721 */ /*************************************************************************** * Views block ***************************************************************************/ function getRegularDeeksCap() public view returns(uint256) { return _regularDeeksCap; } function getSuperDeeksBorn() public view returns(uint256) { return _superDeeksBorn; } function getTotalCurrCapacity() public view returns (uint256) { return (getRegularDeeksCap()).add(getSuperDeeksBorn()); } /** * @dev get name by tokenId */ function nameByTokenId(uint256 _tokenId) public view returns(string memory) { return Deeks[_tokenId].name; } /** * @dev get dna by tokenId */ function dnaByTokenId(uint256 _tokenId) public view returns(string memory) { return Deeks[_tokenId].dna; } /** * @dev returns tokenId for the NEXT token to be minted */ function getNextTokenId() public view returns(uint256) { return _tokenIds.current(); } /** * @dev returns safeAccount address */ function getSafeAccountAddress() onlyOwner public view returns(address) { return safeAddress; } /*************************************************************************** * Finances block ***************************************************************************/ /** * @dev Check contract balance */ function getContractBalance() onlyOwner public view returns(uint256) { uint256 balance = address(this).balance; return balance; } /** * @dev Withdraw ether from this contract */ function withdraw() onlyOwner public { uint256 balance = address(this).balance; msg.sender.transfer(balance); } /** * @dev Withdraw to the SafeAddress */ function withdrawToSafeAddress() onlyOwner public { uint256 balance = address(this).balance; payable(safeAddress).transfer(balance); } /*************************************************************************** * Sale start time management block ***************************************************************************/ /** * @dev Check sale start time */ function getSaleStartTime() public view returns(uint256) { return _saleBeginTime; } /** * @dev Set sale start time */ function setSaleStartTime(uint256 _newSaleStartTime) onlyOwner public { _saleBeginTime = _newSaleStartTime; } }
Mints a token _name = string to hash by user from frontend _dna = Deek's dna generated by frontend from _name hash/ set the tokenId for token we are going to mint we fill Deek name and dna which are going to be stored on-chain increment counter.
function createDeek(string memory _name, string memory _dna) public payable returns (uint256) { require(totalSupply() < getTotalCurrCapacity(), "All Deeks were born"); require(msg.value == getDeekPrice(), "Ether value sent is not correct"); uint256 newItemId = _tokenIds.current(); _safeMint(msg.sender, newItemId); Deeks.push(Deek(_name, _dna)); _tokenIds.increment(); return newItemId; }
6,796,373
pragma solidity ^0.5.0; //pragma solidity >=0.4.0 <0.6.0; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/ShoppingBasket.sol"; contract TestShoppingBasket { ShoppingBasket shoppingBasket; uint amountOfCollectedTokens; function beforeEach() public { shoppingBasket = ShoppingBasket(DeployedAddresses.ShoppingBasket()); shoppingBasket = new ShoppingBasket(); amountOfCollectedTokens = shoppingBasket.addItem(1, "Carrot", 14, 80, 10, "img/carrot.jpg"); } function afterEach() public { shoppingBasket.addItem(1,"", 0, 0, 0, ""); shoppingBasket.purchaseItems(); } function testItemId() public { (uint id,,,,,) = shoppingBasket.getItemAttributes(1); uint expected = 1; Assert.equal(id, expected, "Value of ID has to be 1!"); } function testItemName() public { (,string memory name,,,,) = shoppingBasket.getItemAttributes(1); string memory expected = "Carrot"; Assert.equal(name, expected, "Name of item has to be Carrot!"); } function testItemQuantity() public { (,,uint quantity,,,) = shoppingBasket.getItemAttributes(1); uint expected = 14; Assert.equal(quantity, expected, "Value of quantity has to 4!"); } function testItemPrice() public { (,,,uint price,,) = shoppingBasket.getItemAttributes(1); uint expected = 80; Assert.equal(price, expected, "Value of price has to be 0,80 EUR!"); } function testItemEcoFootprint() public { (,,,,uint ecoFootprint,) = shoppingBasket.getItemAttributes(1); uint expected = 10; Assert.equal(ecoFootprint, expected, "Eco Footprint has to 10!"); } function testItemImgRef() public { (,,,,,string memory imgRef) = shoppingBasket.getItemAttributes(1); string memory expected = "img/carrot.jpg"; Assert.equal(imgRef, expected, "Name of item has to be Carrot!"); } function testAddItemToBasket() public { uint expected = 11; Assert.equal(amountOfCollectedTokens, expected, "Amount of collected tokens has to be 11!"); } function testAddMultipleItemsToBasket() public { uint tokenAmount = 0; tokenAmount = shoppingBasket.addItem(1, "Banana", 4, 60, 50, "/img/banana.jpg"); tokenAmount = shoppingBasket.addItem(2, "Cucumber", 2, 100, 80, "img/cucumber.jpg"); tokenAmount = shoppingBasket.addItem(3, "Apple", 3, 90, 90, "/img/apple.jpg"); //tokenAmount = shoppingBasket.purchaseItems(); uint expected = 63; Assert.equal(tokenAmount, expected, "Token amount has to be 63."); } function testListOfBasketItemIds() public { uint tokenAmount = 0; tokenAmount = shoppingBasket.addItem(1, "Banana", 4, 60, 50, "/img/banana.jpg"); tokenAmount = shoppingBasket.addItem(2, "Cucumber", 2, 100, 80, "img/cucumber.jpg"); tokenAmount = shoppingBasket.addItem(3, "Apple", 3, 90, 90, "/img/apple.jpg"); //tokenAmount = shoppingBasket.purchaseItems(); uint[64] memory listOfBasketItemIds = shoppingBasket.getListOfBasketItemIds(); uint expected1 = 1; Assert.equal(listOfBasketItemIds[1], expected1, "Value of has to be 1."); uint expected2 = 2; Assert.equal(listOfBasketItemIds[2], expected2, "Value of has to be 2."); uint expected3 = 3; Assert.equal(listOfBasketItemIds[3], expected3, "Value of has to be 3."); } }
tokenAmount = shoppingBasket.purchaseItems();
function testAddMultipleItemsToBasket() public { uint tokenAmount = 0; tokenAmount = shoppingBasket.addItem(1, "Banana", 4, 60, 50, "/img/banana.jpg"); tokenAmount = shoppingBasket.addItem(2, "Cucumber", 2, 100, 80, "img/cucumber.jpg"); tokenAmount = shoppingBasket.addItem(3, "Apple", 3, 90, 90, "/img/apple.jpg"); uint expected = 63; Assert.equal(tokenAmount, expected, "Token amount has to be 63."); }
13,005,597
/*** * ██████╗ ███████╗ ██████╗ ██████╗ * ██╔══██╗██╔════╝██╔════╝ ██╔═══██╗ * ██║ ██║█████╗ ██║ ███╗██║ ██║ * ██║ ██║██╔══╝ ██║ ██║██║ ██║ * ██████╔╝███████╗╚██████╔╝╚██████╔╝ * ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ * * https://dego.finance * MIT License * =========== * * Copyright (c) 2020 dego * * 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 */ // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/drafts/Counters.sol pragma solidity ^0.5.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: @openzeppelin/contracts/token/ERC721/ERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } // File: contracts/interface/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint amount) external; /** * @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/library/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/library/Governance.sol pragma solidity ^0.5.0; contract Governance { address public _governance; constructor() public { _governance = tx.origin; } event GovernanceTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyGovernance { require(msg.sender == _governance, "not governance"); _; } function setGovernance(address governance) public onlyGovernance { require(governance != address(0), "new governance the zero address"); emit GovernanceTransferred(_governance, governance); _governance = governance; } } // File: contracts/interface/IPool.sol pragma solidity ^0.5.0; interface IPool { function totalSupply( ) external view returns (uint256); function balanceOf( address player ) external view returns (uint256); } // File: contracts/interface/IGegoToken.sol pragma solidity ^0.5.0; contract IGegoToken is IERC721 { struct GegoV1 { uint256 id; uint256 grade; uint256 quality; uint256 amount; uint256 resId; address author; uint256 createdTime; uint256 blockNum; } struct Gego { uint256 id; uint256 grade; uint256 quality; uint256 amount; uint256 resBaseId; uint256 tLevel; uint256 ruleId; uint256 nftType; address author; address erc20; uint256 createdTime; uint256 blockNum; } function mint(address to, uint256 tokenId) external returns (bool) ; function burn(uint256 tokenId) external; } // File: contracts/interface/IGegoFactoryV2.sol pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; interface IGegoFactoryV2 { function getGego(uint256 tokenId) external view returns ( uint256 grade, uint256 quality, uint256 amount, uint256 resBaseId, uint256 tLevel, uint256 ruleId, uint256 nftType, address author, address erc20, uint256 createdTime, uint256 blockNum ); function getGegoStruct(uint256 tokenId) external view returns (IGegoToken.Gego memory gego); function burn(uint256 tokenId) external returns ( bool ); function isRulerProxyContract(address proxy) external view returns ( bool ); } // File: contracts/reward/NFTRewardKCS.sol pragma solidity ^0.5.0; // gego contract NFTRewardKCS is IPool,Governance { using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public _rewardToken = IERC20(0x0); IGegoFactoryV2 public _gegoFactory = IGegoFactoryV2(0x0); IGegoToken public _gegoToken = IGegoToken(0x0); uint256 public _startTime1 = now + 365 days; uint256 public FINISHDURATION1 = 7 days; uint256 public _stageFinish1 = 0; uint256 public _rewardRate1 = 0; bool public _hasStart1 = false; uint256 public _startTime2 = now + 365 days; uint256 public FINISHDURATION2 = 7 days; uint256 public _stageFinish2 = 0; uint256 public _rewardRate2 = 0; bool public _hasStart2 = false; uint256 public _initReward = 0; uint256 public _ruleId = 0; uint256 public _nftType = 0; uint256 public _lastUpdateTime; uint256 public _rewardPerTokenStored; mapping(address => uint256) public _userRewardPerTokenPaid; mapping(address => uint256) public _rewards; uint256 public _fixRateBase = 100000; uint256 public _totalWeight; mapping(address => uint256) public _weightBalances; mapping(address => uint256[]) public _playerGego; mapping(uint256 => uint256) public _gegoMapIndex; event RewardAdded(uint256 reward); event StakedGEGO(address indexed user, uint256 amount); event WithdrawnGego(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event NFTReceived(address operator, address from, uint256 tokenId, bytes data); event SetStartTime(uint256 startTime); event FinishReward(uint256 reward); event StartReward(uint256 reward); modifier updateReward(address account) { _rewardPerTokenStored = rewardPerToken(); _lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { _rewards[account] = earned(account); _userRewardPerTokenPaid[account] = _rewardPerTokenStored; } _; } modifier checkOnRewardTime() { require((block.timestamp > _startTime1 && block.timestamp <= _stageFinish1)||(block.timestamp > _startTime2 && block.timestamp <= _stageFinish2), "not on stage"); _; } constructor(address rewardToken, address gegoToken, address gegoFactory, uint256 ruleId, uint256 nftType) public { _rewardToken = IERC20(rewardToken); _gegoToken = IGegoToken(gegoToken); _gegoFactory = IGegoFactoryV2(gegoFactory); _ruleId = ruleId; _nftType = nftType; } function totalSupply() public view returns (uint256) { return _totalWeight; } function balanceOf(address account) public view returns (uint256) { return _weightBalances[account]; } /* Fee collection for any other token */ function seize(IERC20 token, uint256 amount) external { require(token != _rewardToken, "reward"); token.safeTransfer(_governance, amount); } /* Fee collection for any other token */ function seizeErc721(IERC721 token, uint256 tokenId) external { require(token != _gegoToken, "reward"); token.safeTransferFrom(address(this), _governance, tokenId); } // fix function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return _rewardPerTokenStored; } if (_lastUpdateTime <= _stageFinish1) { return _rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(_lastUpdateTime) .mul(_rewardRate1) .mul(1e18) .div(totalSupply()) ); }else{ return _rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(_lastUpdateTime) .mul(_rewardRate2) .mul(1e18) .div(totalSupply()) ); } } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(_userRewardPerTokenPaid[account])) .div(1e18) .add(_rewards[account]); } //the grade is a number between 1-6 //the quality is a number between 1-10000 /* 1 quality 1.1+ 0.1*quality/5000 2 quality 1.2+ 0.1*(quality-5000)/3000 3 quality 1.3+ 0.1*(quality-8000/1000 4 quality 1.4+ 0.2*(quality-9000)/800 5 quality 1.6+ 0.2*(quality-9800)/180 6 quality 1.8+ 0.2*(quality-9980)/20 */ function getFixRate(uint256 grade,uint256 quality) public pure returns (uint256){ require(grade > 0 && grade <7, "the gego not token"); uint256 unfold = 0; if( grade == 1 ){ unfold = quality*10000/5000; return unfold.add(110000); }else if( grade == 2){ unfold = quality.sub(5000)*10000/3000; return unfold.add(120000); }else if( grade == 3){ unfold = quality.sub(8000)*10000/1000; return unfold.add(130000); }else if( grade == 4){ unfold = quality.sub(9000)*20000/800; return unfold.add(140000); }else if( grade == 5){ unfold = quality.sub(9800)*20000/180; return unfold.add(160000); }else{ unfold = quality.sub(9980)*20000/20; return unfold.add(180000); } } function getStakeInfo( uint256 gegoId ) public view returns ( uint256 stakeRate, uint256 amount,uint256 ruleId,uint256 nftType){ uint256 grade; uint256 quality; (grade,quality,amount, , ,ruleId, nftType, , , , ) = _gegoFactory.getGego(gegoId); require(amount > 0,"the gego not token"); stakeRate = getFixRate(grade,quality); } // stake GEGO function stakeGego(uint256 gegoId) public updateReward(msg.sender) checkOnRewardTime { uint256[] storage gegoIds = _playerGego[msg.sender]; if (gegoIds.length == 0) { gegoIds.push(0); _gegoMapIndex[0] = 0; } gegoIds.push(gegoId); _gegoMapIndex[gegoId] = gegoIds.length - 1; uint256 stakeRate; uint256 ercAmount; uint256 ruleId; uint256 nftType; (stakeRate, ercAmount, ruleId, nftType) = getStakeInfo(gegoId); require(ruleId == _ruleId, "Not conforming to the rules"); require(nftType == _nftType, "Not conforming to the rules"); if(ercAmount > 0){ uint256 stakeWeight = stakeRate.mul(ercAmount).div(_fixRateBase); _weightBalances[msg.sender] = _weightBalances[msg.sender].add(stakeWeight); _totalWeight = _totalWeight.add(stakeWeight); } _gegoToken.safeTransferFrom(msg.sender, address(this), gegoId); emit StakedGEGO(msg.sender, gegoId); } function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4) { // if(_hasStart1 == false && _hasStart2 == false) { // return 0; // } emit NFTReceived(operator, from, tokenId, data); return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } function withdrawGego(uint256 gegoId) public updateReward(msg.sender) { require(gegoId > 0, "the gegoId error"); uint256[] memory gegoIds = _playerGego[msg.sender]; uint256 gegoIndex = _gegoMapIndex[gegoId]; require(gegoIds[gegoIndex] == gegoId, "not gegoId owner"); uint256 gegoArrayLength = gegoIds.length-1; uint256 tailId = gegoIds[gegoArrayLength]; _playerGego[msg.sender][gegoIndex] = tailId; _playerGego[msg.sender][gegoArrayLength] = 0; _playerGego[msg.sender].length--; _gegoMapIndex[tailId] = gegoIndex; _gegoMapIndex[gegoId] = 0; uint256 stakeRate; uint256 ercAmount; (stakeRate, ercAmount,,) = getStakeInfo(gegoId); uint256 stakeWeight = stakeRate.mul(ercAmount).div(_fixRateBase); _weightBalances[msg.sender] = _weightBalances[msg.sender].sub(stakeWeight); _totalWeight = _totalWeight.sub(stakeWeight); _gegoToken.safeTransferFrom(address(this), msg.sender, gegoId); emit WithdrawnGego(msg.sender, gegoId); } function withdraw() public { uint256[] memory gegoId = _playerGego[msg.sender]; for (uint8 index = 1; index < gegoId.length; index++) { if (gegoId[index] > 0) { withdrawGego(gegoId[index]); } } } function getPlayerIds( address account ) public view returns( uint256[] memory gegoId ) { gegoId = _playerGego[account]; } function exit() external { withdraw(); getReward(); } function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { _rewards[msg.sender] = 0; _rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function lastTimeRewardApplicable() private view returns (uint256) { if (block.timestamp <= _stageFinish1) { return Math.min(block.timestamp, _stageFinish1); } else if ( _stageFinish1 < block.timestamp && block.timestamp <= _startTime2) { return _stageFinish1; } else { return Math.min(block.timestamp, _stageFinish2); } } //for extra reward function notifyRewardAmount(uint256 reward,uint256 duration, uint256 stage) external onlyGovernance updateReward(address(0)) { if (stage == 1) { require(_hasStart1 == false, "stage1 has started"); FINISHDURATION1 = duration; }else{ require(_hasStart2 == false, "stage2 has started"); FINISHDURATION2 = duration; } // uint256 balanceBefore = _rewardToken.balanceOf(address(this)); // _rewardToken.safeTransferFrom(msg.sender, address(this), reward); // uint256 balanceEnd = _rewardToken.balanceOf(address(this)); //_initReward = _initReward.add(balanceEnd.sub(balanceBefore)); _initReward = reward; //balanceEnd.sub(balanceBefore); emit RewardAdded(_initReward); } // set fix time to start reward function startNFTReward(uint256 startTime, uint256 stage) external onlyGovernance updateReward(address(0)) { if (stage == 1) { require(_hasStart1 == false, "stage1 has started"); _hasStart1 = true; _startTime1 = startTime; _stageFinish1 = startTime.add(FINISHDURATION1); _rewardRate1 = _initReward.div(FINISHDURATION1); } else { require(_hasStart2 == false, "stage2 has started"); _hasStart2 = true; _startTime2 = startTime; _stageFinish2 = startTime.add(FINISHDURATION2); _rewardRate2 = _initReward.div(FINISHDURATION2); } _lastUpdateTime = startTime; emit SetStartTime(startTime); } function setRuleId( uint256 ruleId) public onlyGovernance { _ruleId = ruleId; } function setNftType( uint256 nftType) public onlyGovernance { _nftType = nftType; } }
set fix time to start reward
function startNFTReward(uint256 startTime, uint256 stage) external onlyGovernance updateReward(address(0)) { if (stage == 1) { require(_hasStart1 == false, "stage1 has started"); _hasStart1 = true; _startTime1 = startTime; _stageFinish1 = startTime.add(FINISHDURATION1); _rewardRate1 = _initReward.div(FINISHDURATION1); require(_hasStart2 == false, "stage2 has started"); _hasStart2 = true; _startTime2 = startTime; _stageFinish2 = startTime.add(FINISHDURATION2); _rewardRate2 = _initReward.div(FINISHDURATION2); } _lastUpdateTime = startTime; emit SetStartTime(startTime); }
6,503,874
./full_match/1/0x3dBEBa7da4f4f0b061E260cEC71727616c75c0E1/sources/contracts/FEELSGOOD.sol
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, "FeelsGoodMath: addition overflow"); return c; }
17,079,881
./full_match/137/0x0908498eFE5b3f80e4fC42Edab7C271496A52096/sources/JAave_1JunPolDev.sol
get Aave reserve Data for an asset liquidityRate is the return percentage for that asset (multiply by 10^27)/
function getAaveReserveData(uint256 _trancheNum) external view returns(uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp) { require(lendingPoolAddressProvider != address(0), "JAave: set lending pool address provider"); IAaveProtocolDataProvider aaveProtocolDataProvider = getDataProvider(); address asset = trancheAddresses[_trancheNum].buyerCoinAddress; if (asset == ETH_ADDR) asset = wrappedEthAddress; return aaveProtocolDataProvider.getReserveData(asset); }
4,687,100
./full_match/1/0x4D694eA338d9Aa9143853458fF794707bB1AD285/sources/contracts/CMFtoken.sol
BURN____________________________________________________________________________________________________
function burn(address from, uint amount) public { if(totalBurned<(cap-minCap)){ if(totalBurned+amount>(cap-minCap)) amount=(cap-minCap)-totalBurned; _burn(from,amount); totalBurned+=amount; } }
3,043,863
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // 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 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "./IEverscale.sol"; pragma experimental ABIEncoderV2; interface IBridge is IEverscale { struct Round { uint32 end; uint32 ttl; uint32 relays; uint32 requiredSignatures; } function updateMinimumRequiredSignatures(uint32 _minimumRequiredSignatures) external; function setConfiguration(EverscaleAddress calldata _roundRelaysConfiguration) external; function updateRoundTTL(uint32 _roundTTL) external; function isRelay( uint32 round, address candidate ) external view returns (bool); function isBanned( address candidate ) external view returns (bool); function isRoundRotten( uint32 round ) external view returns (bool); function verifySignedEverscaleEvent( bytes memory payload, bytes[] memory signatures ) external view returns (uint32); function setRoundRelays( bytes calldata payload, bytes[] calldata signatures ) external; function forceRoundRelays( uint160[] calldata _relays, uint32 roundEnd ) external; function banRelays( address[] calldata _relays ) external; function unbanRelays( address[] calldata _relays ) external; function pause() external; function unpause() external; function setRoundSubmitter(address _roundSubmitter) external; event EmergencyShutdown(bool active); event UpdateMinimumRequiredSignatures(uint32 value); event UpdateRoundTTL(uint32 value); event UpdateRoundRelaysConfiguration(EverscaleAddress configuration); event UpdateRoundSubmitter(address _roundSubmitter); event NewRound(uint32 indexed round, Round meta); event RoundRelay(uint32 indexed round, address indexed relay); event BanRelay(address indexed relay, bool status); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; interface IEverscale { struct EverscaleAddress { int8 wid; uint256 addr; } struct EverscaleEvent { uint64 eventTransactionLt; uint32 eventTimestamp; bytes eventData; int8 configurationWid; uint256 configurationAddress; int8 eventContractWid; uint256 eventContractAddress; address proxy; uint32 round; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "../IEverscale.sol"; interface IMultiVault is IEverscale { enum Fee { Deposit, Withdraw } enum TokenType { Native, Alien } struct TokenMeta { string name; string symbol; uint8 decimals; } struct Token { uint activation; bool blacklisted; uint depositFee; uint withdrawFee; bool isNative; } struct NativeWithdrawalParams { EverscaleAddress native; TokenMeta meta; uint256 amount; address recipient; uint256 chainId; } struct AlienWithdrawalParams { address token; uint256 amount; address recipient; uint256 chainId; } function defaultDepositFee() external view returns (uint); function defaultWithdrawFee() external view returns (uint); function apiVersion() external view returns (string memory api_version); function initialize( address _bridge, address _governance, EverscaleAddress memory _rewards ) external; function tokens(address _token) external view returns (Token memory); function natives(address _token) external view returns (EverscaleAddress memory); function blacklistAddToken(address token) external; function blacklistRemoveToken(address token) external; function setTokenDepositFee(address token, uint _depositFee) external; function setTokenWithdrawFee(address token, uint _withdrawFee) external; function setDefaultDepositFee(uint _defaultDepositFee) external; function setDefaultWithdrawFee(uint _defaultWithdrawFee) external; function rewards() external view returns (EverscaleAddress memory); function configuration() external view returns (EverscaleAddress memory); function withdrawalIds(bytes32) external view returns (bool); function bridge() external view returns(address); function governance() external view returns (address); function guardian() external view returns (address); function management() external view returns (address); function emergencyShutdown() external view returns (bool); function setEmergencyShutdown(bool active) external; function setConfiguration(EverscaleAddress memory _configuration) external; function setGovernance(address _governance) external; function acceptGovernance() external; function setGuardian(address _guardian) external; function setManagement(address _management) external; function setRewards(EverscaleAddress memory _rewards) external; function deposit( EverscaleAddress memory recipient, address token, uint amount ) external; function saveWithdrawNative( bytes memory payload, bytes[] memory signatures ) external; function saveWithdrawAlien( bytes memory payload, bytes[] memory signatures ) external; function migrateAlienTokenToVault( address token, address vault ) external; event BlacklistTokenAdded(address token); event BlacklistTokenRemoved(address token); event UpdateDefaultDepositFee(uint fee); event UpdateDefaultWithdrawFee(uint fee); event UpdateBridge(address bridge); event UpdateConfiguration(int128 wid, uint256 addr); event UpdateRewards(int128 wid, uint256 addr); event UpdateTokenDepositFee(address token, uint256 fee); event UpdateTokenWithdrawFee(address token, uint256 fee); event UpdateGovernance(address governance); event UpdateManagement(address management); event NewPendingGovernance(address governance); event UpdateGuardian(address guardian); event EmergencyShutdown(bool active); event TokenMigrated(address token, address vault); event TokenActivated( address token, uint activation, bool isNative, uint depositFee, uint withdrawFee ); event TokenCreated( address token, int8 native_wid, uint256 native_addr, string name, string symbol, uint8 decimals ); event AlienTransfer( uint256 base_chainId, uint160 base_token, string name, string symbol, uint8 decimals, uint256 amount, int8 recipient_wid, uint256 recipient_addr ); event NativeTransfer( int8 native_wid, uint256 native_addr, uint256 amount, int8 recipient_wid, uint256 recipient_addr ); event Deposit( TokenType _type, address sender, address token, int8 recipient_wid, uint256 recipient_addr, uint256 amount, uint256 fee ); event Withdraw( TokenType _type, bytes32 payloadId, address token, address recipient, uint256 amunt, uint256 fee ); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; interface IMultiVaultToken { function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) external; function burn(address account, uint256 amount) external; function mint(address account, uint256 amount) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "./IVaultBasic.sol"; interface IVault is IVaultBasic { enum ApproveStatus { NotRequired, Required, Approved, Rejected } struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalSkim; uint256 totalLoss; address rewardsManager; EverscaleAddress rewards; } struct PendingWithdrawalParams { uint256 amount; uint256 bounty; uint256 timestamp; ApproveStatus approveStatus; } struct PendingWithdrawalId { address recipient; uint256 id; } struct WithdrawalPeriodParams { uint256 total; uint256 considered; } function initialize( address _token, address _bridge, address _governance, uint _targetDecimals, EverscaleAddress memory _rewards ) external; function withdrawGuardian() external view returns (address); function pendingWithdrawalsPerUser(address user) external view returns (uint); function pendingWithdrawals( address user, uint id ) external view returns (PendingWithdrawalParams memory); function pendingWithdrawalsTotal() external view returns (uint); function managementFee() external view returns (uint256); function performanceFee() external view returns (uint256); function strategies( address strategyId ) external view returns (StrategyParams memory); function withdrawalQueue() external view returns (address[20] memory); function withdrawLimitPerPeriod() external view returns (uint256); function undeclaredWithdrawLimit() external view returns (uint256); function withdrawalPeriods( uint256 withdrawalPeriodId ) external view returns (WithdrawalPeriodParams memory); function depositLimit() external view returns (uint256); function debtRatio() external view returns (uint256); function totalDebt() external view returns (uint256); function lastReport() external view returns (uint256); function lockedProfit() external view returns (uint256); function lockedProfitDegradation() external view returns (uint256); function setWithdrawGuardian(address _withdrawGuardian) external; function setStrategyRewards( address strategyId, EverscaleAddress memory _rewards ) external; function setLockedProfitDegradation(uint256 degradation) external; function setDepositLimit(uint256 limit) external; function setPerformanceFee(uint256 fee) external; function setManagementFee(uint256 fee) external; function setWithdrawLimitPerPeriod(uint256 _withdrawLimitPerPeriod) external; function setUndeclaredWithdrawLimit(uint256 _undeclaredWithdrawLimit) external; function setWithdrawalQueue(address[20] memory queue) external; function setPendingWithdrawalBounty(uint256 id, uint256 bounty) external; function deposit( EverscaleAddress memory recipient, uint256 amount, PendingWithdrawalId memory pendingWithdrawalId ) external; function deposit( EverscaleAddress memory recipient, uint256[] memory amount, PendingWithdrawalId[] memory pendingWithdrawalId ) external; function depositToFactory( uint128 amount, int8 wid, uint256 user, uint256 creditor, uint256 recipient, uint128 tokenAmount, uint128 tonAmount, uint8 swapType, uint128 slippageNumerator, uint128 slippageDenominator, bytes memory level3 ) external; function saveWithdraw( bytes memory payload, bytes[] memory signatures ) external returns ( bool instantWithdrawal, PendingWithdrawalId memory pendingWithdrawalId ); function saveWithdraw( bytes memory payload, bytes[] memory signatures, uint bounty ) external; function cancelPendingWithdrawal( uint256 id, uint256 amount, EverscaleAddress memory recipient, uint bounty ) external; function withdraw( uint256 id, uint256 amountRequested, address recipient, uint256 maxLoss, uint bounty ) external returns(uint256); function addStrategy( address strategyId, uint256 _debtRatio, uint256 minDebtPerHarvest, uint256 maxDebtPerHarvest, uint256 _performanceFee ) external; function updateStrategyDebtRatio( address strategyId, uint256 _debtRatio ) external; function updateStrategyMinDebtPerHarvest( address strategyId, uint256 minDebtPerHarvest ) external; function updateStrategyMaxDebtPerHarvest( address strategyId, uint256 maxDebtPerHarvest ) external; function updateStrategyPerformanceFee( address strategyId, uint256 _performanceFee ) external; function migrateStrategy( address oldVersion, address newVersion ) external; function revokeStrategy( address strategyId ) external; function revokeStrategy() external; function totalAssets() external view returns (uint256); function debtOutstanding(address strategyId) external view returns (uint256); function debtOutstanding() external view returns (uint256); function creditAvailable(address strategyId) external view returns (uint256); function creditAvailable() external view returns (uint256); function availableDepositLimit() external view returns (uint256); function expectedReturn(address strategyId) external view returns (uint256); function report( uint256 profit, uint256 loss, uint256 _debtPayment ) external returns (uint256); function skim(address strategyId) external; function forceWithdraw( PendingWithdrawalId memory pendingWithdrawalId ) external; function forceWithdraw( PendingWithdrawalId[] memory pendingWithdrawalId ) external; function setPendingWithdrawalApprove( PendingWithdrawalId memory pendingWithdrawalId, ApproveStatus approveStatus ) external; function setPendingWithdrawalApprove( PendingWithdrawalId[] memory pendingWithdrawalId, ApproveStatus[] memory approveStatus ) external; event PendingWithdrawalUpdateBounty(address recipient, uint256 id, uint256 bounty); event PendingWithdrawalCancel(address recipient, uint256 id, uint256 amount); event PendingWithdrawalCreated( address recipient, uint256 id, uint256 amount, bytes32 payloadId ); event PendingWithdrawalWithdraw( address recipient, uint256 id, uint256 requestedAmount, uint256 redeemedAmount ); event PendingWithdrawalFill( address recipient, uint256 id ); event PendingWithdrawalUpdateApproveStatus( address recipient, uint256 id, ApproveStatus approveStatus ); event UpdateWithdrawLimitPerPeriod(uint256 withdrawLimitPerPeriod); event UpdateUndeclaredWithdrawLimit(uint256 undeclaredWithdrawLimit); event UpdateDepositLimit(uint256 depositLimit); event UpdatePerformanceFee(uint256 performanceFee); event UpdateManagementFee(uint256 managenentFee); event UpdateWithdrawGuardian(address withdrawGuardian); event UpdateWithdrawalQueue(address[20] queue); event StrategyUpdateDebtRatio(address indexed strategy, uint256 debtRatio); event StrategyUpdateMinDebtPerHarvest(address indexed strategy, uint256 minDebtPerHarvest); event StrategyUpdateMaxDebtPerHarvest(address indexed strategy, uint256 maxDebtPerHarvest); event StrategyUpdatePerformanceFee(address indexed strategy, uint256 performanceFee); event StrategyMigrated(address indexed oldVersion, address indexed newVersion); event StrategyRevoked(address indexed strategy); event StrategyRemovedFromQueue(address indexed strategy); event StrategyAddedToQueue(address indexed strategy); event StrategyReported( address indexed strategy, uint256 gain, uint256 loss, uint256 debtPaid, uint256 totalGain, uint256 totalSkim, uint256 totalLoss, uint256 totalDebt, uint256 debtAdded, uint256 debtRatio ); event StrategyAdded( address indexed strategy, uint256 debtRatio, uint256 minDebtPerHarvest, uint256 maxDebtPerHarvest, uint256 performanceFee ); event StrategyUpdateRewards( address strategyId, int128 wid, uint256 addr ); event FactoryDeposit( uint128 amount, int8 wid, uint256 user, uint256 creditor, uint256 recipient, uint128 tokenAmount, uint128 tonAmount, uint8 swapType, uint128 slippageNumerator, uint128 slippageDenominator, bytes1 separator, bytes level3 ); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "../IEverscale.sol"; interface IVaultBasic is IEverscale { struct WithdrawalParams { EverscaleAddress sender; uint256 amount; address recipient; uint32 chainId; } function bridge() external view returns (address); function configuration() external view returns (EverscaleAddress memory); function withdrawalIds(bytes32) external view returns (bool); function rewards() external view returns (EverscaleAddress memory); function governance() external view returns (address); function guardian() external view returns (address); function management() external view returns (address); function token() external view returns (address); function targetDecimals() external view returns (uint256); function tokenDecimals() external view returns (uint256); function depositFee() external view returns (uint256); function withdrawFee() external view returns (uint256); function emergencyShutdown() external view returns (bool); function apiVersion() external view returns (string memory api_version); function setDepositFee(uint _depositFee) external; function setWithdrawFee(uint _withdrawFee) external; function setConfiguration(EverscaleAddress memory _configuration) external; function setGovernance(address _governance) external; function acceptGovernance() external; function setGuardian(address _guardian) external; function setManagement(address _management) external; function setRewards(EverscaleAddress memory _rewards) external; function setEmergencyShutdown(bool active) external; function deposit( EverscaleAddress memory recipient, uint256 amount ) external; function decodeWithdrawalEventData( bytes memory eventData ) external view returns(WithdrawalParams memory); function sweep(address _token) external; // Events event Deposit( uint256 amount, int128 wid, uint256 addr ); event InstantWithdrawal( bytes32 payloadId, address recipient, uint256 amount ); event UpdateBridge(address bridge); event UpdateConfiguration(int128 wid, uint256 addr); event UpdateTargetDecimals(uint256 targetDecimals); event UpdateRewards(int128 wid, uint256 addr); event UpdateDepositFee(uint256 fee); event UpdateWithdrawFee(uint256 fee); event UpdateGovernance(address governance); event UpdateManagement(address management); event NewPendingGovernance(address governance); event UpdateGuardian(address guardian); event EmergencyShutdown(bool active); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "./../interfaces/multivault/IMultiVault.sol"; import "./../interfaces/IEverscale.sol"; library MultiVaultLibrary { function decodeNativeWithdrawalEventData( bytes memory eventData ) internal pure returns (IMultiVault.NativeWithdrawalParams memory) { ( int8 native_wid, uint256 native_addr, string memory name, string memory symbol, uint8 decimals, uint128 amount, uint160 recipient, uint256 chainId ) = abi.decode( eventData, ( int8, uint256, string, string, uint8, uint128, uint160, uint256 ) ); return IMultiVault.NativeWithdrawalParams({ native: IEverscale.EverscaleAddress(native_wid, native_addr), meta: IMultiVault.TokenMeta(name, symbol, decimals), amount: amount, recipient: address(recipient), chainId: chainId }); } function decodeAlienWithdrawalEventData( bytes memory eventData ) internal pure returns (IMultiVault.AlienWithdrawalParams memory) { ( uint160 token, uint128 amount, uint160 recipient, uint256 chainId ) = abi.decode( eventData, (uint160, uint128, uint160, uint256) ); return IMultiVault.AlienWithdrawalParams({ token: address(token), amount: uint256(amount), recipient: address(recipient), chainId: chainId }); } /// @notice Calculates the CREATE2 address for token, based on the Everscale sig /// @param native_wid Everscale token workchain ID /// @param native_addr Everscale token address body /// @return token Token address function getNativeToken( int8 native_wid, uint256 native_addr ) internal view returns (address token) { token = address(uint160(uint(keccak256(abi.encodePacked( hex'ff', address(this), keccak256(abi.encodePacked(native_wid, native_addr)), hex'5ae84bdc4f10bd94dda6e6c258ff4133478a78c800ece6c093389bffe687e46f' // MultiVaultToken init code hash ))))); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./../interfaces/multivault/IMultiVault.sol"; import "./../interfaces/multivault/IMultiVaultToken.sol"; import "./../interfaces/IBridge.sol"; import "./../interfaces/vault/IVault.sol"; import "./../libraries/MultiVaultLibrary.sol"; import "./MultiVaultToken.sol"; import "./../utils/ChainId.sol"; uint constant MAX_BPS = 10_000; uint constant FEE_LIMIT = MAX_BPS / 2; address constant ZERO_ADDRESS = address(0); uint8 constant DECIMALS_LIMIT = 18; uint256 constant SYMBOL_LENGTH_LIMIT = 32; uint256 constant NAME_LENGTH_LIMIT = 32; string constant API_VERSION = '0.1.0'; /// @notice Vault, based on Octus Bridge. Allows to transfer arbitrary tokens from Everscale /// to EVM and backwards. Everscale tokens are called "natives" (eg QUBE). EVM tokens are called /// "aliens" (eg AAVE). /// Inspired by Yearn Vault V2. contract MultiVault is IMultiVault, ReentrancyGuard, Initializable, ChainId { using SafeERC20 for IERC20; // function getInitHash() public pure returns(bytes32){ // bytes memory bytecode = type(MultiVaultToken).creationCode; // return keccak256(abi.encodePacked(bytecode)); // } mapping (address => Token) tokens_; mapping (address => EverscaleAddress) natives_; uint public override defaultDepositFee; uint public override defaultWithdrawFee; bool public override emergencyShutdown; address public override bridge; mapping(bytes32 => bool) public override withdrawalIds; EverscaleAddress rewards_; EverscaleAddress configuration_; address public override governance; address pendingGovernance; address public override guardian; address public override management; /// @notice Get token information /// @param _token Token address function tokens( address _token ) external view override returns (Token memory) { return tokens_[_token]; } /// @notice Get native Everscale token address for EVM token /// @param _token Token address function natives( address _token ) external view override returns (EverscaleAddress memory) { return natives_[_token]; } /// @notice Rewards address /// @return Everscale address, used for collecting rewards. function rewards() external view override returns (EverscaleAddress memory) { return rewards_; } /// @notice Configuration address /// @return Everscale address, used for verifying `saveWithdraw` payloads function configuration() external view override returns (EverscaleAddress memory) { return configuration_; } modifier tokenNotBlacklisted(address token) { require(!tokens_[token].blacklisted); _; } modifier initializeToken(address token) { if (tokens_[token].activation == 0) { // Non-activated tokens are always aliens require( IERC20Metadata(token).decimals() <= DECIMALS_LIMIT && bytes(IERC20Metadata(token).symbol()).length <= SYMBOL_LENGTH_LIMIT && bytes(IERC20Metadata(token).name()).length <= NAME_LENGTH_LIMIT ); _activateToken(token, false); } _; } modifier onlyEmergencyDisabled() { require(!emergencyShutdown, "Vault: emergency mode enabled"); _; } modifier onlyGovernance() { require(msg.sender == governance); _; } modifier onlyPendingGovernance() { require(msg.sender == pendingGovernance); _; } modifier onlyGovernanceOrManagement() { require(msg.sender == governance || msg.sender == management); _; } modifier onlyGovernanceOrGuardian() { require(msg.sender == governance || msg.sender == guardian); _; } modifier withdrawalNotSeenBefore(bytes memory payload) { bytes32 withdrawalId = keccak256(payload); require(!withdrawalIds[withdrawalId], "Vault: withdraw payload already seen"); _; withdrawalIds[withdrawalId] = true; } modifier respectFeeLimit(uint fee) { require(fee <= FEE_LIMIT); _; } /// @notice Vault API version. Used to track the deployed version of this contract. // @return api_version Current API version function apiVersion() external override pure returns (string memory api_version) { return API_VERSION; } /// @notice MultiVault initializer /// @param _bridge Bridge address /// @param _governance Governance address /// @param _rewards Everscale address for receiving rewards function initialize( address _bridge, address _governance, EverscaleAddress memory _rewards ) external override initializer { bridge = _bridge; emit UpdateBridge(bridge); governance = _governance; emit UpdateGovernance(governance); rewards_ = _rewards; emit UpdateRewards(rewards_.wid, rewards_.addr); } /// @notice Add token to blacklist. Only native token can be blacklisted. /// Blacklisted tokens cant be deposited or withdrawn. /// @param token Token address function blacklistAddToken( address token ) public override onlyGovernance tokenNotBlacklisted(token) { tokens_[token].blacklisted = true; emit BlacklistTokenAdded(token); } /// @notice Remove token from blacklist. /// @param token Token address function blacklistRemoveToken( address token ) external override onlyGovernance { require(tokens_[token].blacklisted); tokens_[token].blacklisted = false; emit BlacklistTokenRemoved(token); } /// @notice Set address to receive fees. /// This may be called only by `governance` /// @param _rewards Rewards receiver in Everscale network function setRewards( EverscaleAddress memory _rewards ) external override onlyGovernance { rewards_ = _rewards; emit UpdateRewards(rewards_.wid, rewards_.addr); } /// @notice Set default deposit fee. /// @param _defaultDepositFee Default deposit fee, should be less than FEE_LIMIT function setDefaultDepositFee( uint _defaultDepositFee ) external override onlyGovernanceOrManagement respectFeeLimit(_defaultDepositFee) { defaultDepositFee = _defaultDepositFee; emit UpdateDefaultDepositFee(defaultDepositFee); } /// @notice Set default withdraw fee. /// @param _defaultWithdrawFee Default withdraw fee, should be less than FEE_LIMIT function setDefaultWithdrawFee( uint _defaultWithdrawFee ) external override onlyGovernanceOrManagement respectFeeLimit(_defaultWithdrawFee) { defaultWithdrawFee = _defaultWithdrawFee; emit UpdateDefaultWithdrawFee(defaultWithdrawFee); } /// @notice Set deposit fee for specific token. /// This may be called only by `owner` or `management`. /// @param token Token address /// @param _depositFee Deposit fee, must be less than FEE_LIMIT. function setTokenDepositFee( address token, uint _depositFee ) public override onlyGovernanceOrManagement respectFeeLimit(_depositFee) { tokens_[token].depositFee = _depositFee; emit UpdateTokenDepositFee(token, _depositFee); } /// @notice Set withdraw fee for specific token. /// This may be called only by `governance` or `management` /// @param token Token address, must be enabled /// @param _withdrawFee Withdraw fee, must be less than FEE_LIMIT. function setTokenWithdrawFee( address token, uint _withdrawFee ) public override onlyGovernanceOrManagement respectFeeLimit(_withdrawFee) { tokens_[token].withdrawFee = _withdrawFee; emit UpdateTokenWithdrawFee(token, _withdrawFee); } /// @notice Set configuration address. /// @param _configuration The address to use for configuration. function setConfiguration( EverscaleAddress memory _configuration ) external override onlyGovernance { configuration_ = _configuration; emit UpdateConfiguration(configuration_.wid, configuration_.addr); } /// @notice Nominate new address to use as a governance. /// The change does not go into effect immediately. This function sets a /// pending change, and the governance address is not updated until /// the proposed governance address has accepted the responsibility. /// This may only be called by the `governance`. /// @param _governance The address requested to take over Vault governance. function setGovernance( address _governance ) external override onlyGovernance { pendingGovernance = _governance; emit NewPendingGovernance(pendingGovernance); } /// @notice Once a new governance address has been proposed using `setGovernance`, /// this function may be called by the proposed address to accept the /// responsibility of taking over governance for this contract. /// This may only be called by the `pendingGovernance`. function acceptGovernance() external override onlyPendingGovernance { governance = pendingGovernance; emit UpdateGovernance(governance); } /// @notice Changes the management address. /// This may only be called by `governance` /// @param _management The address to use for management. function setManagement( address _management ) external override onlyGovernance { management = _management; emit UpdateManagement(management); } /// @notice Changes the address of `guardian`. /// This may only be called by `governance`. /// @param _guardian The new guardian address to use. function setGuardian( address _guardian ) external override onlyGovernance { guardian = _guardian; emit UpdateGuardian(guardian); } /// @notice Activates or deactivates MultiVault emergency shutdown. /// During emergency shutdown: /// - Deposits are disabled /// - Withdrawals are disabled /// This may only be called by `governance` or `guardian`. /// @param active If `true`, the MultiVault goes into Emergency Shutdown. If `false`, the MultiVault goes back into /// Normal Operation. function setEmergencyShutdown( bool active ) external override { if (active) { require(msg.sender == guardian || msg.sender == governance); } else { require(msg.sender == governance); } emergencyShutdown = active; emit EmergencyShutdown(active); } /// @notice Transfer tokens to the Everscale. Works both for native and alien tokens. /// Approve is required only for alien tokens deposit. /// @param recipient Everscale recipient. /// @param token EVM token address, should not be blacklisted. /// @param amount Amount of tokens to transfer. function deposit( EverscaleAddress memory recipient, address token, uint amount ) external override nonReentrant tokenNotBlacklisted(token) initializeToken(token) onlyEmergencyDisabled { uint fee = calculateMovementFee(amount, token, Fee.Deposit); bool isNative = tokens_[token].isNative; if (isNative) { IMultiVaultToken(token).burn( msg.sender, amount ); _transferToEverscaleNative(token, recipient, amount - fee); if (fee > 0) _transferToEverscaleNative(token, rewards_, fee); } else { IERC20(token).safeTransferFrom( msg.sender, address(this), amount ); _transferToEverscaleAlien(token, recipient, amount - fee); if (fee > 0) _transferToEverscaleAlien(token, rewards_, fee); } emit Deposit( isNative ? TokenType.Native : TokenType.Alien, msg.sender, token, recipient.wid, recipient.addr, amount, fee ); } /// @notice Save withdrawal for native token /// @param payload Withdraw payload /// @param signatures Payload signatures function saveWithdrawNative( bytes memory payload, bytes[] memory signatures ) external override nonReentrant withdrawalNotSeenBefore(payload) onlyEmergencyDisabled { EverscaleEvent memory _event = _processWithdrawEvent(payload, signatures); bytes32 payloadId = keccak256(payload); // Decode event data NativeWithdrawalParams memory withdrawal = MultiVaultLibrary.decodeNativeWithdrawalEventData(_event.eventData); // Ensure chain id is correct require(withdrawal.chainId == getChainID()); // Derive token address // Depends on the withdrawn token source address token = _getNativeWithdrawalToken(withdrawal); // Ensure token is not blacklisted require(!tokens_[token].blacklisted); // Consider movement fee and send it to `rewards_` uint256 fee = calculateMovementFee( withdrawal.amount, token, Fee.Withdraw ); IMultiVaultToken(token).mint( withdrawal.recipient, withdrawal.amount - fee ); if (fee > 0) _transferToEverscaleNative(token, rewards_, fee); emit Withdraw( TokenType.Native, payloadId, token, withdrawal.recipient, withdrawal.amount, fee ); } function saveWithdrawAlien( bytes memory payload, bytes[] memory signatures ) external override nonReentrant withdrawalNotSeenBefore(payload) onlyEmergencyDisabled { EverscaleEvent memory _event = _processWithdrawEvent(payload, signatures); bytes32 payloadId = keccak256(payload); // Decode event data AlienWithdrawalParams memory withdrawal = MultiVaultLibrary.decodeAlienWithdrawalEventData(_event.eventData); // Ensure chain id is correct require(withdrawal.chainId == getChainID()); // Ensure token is not blacklisted require(!tokens_[withdrawal.token].blacklisted); // Consider movement fee and send it to `rewards_` uint256 fee = calculateMovementFee( withdrawal.amount, withdrawal.token, Fee.Withdraw ); IERC20(withdrawal.token).safeTransfer( withdrawal.recipient, withdrawal.amount - fee ); if (fee > 0) _transferToEverscaleAlien(withdrawal.token, rewards_, fee); emit Withdraw( TokenType.Alien, payloadId, withdrawal.token, withdrawal.recipient, withdrawal.amount, fee ); } function migrateAlienTokenToVault( address token, address vault ) external override onlyGovernance { require(tokens_[token].activation > 0); require(!tokens_[token].isNative); require(IVault(vault).token() == token); require(IVault(token).governance() == governance); tokens_[token].blacklisted = true; IERC20(token).safeTransfer( vault, IERC20(token).balanceOf(address(this)) ); emit TokenMigrated(token, vault); } /// @notice Calculates fee for deposit or withdrawal. /// @param amount Amount of tokens. /// @param _token Token address. /// @param fee Fee type (Deposit = 0, Withdraw = 1). function calculateMovementFee( uint256 amount, address _token, Fee fee ) public view returns (uint256) { Token memory token = tokens_[_token]; uint tokenFee = fee == Fee.Deposit ? token.depositFee : token.withdrawFee; return tokenFee * amount / MAX_BPS; } function getNativeToken( int8 native_wid, uint256 native_addr ) external view returns (address) { return MultiVaultLibrary.getNativeToken(native_wid, native_addr); } function _activateToken( address token, bool isNative ) internal { tokens_[token].activation = block.number; tokens_[token].blacklisted = false; tokens_[token].isNative = isNative; tokens_[token].depositFee = defaultDepositFee; tokens_[token].withdrawFee = defaultWithdrawFee; emit TokenActivated( token, block.number, isNative, defaultDepositFee, defaultWithdrawFee ); } function _transferToEverscaleNative( address _token, EverscaleAddress memory recipient, uint amount ) internal { EverscaleAddress memory native = natives_[_token]; emit NativeTransfer( native.wid, native.addr, amount, recipient.wid, recipient.addr ); } function _transferToEverscaleAlien( address _token, EverscaleAddress memory recipient, uint amount ) internal { emit AlienTransfer( getChainID(), uint160(_token), IERC20Metadata(_token).name(), IERC20Metadata(_token).symbol(), IERC20Metadata(_token).decimals(), amount, recipient.wid, recipient.addr ); } function _getNativeWithdrawalToken( NativeWithdrawalParams memory withdrawal ) internal returns (address token) { token = MultiVaultLibrary.getNativeToken( withdrawal.native.wid, withdrawal.native.addr ); if (tokens_[token].activation == 0) { _deployTokenForNative(withdrawal.native, withdrawal.meta); _activateToken(token, true); natives_[token] = withdrawal.native; } } function _deployTokenForNative( EverscaleAddress memory native, TokenMeta memory meta ) internal returns (address token) { bytes memory bytecode = type(MultiVaultToken).creationCode; bytes32 salt = keccak256(abi.encodePacked(native.wid, native.addr)); assembly { token := create2(0, add(bytecode, 32), mload(bytecode), salt) } IMultiVaultToken(token).initialize( string(abi.encodePacked('Octus ', meta.name)), string(abi.encodePacked('oct', meta.symbol)), meta.decimals ); emit TokenCreated( token, native.wid, native.addr, meta.name, meta.symbol, meta.decimals ); } function _processWithdrawEvent( bytes memory payload, bytes[] memory signatures ) internal returns (EverscaleEvent memory) { require( IBridge(bridge).verifySignedEverscaleEvent(payload, signatures) == 0, "Vault: signatures verification failed" ); // Decode Everscale event (EverscaleEvent memory _event) = abi.decode(payload, (EverscaleEvent)); require( _event.configurationWid == configuration_.wid && _event.configurationAddress == configuration_.addr ); return _event; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/multivault/IMultiVaultToken.sol"; contract MultiVaultToken is IMultiVaultToken, Context, IERC20, IERC20Metadata, Ownable { uint activation; 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}, {symbol} and {decimals}. * * All two of these values are immutable: they can only be set once during * construction. */ function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) external override { require(activation == 0); _name = name_; _symbol = symbol_; _decimals = decimals_; activation = block.number; } /** * @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 _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]; } function mint( address account, uint amount ) external override onlyOwner { _mint(account, amount); } function burn( address account, uint amount ) external override onlyOwner { _burn(account, amount); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.2; contract ChainId { function getChainID() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } }
SPDX-License-Identifier: AGPL-3.0
interface IVault is IVaultBasic { enum ApproveStatus { NotRequired, Required, Approved, Rejected } function defaultDepositFee() external view returns (uint); function defaultWithdrawFee() external view returns (uint); function apiVersion() external view returns (string memory api_version); function initialize( address _bridge, address _governance, EverscaleAddress memory _rewards ) external; function tokens(address _token) external view returns (Token memory); function natives(address _token) external view returns (EverscaleAddress memory); function blacklistAddToken(address token) external; function blacklistRemoveToken(address token) external; function setTokenDepositFee(address token, uint _depositFee) external; function setTokenWithdrawFee(address token, uint _withdrawFee) external; function setDefaultDepositFee(uint _defaultDepositFee) external; function setDefaultWithdrawFee(uint _defaultWithdrawFee) external; function rewards() external view returns (EverscaleAddress memory); function configuration() external view returns (EverscaleAddress memory); function withdrawalIds(bytes32) external view returns (bool); function bridge() external view returns(address); function governance() external view returns (address); function guardian() external view returns (address); function management() external view returns (address); function emergencyShutdown() external view returns (bool); function setEmergencyShutdown(bool active) external; function setConfiguration(EverscaleAddress memory _configuration) external; function setGovernance(address _governance) external; function acceptGovernance() external; function setGuardian(address _guardian) external; function setManagement(address _management) external; function setRewards(EverscaleAddress memory _rewards) external; function deposit( EverscaleAddress memory recipient, address token, uint amount ) external; function saveWithdrawNative( bytes memory payload, bytes[] memory signatures ) external; function saveWithdrawAlien( bytes memory payload, bytes[] memory signatures ) external; function migrateAlienTokenToVault( address token, address vault ) external; event BlacklistTokenAdded(address token); event BlacklistTokenRemoved(address token); event UpdateDefaultDepositFee(uint fee); event UpdateDefaultWithdrawFee(uint fee); event UpdateBridge(address bridge); event UpdateConfiguration(int128 wid, uint256 addr); event UpdateRewards(int128 wid, uint256 addr); event UpdateTokenDepositFee(address token, uint256 fee); event UpdateTokenWithdrawFee(address token, uint256 fee); event UpdateGovernance(address governance); event UpdateManagement(address management); event NewPendingGovernance(address governance); event UpdateGuardian(address guardian); event EmergencyShutdown(bool active); event TokenMigrated(address token, address vault); event TokenActivated( address token, uint activation, bool isNative, uint depositFee, uint withdrawFee ); event TokenCreated( address token, int8 native_wid, uint256 native_addr, string name, string symbol, uint8 decimals ); event AlienTransfer( uint256 base_chainId, uint160 base_token, string name, string symbol, uint8 decimals, uint256 amount, int8 recipient_wid, uint256 recipient_addr ); event NativeTransfer( int8 native_wid, uint256 native_addr, uint256 amount, int8 recipient_wid, uint256 recipient_addr ); event Deposit( TokenType _type, address sender, address token, int8 recipient_wid, uint256 recipient_addr, uint256 amount, uint256 fee ); event Withdraw( TokenType _type, bytes32 payloadId, address token, address recipient, uint256 amunt, uint256 fee ); } pragma solidity ^0.8.2; } pragma solidity ^0.8.2; import "./IVaultBasic.sol"; struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalSkim; uint256 totalLoss; address rewardsManager; EverscaleAddress rewards; } struct PendingWithdrawalParams { uint256 amount; uint256 bounty; uint256 timestamp; ApproveStatus approveStatus; } struct PendingWithdrawalId { address recipient; uint256 id; } struct WithdrawalPeriodParams { uint256 total; uint256 considered; } }
5,970,819
./full_match/4/0xC2d0Ee71f7bd1406ef07B10C77c0A35FdB4B3Ee1/sources/localhost/crowdsale/MintedCrowdsale.sol
Overrides delivery by minting tokens upon purchase. beneficiary Token purchaser tokenAmount Number of tokens to be minted/ Potentially dangerous assumption about the type of the token.
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { require( CleverToken(address(token())).mint(beneficiary, tokenAmount), "MintedCrowdsale: minting failed" ); }
12,488,376
./full_match/137/0x53Ff1Dee931e5C0678d6eEf4140F04Ebd8a4d7AF/sources/project_/contracts/Nexus.sol
Call this function after finalizing the presale
function enableAllFees() external onlyOwner { restoreAllFee(); _previousReflectionFee = _reflectioinFee; _previousStakingFee = _stakingFee; _previousNexusFee = _nexusFee; _previousLiquidityFee = _liquidityFee; setSwapAndLiquifyEnabled(true); }
4,797,593
./full_match/80001/0x18feE959CADA8E40664bF966c123D95A42BACD6F/sources/routerContract.sol
do not allow recovering self token
function recoverToken(address tokenAddress, uint256 tokenAmount) public onlyRole(DEFAULT_ADMIN_ROLE) { require(tokenAddress != address(this), "Self withdraw"); IERC20(tokenAddress).transfer(GNOSIS, tokenAmount); }
5,686,774
// File: node_modules\openzeppelin-solidity\contracts\ownership\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Holder.sol contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: node_modules\openzeppelin-solidity\contracts\AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721BasicToken.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Token.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function ERC721Token(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: contracts\Integers.sol /** * Integers Library * * In summary this is a simple library of integer functions which allow a simple * conversion to and from strings * * @author James Lockhart <[email protected]> */ library Integers { /** * Parse Int * * Converts an ASCII string value into an uint as long as the string * its self is a valid unsigned integer * * @param _value The ASCII string to be converted to an unsigned integer * @return uint The unsigned value of the ASCII string */ function parseInt(string _value) public returns (uint _ret) { bytes memory _bytesValue = bytes(_value); uint j = 1; for(uint i = _bytesValue.length-1; i >= 0 && i < _bytesValue.length; i--) { assert(_bytesValue[i] >= 48 && _bytesValue[i] <= 57); _ret += (uint(_bytesValue[i]) - 48)*j; j*=10; } } /** * To String * * Converts an unsigned integer to the ASCII string equivalent value * * @param _base The unsigned integer to be converted to a string * @return string The resulting ASCII string value */ function toString(uint _base) internal returns (string) { if (_base==0){ return "0"; } bytes memory _tmp = new bytes(32); uint i; for(i = 0;_base > 0;i++) { _tmp[i] = byte((_base % 10) + 48); _base /= 10; } bytes memory _real = new bytes(i--); for(uint j = 0; j < _real.length; j++) { _real[j] = _tmp[i--]; } return string(_real); } /** * To Byte * * Convert an 8 bit unsigned integer to a byte * * @param _base The 8 bit unsigned integer * @return byte The byte equivalent */ function toByte(uint8 _base) public returns (byte _ret) { assembly { let m_alloc := add(msize(),0x1) mstore8(m_alloc, _base) _ret := mload(m_alloc) } } /** * To Bytes * * Converts an unsigned integer to bytes * * @param _base The integer to be converted to bytes * @return bytes The bytes equivalent */ function toBytes(uint _base) internal returns (bytes _ret) { assembly { let m_alloc := add(msize(),0x1) _ret := mload(m_alloc) mstore(_ret, 0x20) mstore(add(_ret, 0x20), _base) } } } // File: contracts\Strings.sol /** * Strings Library * * In summary this is a simple library of string functions which make simple * string operations less tedious in solidity. * * Please be aware these functions can be quite gas heavy so use them only when * necessary not to clog the blockchain with expensive transactions. * * @author James Lockhart <[email protected]> */ library Strings { /** * Concat (High gas cost) * * Appends two strings together and returns a new value * * @param _base When being used for a data type this is the extended object * otherwise this is the string which will be the concatenated * prefix * @param _value The value to be the concatenated suffix * @return string The resulting string from combinging the base and value */ function concat(string _base, string _value) internal returns (string) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length > 0); string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length); bytes memory _newValue = bytes(_tmpValue); uint i; uint j; for(i = 0; i < _baseBytes.length; i++) { _newValue[j++] = _baseBytes[i]; } for(i = 0; i<_valueBytes.length; i++) { _newValue[j++] = _valueBytes[i]; } return string(_newValue); } /** * Index Of * * Locates and returns the position of a character within a string * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf(string _base, string _value) internal returns (int) { return _indexOf(_base, _value, 0); } /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function _indexOf(string _base, string _value, uint _offset) internal returns (int) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for(uint i = _offset; i < _baseBytes.length; i++) { if (_baseBytes[i] == _valueBytes[0]) { return int(i); } } return -1; } /** * Length * * Returns the length of the specified string * * @param _base When being used for a data type this is the extended object * otherwise this is the string to be measured * @return uint The length of the passed string */ function length(string _base) internal returns (uint) { bytes memory _baseBytes = bytes(_base); return _baseBytes.length; } /** * Sub String * * Extracts the beginning part of a string based on the desired length * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @return string The extracted sub string */ function substring(string _base, int _length) internal returns (string) { return _substring(_base, _length, 0); } /** * Sub String * * Extracts the part of a string based on the desired length and offset. The * offset and length must not exceed the lenth of the base string. * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @param _offset The starting point to extract the sub string from * @return string The extracted sub string */ function _substring(string _base, int _length, int _offset) internal returns (string) { bytes memory _baseBytes = bytes(_base); assert(uint(_offset+_length) <= _baseBytes.length); string memory _tmp = new string(uint(_length)); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for(uint i = uint(_offset); i < uint(_offset+_length); i++) { _tmpBytes[j++] = _baseBytes[i]; } return string(_tmpBytes); } /** * String Split (Very high gas cost) * * Splits a string into an array of strings based off the delimiter value. * Please note this can be quite a gas expensive function due to the use of * storage so only use if really required. * * @param _base When being used for a data type this is the extended object * otherwise this is the string value to be split. * @param _value The delimiter to split the string on which must be a single * character * @return string[] An array of values split based off the delimiter, but * do not container the delimiter. */ function split(string _base, string _value) internal returns (string[] storage splitArr) { bytes memory _baseBytes = bytes(_base); uint _offset = 0; while(_offset < _baseBytes.length-1) { int _limit = _indexOf(_base, _value, _offset); if (_limit == -1) { _limit = int(_baseBytes.length); } string memory _tmp = new string(uint(_limit)-_offset); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for(uint i = _offset; i < uint(_limit); i++) { _tmpBytes[j++] = _baseBytes[i]; } _offset = uint(_limit) + 1; splitArr.push(string(_tmpBytes)); } return splitArr; } /** * Compare To * * Compares the characters of two strings, to ensure that they have an * identical footprint * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent */ function compareTo(string _base, string _value) internal returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for(uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i]) { return false; } } return true; } /** * Compare To Ignore Case (High gas cost) * * Compares the characters of two strings, converting them to the same case * where applicable to alphabetic characters to distinguish if the values * match. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent value * discarding case */ function compareToIgnoreCase(string _base, string _value) internal returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for(uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i] && _upper(_baseBytes[i]) != _upper(_valueBytes[i])) { return false; } } return true; } /** * Upper * * Converts all the values of a string to their corresponding upper case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to upper case * @return string */ function upper(string _base) internal returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _upper(_baseBytes[i]); } return string(_baseBytes); } /** * Lower * * Converts all the values of a string to their corresponding lower case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to lower case * @return string */ function lower(string _base) internal returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _lower(_baseBytes[i]); } return string(_baseBytes); } /** * Upper * * Convert an alphabetic character to upper case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to upper case * @return bytes1 The converted value if the passed value was alphabetic * and in a lower case otherwise returns the original value */ function _upper(bytes1 _b1) private constant returns (bytes1) { if (_b1 >= 0x61 && _b1 <= 0x7A) { return bytes1(uint8(_b1)-32); } return _b1; } /** * Lower * * Convert an alphabetic character to lower case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to lower case * @return bytes1 The converted value if the passed value was alphabetic * and in a upper case otherwise returns the original value */ function _lower(bytes1 _b1) private constant returns (bytes1) { if (_b1 >= 0x41 && _b1 <= 0x5A) { return bytes1(uint8(_b1)+32); } return _b1; } } // File: contracts\DigitalArtChain.sol contract DigitalArtChain is Ownable, ERC721Token, ERC721Holder { using Strings for string; using Integers for uint; function DigitalArtChain () ERC721Token("DigitalArtChain" ,"DAC") public { } struct DigitalArt { string ipfsHash; address publisher; } DigitalArt[] public digitalArts; mapping (string => uint256) ipfsHashToTokenId; mapping (address => uint256) internal publishedTokensCount; mapping (address => uint256[]) internal publishedTokens; mapping(address => mapping (uint256 => uint256)) internal publishedTokensIndex; struct SellingItem { address seller; uint128 price; } mapping (uint256 => SellingItem) public tokenIdToSellingItem; uint128 public createDigitalArtFee = 0.00198 ether; uint128 public publisherCut = 500; string preUri1 = "http://api.digitalartchain.com/tokens?tokenId="; string preUri2 = "&ipfsHash="; /*** Modifier ***/ modifier onlyOwner() { require(msg.sender == owner); _; } /*** Owner Action ***/ function withdraw() public onlyOwner { owner.transfer(this.balance); } function setCreateDigitalArtFee(uint128 _fee) public onlyOwner { createDigitalArtFee = _fee; } function setPublisherCut(uint128 _cut) public onlyOwner { require(_cut > 0 && _cut < 10000); publisherCut = _cut; } function setPreUri1(string _preUri) public onlyOwner { preUri1 = _preUri; } function setPreUri2(string _preUri) public onlyOwner { preUri2 = _preUri; } function getIpfsHashToTokenId(string _string) public view returns (uint256){ return ipfsHashToTokenId[_string]; } function getOwnedTokens(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } function getAllTokens() public view returns (uint256[]) { return allTokens; } function publishedCountOf(address _publisher) public view returns (uint256) { return publishedTokensCount[_publisher]; } function publishedTokenOfOwnerByIndex(address _publisher, uint256 _index) public view returns (uint256) { require(_index < publishedCountOf(_publisher)); return publishedTokens[_publisher][_index]; } function getPublishedTokens(address _publisher) public view returns (uint256[]) { return publishedTokens[_publisher]; } function mintDigitalArt(string _ipfsHash) public payable { require(msg.value == createDigitalArtFee); require(ipfsHashToTokenId[_ipfsHash] == 0); DigitalArt memory _digitalArt = DigitalArt({ipfsHash: _ipfsHash, publisher: msg.sender}); uint256 newDigitalArtId = digitalArts.push(_digitalArt) - 1; ipfsHashToTokenId[_ipfsHash] = newDigitalArtId; _mint(msg.sender, newDigitalArtId); publishedTokensCount[msg.sender]++; uint256 length = publishedTokens[msg.sender].length; publishedTokens[msg.sender].push(newDigitalArtId); publishedTokensIndex[msg.sender][newDigitalArtId] = length; } function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return preUri1.concat(_tokenId.toString()).concat(preUri2).concat(digitalArts[_tokenId].ipfsHash); } function addDigitalArtSellingItem(uint256 _tokenId, uint128 _price) public onlyOwnerOf(_tokenId) { require(tokenIdToSellingItem[_tokenId].seller == address(0)); SellingItem memory _sellingItem = SellingItem(msg.sender, uint128(_price)); tokenIdToSellingItem[_tokenId] = _sellingItem; approve(address(this), _tokenId); safeTransferFrom(msg.sender, address(this), _tokenId); } function cancelDigitalArtSellingItem(uint256 _tokenId) public { require(tokenIdToSellingItem[_tokenId].seller == msg.sender); this.safeTransferFrom(address(this), tokenIdToSellingItem[_tokenId].seller, _tokenId); delete tokenIdToSellingItem[_tokenId]; } function purchaseDigitalArtSellingItem(uint256 _tokenId) public payable { require(tokenIdToSellingItem[_tokenId].seller != address(0)); require(tokenIdToSellingItem[_tokenId].seller != msg.sender); require(tokenIdToSellingItem[_tokenId].price == msg.value); SellingItem memory sellingItem = tokenIdToSellingItem[_tokenId]; if (sellingItem.price > 0) { uint128 actualPublisherCut = _computePublisherCut(sellingItem.price); uint128 proceeds = sellingItem.price - actualPublisherCut; sellingItem.seller.transfer(proceeds); digitalArts[_tokenId].publisher.transfer(actualPublisherCut); } delete tokenIdToSellingItem[_tokenId]; this.safeTransferFrom(address(this), msg.sender, _tokenId); } /*** Tools ***/ function _computePublisherCut(uint128 _price) internal view returns (uint128) { return _price * publisherCut / 10000; } }
Length Returns the length of the specified string _base When being used for a data type this is the extended object otherwise this is the string to be measured return uint The length of the passed string/
function length(string _base) internal returns (uint) { bytes memory _baseBytes = bytes(_base); return _baseBytes.length; }
4,808,883
// SPDX-License-Identifier: Unlicense pragma solidity >=0.7.6; import 'src/tsm/contracts/NutBerryTokenBridge.sol'; import 'src/v1/contracts/NutBerryFlavorV1.sol'; import './V1TestOneChallenge.sol'; contract V1TestOne is NutBerryFlavorV1, V1TestOneChallenge { function submitCustomBlock (uint256, uint256) external { _createBlockMessage(); } // ERC-20 function _BALANCES_KEY (address token, address account) internal returns (uint256 ret) { assembly { mstore(0, token) mstore(32, account) ret := keccak256(0, 64) } } // ERC-721 function _OWNERS_KEY (address token, uint256 tokenId) internal returns (uint256 ret) { assembly { mstore(0, token) mstore(32, tokenId) ret := keccak256(0, 64) } } function _NONCE_KEY (address a) internal returns (uint256 ret) { assembly { mstore(0, 0xacacac) mstore(32, a) ret := keccak256(0, 64) } } function _increment (uint256 k, uint256 v) internal { _sstore(k, _sload(k) + v); } function _incrementNonce (address a) internal { _increment(_NONCE_KEY(a), 1); NutBerryCore._setStorageL1(bytes32(uint256(a)), 1); } function owners (address token, uint256 tokenId) public returns (address) { return address(_sload(_OWNERS_KEY(token, tokenId))); } function balances (address token, address account) public returns (uint256) { return _sload(_BALANCES_KEY(token, account)); } function nonces (address account) public returns (uint256) { return _sload(_NONCE_KEY(account)); } /// @dev State transition when a user deposits a token. function onDeposit (address owner, address token, uint256 value, uint256 tokenType) external { // all power the core protocol require(msg.sender == address(this)); if (NutBerryTokenBridge._getTokenType(token) == 0) { NutBerryTokenBridge._setTokenType(token, tokenType); } if (tokenType == 1) { _increment(_BALANCES_KEY(token, owner), value); } else { _sstore(_OWNERS_KEY(token, value), uint(owner)); } } event Message(bytes data); function onCustomBlockBeacon (bytes memory data) external { require(msg.sender == address(this)); _storeCallDataHash(); _sstore(uint256(keccak256(data)), _getTime()); emit Message(data); } function _storeCallDataHash () internal { uint ptr; uint hash; assembly { let size := calldatasize() // that becomes more work on L1 (challenge) if origin() { // < usual calldata... > // < 32 bytes timestamp > // < read witnesses... - each 32 bytes > // < # of witness elements - 32 bytes> // < write witnesses - each 32 bytes > // < # of witness elements - 32 bytes > size := sub(calldatasize(), 32) // load the length of nElements and sub size := sub(size, mul(32, calldataload(size))) // points to the start of `write witnesses` size := sub(size, 32) // points at `# read witnesses` and subtracts size := sub(size, mul(32, calldataload(size))) // sub again (block timestamp) size := sub(size, 32) } ptr := mload(64) calldatacopy(ptr, 0, size) hash := keccak256(ptr, size) log1(0, 0, hash) } _sstore(hash, ptr); } function onExit (address msgSender, address token, uint256 value) external { // all power the core protocol require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); if (NutBerryTokenBridge._getTokenType(token) == 1) { _incrementExit(token, msgSender, value); } else { _setERC721Exit(token, msgSender, value); } assembly { let ptr := 0 let size := 32 mstore(ptr, token) log0(ptr, size) ptr := add(ptr, size) mstore(ptr, value) log0(ptr, size) } } function onTransfer (address msgSender, address to, address token, uint256 value) external { // all power the core protocol require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); assembly { let ptr := 0 let size := 32 mstore(ptr, to) log0(ptr, size) ptr := add(ptr, size) mstore(ptr, token) log0(ptr, size) ptr := add(ptr, size) mstore(ptr, value) log0(ptr, size) } } function onOne (address msgSender, bytes memory one, uint256 nonce, bytes memory two) external { // all power the core protocol require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); assembly { let ptr := mload(64) let size := 32 size := mload(one) log0(add(one, 32), size) size := 32 mstore(ptr, nonce) log0(ptr, size) size := mload(two) log0(add(two, 32), size) } } function onTwo (address msgSender, bytes24 foo) external { require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); uint tmp; assembly { let ptr := mload(64) let size := 32 mstore(ptr, foo) log0(ptr, size) tmp := keccak256(0, 32) } for (uint i = 0; i < 3000; i++) { _sstore(0x4411, tmp); } } function onThree (address msgSender, int128) external { require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); uint tmp = 0; for (uint i = 0; i < 0xff; i++) { uint _now = _getTime(); if (_now < 1623777000 || _now > 2623777000) { revert(); } tmp += _now; } _sstore(0x9241, tmp); assembly { mstore(0, calldataload(36)) log0(0, 32) } } function onShouldRevert (address, uint256 shouldRevertWithString) external { require(msg.sender == address(this)); if (shouldRevertWithString == 0) { revert(); } revert('hello world'); } function signalUpgradeTo (address newImplementation) external { emit NutBerryEvents.RollupUpgrade(newImplementation); } }
all power the core protocol
function onOne (address msgSender, bytes memory one, uint256 nonce, bytes memory two) external { require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); assembly { let ptr := mload(64) let size := 32 size := mload(one) log0(add(one, 32), size) size := 32 mstore(ptr, nonce) log0(ptr, size) size := mload(two) log0(add(two, 32), size) } }
12,770,373
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/LiveMintTokyo.sol
Returns A User's QR Allocation Amount, Or 0 If Not Eligible/
function readEligibility(address Recipient, bytes32[] memory Proof) public view returns(uint) { bool Eligible = readQREligibility(Recipient, Proof); }
8,470,956
pragma solidity ^0.5.0; library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() 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; } } contract Pausable is Ownable { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @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() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } /* * approve/increaseApprove/decreaseApprove can be set when Paused state */ /* * function approve(address spender, uint256 value) public whenNotPaused returns (bool) { * return super.approve(spender, value); * } * * function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { * return super.increaseAllowance(spender, addedValue); * } * * function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { * return super.decreaseAllowance(spender, subtractedValue); * } */ } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } contract LITI is ERC20Detailed, ERC20Pausable { struct LockInfo { uint256 _releaseTime; uint256 _amount; } mapping (address => LockInfo[]) public timelockList; mapping (address => bool) public frozenAccount; event Freeze(address indexed holder); event Unfreeze(address indexed holder); event Lock(address indexed holder, uint256 value, uint256 releaseTime); event Unlock(address indexed holder, uint256 value); modifier notFrozen(address _holder) { require(!frozenAccount[_holder]); _; } constructor() ERC20Detailed("LITI", "LITI", 18) public { _mint(msg.sender, 1000000000 * (10 ** 18)); } function mint(uint _amount) public onlyOwner returns (bool) { _mint(msg.sender, _amount); return true; } function burn(uint _amount) public onlyOwner returns (bool) { _burn(msg.sender, _amount); return true; } function balanceOf(address owner) public view returns (uint256) { uint256 totalBalance = super.balanceOf(owner); if( timelockList[owner].length >0 ){ for(uint i=0; i<timelockList[owner].length;i++){ totalBalance = totalBalance.add(timelockList[owner][i]._amount); } } return totalBalance; } function transfer(address to, uint256 value) public notFrozen(msg.sender) returns (bool) { if (timelockList[msg.sender].length > 0 ) { _autoUnlock(msg.sender); } return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public notFrozen(from) returns (bool) { if (timelockList[from].length > 0) { _autoUnlock(from); } return super.transferFrom(from, to, value); } function freezeAccount(address holder) public onlyOwner returns (bool) { require(!frozenAccount[holder]); frozenAccount[holder] = true; emit Freeze(holder); return true; } function unfreezeAccount(address holder) public onlyOwner returns (bool) { require(frozenAccount[holder]); frozenAccount[holder] = false; emit Unfreeze(holder); return true; } function lock(address holder, uint256 value, uint256 releaseTime) public onlyOwner returns (bool) { require(_balances[holder] >= value,"There is not enough balances of holder."); _lock(holder,value,releaseTime); return true; } function transferWithLock(address holder, uint256 value, uint256 releaseTime) public onlyOwner returns (bool) { _transfer(msg.sender, holder, value); _lock(holder,value,releaseTime); return true; } function unlock(address holder, uint256 idx) public onlyOwner returns (bool) { require( timelockList[holder].length > idx, "There is not lock info."); _unlock(holder,idx); return true; } function _lock(address holder, uint256 value, uint256 releaseTime) internal returns(bool) { _balances[holder] = _balances[holder].sub(value); timelockList[holder].push( LockInfo(releaseTime, value) ); emit Lock(holder, value, releaseTime); return true; } function _unlock(address holder, uint256 idx) internal returns(bool) { LockInfo storage lockinfo = timelockList[holder][idx]; uint256 releaseAmount = lockinfo._amount; delete timelockList[holder][idx]; timelockList[holder][idx] = timelockList[holder][timelockList[holder].length.sub(1)]; timelockList[holder].length -=1; emit Unlock(holder, releaseAmount); _balances[holder] = _balances[holder].add(releaseAmount); return true; } function _autoUnlock(address holder) internal returns(bool) { for(uint256 idx =0; idx < timelockList[holder].length ; idx++ ) { if (timelockList[holder][idx]._releaseTime <= now) { // If lockupinfo was deleted, loop restart at same position. if( _unlock(holder, idx) ) { idx -=1; } } } return true; } }
Total number of tokens in existence/
function totalSupply() public view returns (uint256) { return _totalSupply; }
208
./full_match/97/0x92094b9510f5aD09Ee7c6FdcEAdad96Add1052bE/sources/browser/cubbusdlp/PancakePair.sol
this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'Pancake: INSUFFICIENT_OUTPUT_AMOUNT'); require(amount0Out < _reserve0 && amount1Out < _reserve1, 'Pancake: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'Pancake: INVALID_TO'); if (data.length > 0) IPancakeCallee(to).pancakeCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'Pancake: INSUFFICIENT_INPUT_AMOUNT'); uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(2)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(2)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'Pancake: K');
3,292,669
pragma solidity ^0.4.24; pragma experimental "v0.5.0"; import {PackageDB} from "./PackageDB.sol"; import {ReleaseDB} from "./ReleaseDB.sol"; import {ReleaseValidator} from "./ReleaseValidator.sol"; import {PackageRegistryInterface} from "./PackageRegistryInterface.sol"; import {Authorized} from "./Authority.sol"; /// @title Database contract for a package index. /// @author Tim Coulter <[email protected]>, Piper Merriam <[email protected]> contract PackageRegistry is Authorized, PackageRegistryInterface { PackageDB private packageDb; ReleaseDB private releaseDb; ReleaseValidator private releaseValidator; // Events event VersionRelease(string packageName, string version, string manifestURI); event PackageTransfer(address indexed oldOwner, address indexed newOwner); // // Administrative API // /// @dev Sets the address of the PackageDb contract. /// @param newPackageDb The address to set for the PackageDb. function setPackageDb(address newPackageDb) public auth returns (bool) { packageDb = PackageDB(newPackageDb); return true; } /// @dev Sets the address of the ReleaseDb contract. /// @param newReleaseDb The address to set for the ReleaseDb. function setReleaseDb(address newReleaseDb) public auth returns (bool) { releaseDb = ReleaseDB(newReleaseDb); return true; } /// @dev Sets the address of the ReleaseValidator contract. /// @param newReleaseValidator The address to set for the ReleaseValidator. function setReleaseValidator(address newReleaseValidator) public auth returns (bool) { releaseValidator = ReleaseValidator(newReleaseValidator); return true; } // // +-------------+ // | Write API | // +-------------+ // /// @dev Creates a a new release for the named package. If this is the first release for the given package then this will also assign msg.sender as the owner of the package. Returns success. /// @notice Will create a new release the given package with the given release information. /// @param packageName Package name /// @param version Version string (ex: '1.0.0') /// @param manifestURI The URI for the release manifest for this release. function release( string packageName, string version, string manifestURI ) public auth returns (bytes32 releaseId) { require(address(packageDb) != 0x0, "escape:PackageIndex:package-db-not-set"); require(address(releaseDb) != 0x0, "escape:PackageIndex:release-db-not-set"); require(address(releaseValidator) != 0x0, "escape:PackageIndex:release-validator-not-set"); bytes32 versionHash = releaseDb.hashVersion(version); // If the version for this release is not in the version database, populate // it. This must happen prior to validation to ensure that the version is // present in the releaseDb. if (!releaseDb.versionExists(versionHash)) { releaseDb.setVersion(version); } // Run release validator. This method reverts with an error message string // on failure. releaseValidator.validateRelease( packageDb, releaseDb, msg.sender, packageName, version, manifestURI ); // Compute hashes bool _packageExists = packageExists(packageName); // Both creates the package if it is new as well as updating the updatedAt // timestamp on the package. packageDb.setPackage(packageName); bytes32 nameHash = packageDb.hashName(packageName); // If the package does not yet exist create it and set the owner if (!_packageExists) { packageDb.setPackageOwner(nameHash, msg.sender); } // Create the release and add it to the list of package release hashes. releaseDb.setRelease(nameHash, versionHash, manifestURI); // Log the release. releaseId = releaseDb.hashRelease(nameHash, versionHash); emit VersionRelease(packageName, version, manifestURI); return releaseId; } /// @dev Transfers package ownership to the provider new owner address. /// @notice Will transfer ownership of this package to the provided new owner address. /// @param name Package name /// @param newPackageOwner The address of the new owner. function transferPackageOwner(string name, address newPackageOwner) public auth returns (bool) { if (isPackageOwner(name, msg.sender)) { // Only the package owner may transfer package ownership. return false; } // Lookup the current owner address packageOwner; (packageOwner,,,) = getPackageData(name); // Log the transfer emit PackageTransfer(packageOwner, newPackageOwner); // Update the owner. packageDb.setPackageOwner(packageDb.hashName(name), newPackageOwner); return true; } // // +------------+ // | Read API | // +------------+ // /// @dev Returns the address of the packageDb function getPackageDb() public view returns (address) { return address(packageDb); } /// @dev Returns the address of the releaseDb function getReleaseDb() public view returns (address) { return address(releaseDb); } /// @dev Returns the address of the releaseValidator function getReleaseValidator() public view returns (address) { return address(releaseValidator); } /// @dev Query the existence of a package with the given name. Returns boolean indicating whether the package exists. /// @param name Package name function packageExists(string name) public view returns (bool) { return packageDb.packageExists(packageDb.hashName(name)); } /// @dev Query the existence of a release at the provided version for the named package. Returns boolean indicating whether such a release exists. /// @param name Package name /// @param version Version string (ex: '1.0.0') function releaseExists( string name, string version ) public view returns (bool) { bytes32 nameHash = packageDb.hashName(name); bytes32 versionHash = releaseDb.hashVersion(version); return releaseDb.releaseExists(releaseDb.hashRelease(nameHash, versionHash)); } /// @dev Returns a slice of the array of all package hashes for the named package. /// @param offset The starting index for the slice. /// @param limit The length of the slice function getAllPackageIds(uint offset, uint limit) public view returns( bytes32[] packageIds, uint pointer ) { return packageDb.getAllPackageIds(offset, limit); } /// @dev Retrieves the name for the given name hash. /// @param packageId The name hash of package to lookup the name for. function getPackageName(bytes32 packageId) public view returns (string packageName) { return packageDb.getPackageName(packageId); } /// @dev Returns the package data. /// @param name Package name function getPackageData(string name) public view returns ( address packageOwner, uint createdAt, uint numReleases, uint updatedAt ) { bytes32 nameHash = packageDb.hashName(name); (packageOwner, createdAt, updatedAt) = packageDb.getPackageData(nameHash); numReleases = releaseDb.getNumReleasesForNameHash(nameHash); return (packageOwner, createdAt, numReleases, updatedAt); } /// @dev Returns the release data for the release associated with the given release hash. /// @param releaseId The release hash. function getReleaseData(bytes32 releaseId) public view returns ( string packageName, string version, string manifestURI ) { bytes32 versionHash; bytes32 nameHash; (nameHash,versionHash, ,) = releaseDb.getReleaseData(releaseId); packageName = packageDb.getPackageName(nameHash); version = releaseDb.getVersion(versionHash); manifestURI = releaseDb.getManifestURI(releaseId); return (packageName, version, manifestURI); } /// @dev Returns a slice of the array of all package hashes for the named package. /// @param offset The starting index for the slice. /// @param limit The length of the slice function getAllReleaseIds(string packageName, uint offset, uint limit) public view returns ( bytes32[] releaseIds, uint pointer ) { bytes32 nameHash = packageDb.hashName(packageName); return releaseDb.getAllReleaseIds(nameHash, offset, limit); } /// @dev Returns release id that *would* be generated for a name and version pair on `release`. /// @param packageName Package name /// @param version Version string (ex: '1.0.0') function generateReleaseId(string packageName, string version) public view returns (bytes32 releaseId) { bytes32 nameHash = packageDb.hashName(packageName); bytes32 versionHash = releaseDb.hashVersion(version); return keccak256(abi.encodePacked(nameHash, versionHash)); } /// @dev Returns the release id for a given name and version pair if present on registry. /// @param packageName Package name /// @param version Version string(ex: '1.0.0') function getReleaseId(string packageName, string version) public view returns (bytes32 releaseId) { releaseId = generateReleaseId(packageName, version); bool _releaseExists = releaseDb.releaseExists(releaseId); if (!_releaseExists) { return 0; } return releaseId; } /// @dev Returns the number of packages stored on the registry function numPackageIds() public view returns (uint totalCount) { return packageDb.getNumPackages(); } /// @dev Returns the number of releases for a given package name on the registry /// @param packageName Package name function numReleaseIds(string packageName) public view returns (uint totalCount) { bool _packageExists = packageExists(packageName); if (!_packageExists) { return 0; } bytes32 nameHash = packageDb.hashName(packageName); return releaseDb.getNumReleasesForNameHash(nameHash); } // // +----------------+ // | Internal API | // +----------------+ // /// @dev Returns boolean whether the provided address is the package owner /// @param name The name of the package /// @param _address The address to check function isPackageOwner(string name, address _address) internal view returns (bool) { address packageOwner; (packageOwner,,,) = getPackageData(name); return (packageOwner != _address); } }
Query the existence of a package with the given name. Returns boolean indicating whether the package exists. name Package name
function packageExists(string name) public view returns (bool) { return packageDb.packageExists(packageDb.hashName(name)); }
1,840,465
pragma solidity ^0.5.0; contract GoDice{ uint constant HOUSE_EDGE_PERCENT = 1; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether; uint constant MIN_JACKPOT_BET = 0.1 ether; uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 300000 ether; uint constant MAX_MODULO = 100; uint constant MAX_MASK_MODULO = 40; uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; uint constant BET_EXPIRATION_BLOCKS = 250; address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public owner; address payable private nextOwner; uint public maxProfit; address public secretSigner; uint128 public jackpotSize; uint128 public lockedInBets; struct Bet { uint amount; uint8 modulo; uint8 rollUnder; uint40 placeBlockNumber; uint40 mask; address payable gambler; } mapping (uint => Bet) bets; address public croupier; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint amount); event Payment(address indexed beneficiary, uint amount); event JackpotPayment(address indexed beneficiary, uint amount); // This event is emitted in placeBet to record commit in the logs. event Commit(uint commit); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier."); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address payable _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } // Fallback function deliberately left empty. It&#39;s primary use case // is to top up the bank roll. function () external payable { } // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change the croupier address. function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyOwner { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of dice2.win operation. function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds."); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } function kill() external onlyOwner { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) external payable { // Check that the bet is in &#39;clean&#39; state. Bet storage bet = bets[commit]; require (bet.gambler == address(0), "Bet should be in a &#39;clean&#39; state."); // Validate input data ranges. uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range."); // Check that commit is valid - it has not expired and its signature is valid. require (block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256(abi.encodePacked(commitLastBlock, commit)); require (secretSigner == ecrecover(signatureHash, v, r, s), "ECDSA signature is not valid."); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the dice2.win whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo."); rollUnder = betMask; } // Winning amount and jackpot increase. uint possibleWinAmount; uint jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); // Enforce max profit limit. require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation."); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet."); // Record commit in logs. emit Commit(commit); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can&#39;t be queried by EVM."); require (blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can&#39;t be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private { // Fetch bet parameters into local variables (to save gas). uint amount = bet.amount; uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address payable gambler = bet.gambler; // Check that bet is in &#39;active&#39; state. require (amount != 0, "Bet should be in an &#39;active&#39; state"); // Move bet into &#39;processed&#39; state already. bet.amount = 0; bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint dice = uint(entropy) % modulo; uint diceWinAmount; uint _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); uint diceWin = 0; uint jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin); } function refundBet(uint commit) external { // Check that bet is in &#39;active&#39; state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an &#39;active&#39; state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can&#39;t be queried by EVM."); // Move bet into &#39;processed&#39; state, release funds. bet.amount = 0; uint diceWinAmount; uint jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); // Send the refund. sendFunds(bet.gambler, amount, amount); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) { require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range."); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require (houseEdge + jackpotFee <= amount, "Bet doesn&#39;t even cover house edge."); winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder; } // Helper routine to process the payment. function sendFunds(address payable beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) { // (Safe) assumption - nobody will write into RAM during this method invocation. uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) } uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot; for (;; offset += blobLength) { assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check."); offset += 6; assembly { calldatacopy(scratchBuf2, offset, unclesLength) } memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly { seedHash := keccak256(scratchBuf2, unclesLength) } offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := keccak256(scratchBuf1, blobLength) } } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. // RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])] function requireCorrectReceipt(uint offset) view private { uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string."); offset += pathHeaderByte - 0x7f; } uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k."); offset += 3; uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k."); offset += 3; uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require (statusByte == 0x1, "Status should be success."); offset += 1; uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string."); offset += cumGasHeaderByte - 0x7f; } uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long."); offset += 256 + 3; uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long."); offset += 2; uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long."); offset += 2; uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require (addressHeaderByte == 0x94, "Address is 20 bytes long."); uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } require (logAddress == uint(address(this))); } // Memory copy. function memcpy(uint dest, uint src, uint len) pure private { // Full 32 byte words for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function TestRecover(uint msgA,uint msgB, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes32 msgHash = keccak256(abi.encodePacked(msgA,msgB)); return ecrecover(msgHash, v, r, s); } function getSecretSigner() view public returns(address) { return secretSigner; } }
"commit" for bet settlement can only be obtained by hashing a "reveal". Check that canonical block hash can still be verified. Verify placeBet receipt. Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. Settle bet using reveal and uncleHash as entropy sources.
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can&#39;t be queried by EVM."); requireCorrectReceipt(4 + 32 + 32 + 4); bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); settleBetCommon(bet, reveal, uncleHash); }
6,607,653
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; /** * @title WAMPL (Wrapped AMPL). * * @dev A fixed-balance ERC-20 wrapper for the AMPL rebasing token. * * Users deposit AMPL into this contract and are minted wAMPL. * * Each account's wAMPL balance represents the fixed percentage ownership * of AMPL's market cap. * * For example: 100K wAMPL => 1% of the AMPL market cap * when the AMPL supply is 100M, 100K wAMPL will be redeemable for 1M AMPL * when the AMPL supply is 500M, 100K wAMPL will be redeemable for 5M AMPL * and so on. * * We call wAMPL the "wrapper" token and AMPL the "underlying" or "wrapped" token. */ contract WAMPL is ERC20, ERC20Permit { using SafeERC20 for IERC20; //-------------------------------------------------------------------------- // Constants /// @dev The maximum wAMPL supply. uint256 public constant MAX_WAMPL_SUPPLY = 10000000 * (10**18); // 10 M //-------------------------------------------------------------------------- // Attributes /// @dev The reference to the AMPL token. address private immutable _ampl; //-------------------------------------------------------------------------- /// @param ampl The AMPL ERC20 token address. /// @param name_ The wAMPL ERC20 name. /// @param symbol_ The wAMPL ERC20 symbol. constructor( address ampl, string memory name_, string memory symbol_ ) ERC20(name_, symbol_) ERC20Permit(name_) { _ampl = ampl; } //-------------------------------------------------------------------------- // WAMPL write methods /// @notice Transfers AMPLs from {msg.sender} and mints wAMPLs. /// /// @param wamples The amount of wAMPLs to mint. /// @return The amount of AMPLs deposited. function mint(uint256 wamples) external returns (uint256) { uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _deposit(_msgSender(), _msgSender(), amples, wamples); return amples; } /// @notice Transfers AMPLs from {msg.sender} and mints wAMPLs, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @param wamples The amount of wAMPLs to mint. /// @return The amount of AMPLs deposited. function mintFor(address to, uint256 wamples) external returns (uint256) { uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _deposit(_msgSender(), to, amples, wamples); return amples; } /// @notice Burns wAMPLs from {msg.sender} and transfers AMPLs back. /// /// @param wamples The amount of wAMPLs to burn. /// @return The amount of AMPLs withdrawn. function burn(uint256 wamples) external returns (uint256) { uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), _msgSender(), amples, wamples); return amples; } /// @notice Burns wAMPLs from {msg.sender} and transfers AMPLs back, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @param wamples The amount of wAMPLs to burn. /// @return The amount of AMPLs withdrawn. function burnTo(address to, uint256 wamples) external returns (uint256) { uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return amples; } /// @notice Burns all wAMPLs from {msg.sender} and transfers AMPLs back. /// /// @return The amount of AMPLs withdrawn. function burnAll() external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), _msgSender(), amples, wamples); return amples; } /// @notice Burns all wAMPLs from {msg.sender} and transfers AMPLs back, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @return The amount of AMPLs withdrawn. function burnAllTo(address to) external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return amples; } /// @notice Transfers AMPLs from {msg.sender} and mints wAMPLs. /// /// @param amples The amount of AMPLs to deposit. /// @return The amount of wAMPLs minted. function deposit(uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _deposit(_msgSender(), _msgSender(), amples, wamples); return wamples; } /// @notice Transfers AMPLs from {msg.sender} and mints wAMPLs, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @param amples The amount of AMPLs to deposit. /// @return The amount of wAMPLs minted. function depositFor(address to, uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _deposit(_msgSender(), to, amples, wamples); return wamples; } /// @notice Burns wAMPLs from {msg.sender} and transfers AMPLs back. /// /// @param amples The amount of AMPLs to withdraw. /// @return The amount of burnt wAMPLs. function withdraw(uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _withdraw(_msgSender(), _msgSender(), amples, wamples); return wamples; } /// @notice Burns wAMPLs from {msg.sender} and transfers AMPLs back, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @param amples The amount of AMPLs to withdraw. /// @return The amount of burnt wAMPLs. function withdrawTo(address to, uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return wamples; } /// @notice Burns all wAMPLs from {msg.sender} and transfers AMPLs back. /// /// @return The amount of burnt wAMPLs. function withdrawAll() external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), _msgSender(), amples, wamples); return wamples; } /// @notice Burns all wAMPLs from {msg.sender} and transfers AMPLs back, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @return The amount of burnt wAMPLs. function withdrawAllTo(address to) external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return wamples; } //-------------------------------------------------------------------------- // WAMPL view methods /// @return The address of the underlying "wrapped" token ie) AMPL. function underlying() external view returns (address) { return _ampl; } /// @return The total AMPLs held by this contract. function totalUnderlying() external view returns (uint256) { return _wampleToAmple(totalSupply(), _queryAMPLSupply()); } /// @param owner The account address. /// @return The AMPL balance redeemable by the owner. function balanceOfUnderlying(address owner) external view returns (uint256) { return _wampleToAmple(balanceOf(owner), _queryAMPLSupply()); } /// @param amples The amount of AMPL tokens. /// @return The amount of wAMPL tokens exchangeable. function underlyingToWrapper(uint256 amples) external view returns (uint256) { return _ampleToWample(amples, _queryAMPLSupply()); } /// @param wamples The amount of wAMPL tokens. /// @return The amount of AMPL tokens exchangeable. function wrapperToUnderlying(uint256 wamples) external view returns (uint256) { return _wampleToAmple(wamples, _queryAMPLSupply()); } //-------------------------------------------------------------------------- // Private methods /// @dev Internal helper function to handle deposit state change. /// @param from The initiator wallet. /// @param to The beneficiary wallet. /// @param amples The amount of AMPLs to deposit. /// @param wamples The amount of wAMPLs to mint. function _deposit( address from, address to, uint256 amples, uint256 wamples ) private { IERC20(_ampl).safeTransferFrom(from, address(this), amples); _mint(to, wamples); } /// @dev Internal helper function to handle withdraw state change. /// @param from The initiator wallet. /// @param to The beneficiary wallet. /// @param amples The amount of AMPLs to withdraw. /// @param wamples The amount of wAMPLs to burn. function _withdraw( address from, address to, uint256 amples, uint256 wamples ) private { _burn(from, wamples); IERC20(_ampl).safeTransfer(to, amples); } /// @dev Queries the current total supply of AMPL. /// @return The current AMPL supply. function _queryAMPLSupply() private view returns (uint256) { return IERC20(_ampl).totalSupply(); } //-------------------------------------------------------------------------- // Pure methods /// @dev Converts AMPLs to wAMPL amount. function _ampleToWample(uint256 amples, uint256 totalAMPLSupply) private pure returns (uint256) { return (amples * MAX_WAMPL_SUPPLY) / totalAMPLSupply; } /// @dev Converts wAMPLs amount to AMPLs. function _wampleToAmple(uint256 wamples, uint256 totalAMPLSupply) private pure returns (uint256) { return (wamples * totalAMPLSupply) / MAX_WAMPL_SUPPLY; } } // 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; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation 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. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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.8.0; import "./ECDSA.sol"; /** * @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 */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; 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) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } }
Burns all wAMPLs from {msg.sender} and transfers AMPLs back, to the specified beneficiary. to The beneficiary wallet. return The amount of burnt wAMPLs.
function withdrawAllTo(address to) external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return wamples; }
10,434,885
pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @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); } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: contracts/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. * this contract is slightly modified from original zeppelin version to * enable testing mode and not forward to fundraiser address on every payment */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } // File: contracts/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised * this contract was kept the same as the original zeppelin version * only change was to inheriet the modified crowdsale instead of the * original one */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } // File: zeppelin-solidity/contracts/lifecycle/TokenDestructible.sol /** * @title TokenDestructible: * @author Remco Bloemen <remco@2π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { function TokenDestructible() public payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for(uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } // File: contracts/SpecialRatedCrowdsale.sol /** * SpecialRatedCrowdsale contract * donors putting in more than a certain number of ethers will receive a special rate */ contract SpecialRatedCrowdsale is Crowdsale, TokenDestructible { mapping(address => uint) addressToSpecialRates; function SpecialRatedCrowdsale() { } function addToSpecialRatesMapping(address _address, uint specialRate) onlyOwner public { addressToSpecialRates[_address] = specialRate; } function removeFromSpecialRatesMapping(address _address) onlyOwner public { delete addressToSpecialRates[_address]; } function querySpecialRateForAddress(address _address) onlyOwner public returns(uint) { return addressToSpecialRates[_address]; } function buyTokens(address beneficiary) public payable { if (addressToSpecialRates[beneficiary] != 0) { rate = addressToSpecialRates[beneficiary]; } super.buyTokens(beneficiary); } } // File: contracts/ERC223ReceivingContract.sol /** * @title Contract that will work with ERC223 tokens. **/ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } // File: contracts/ERC223.sol contract ERC223 is BasicToken { function transfer(address _to, uint _value, bytes _data) public returns (bool) { super.transfer(_to, _value); // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); } function transfer(address _to, uint _value) public returns (bool) { super.transfer(_to, _value); // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(msg.sender, _to, _value, empty); } event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } // File: zeppelin-solidity/contracts/token/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/token/PausableToken.sol /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/YoloToken.sol /** @title YoloToken - Token for the UltraYOLO lottery protocol * @author UltraYOLO The totalSupply for YOLO token will be 4 Billion **/ contract YoloToken is CappedToken, PausableToken, ERC223 { string public constant name = "Yolo"; string public constant symbol = "YOLO"; uint public constant decimals = 18; function YoloToken(uint256 _totalSupply) CappedToken(_totalSupply) { paused = true; } } // File: contracts/YoloTokenPresaleRound2.sol /** * @title YoloTokenPresaleRound2 * @author UltraYOLO * Based on widely-adopted OpenZepplin project * A total of 200,000,000 YOLO tokens will be sold during presale at a discount rate of 25% * Supporters who purchase more than 10 ETH worth of YOLO token will have a discount of 35% * Total supply of presale + presale_round_2 + mainsale will be 2,000,000,000 */ contract YoloTokenPresaleRound2 is SpecialRatedCrowdsale, CappedCrowdsale, Pausable { using SafeMath for uint256; uint256 public rateTierHigher; uint256 public rateTierNormal; function YoloTokenPresaleRound2 (uint256 _cap, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _tokenAddress) CappedCrowdsale(_cap) Crowdsale(_startTime, _endTime, _rate, _wallet) { token = YoloToken(_tokenAddress); rateTierHigher = _rate.mul(27).div(20); rateTierNormal = _rate.mul(5).div(4); } function () external payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { require(validPurchase()); if (msg.value >= 10 ether) { rate = rateTierHigher; } else { rate = rateTierNormal; } super.buyTokens(beneficiary); } function validPurchase() internal view returns (bool) { return super.validPurchase() && !paused; } function setCap(uint256 _cap) onlyOwner public { cap = _cap; } function setStartTime(uint256 _startTime) onlyOwner public { startTime = _startTime; } function setEndTime(uint256 _endTime) onlyOwner public { endTime = _endTime; } function setRate(uint256 _rate) onlyOwner public { rate = _rate; rateTierHigher = _rate.mul(27).div(20); rateTierNormal = _rate.mul(5).div(4); } function setWallet(address _wallet) onlyOwner public { wallet = _wallet; } function withdrawFunds(uint256 amount) onlyOwner public { wallet.transfer(amount); } function resetTokenOwnership() onlyOwner public { token.transferOwnership(owner); } }
Standard function transfer similar to ERC20 transfer with no _data . Added due to backwards compatibility reasons . Retrieve the size of the code on target address, this needs assembly .
function transfer(address _to, uint _value, bytes _data) public returns (bool) { super.transfer(_to, _value); uint codeLength; assembly { codeLength := extcodesize(_to) } if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); }
10,434,529
/** *Submitted for verification at Etherscan.io on 2020-05-01 */ /* Copyright 2020 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/protocol/v1/traders/P1TraderConstants.sol /** * @title P1TraderConstants * @author dYdX * * @notice Constants for traderFlags set by contracts implementing the I_P1Trader interface. */ contract P1TraderConstants { bytes32 constant internal TRADER_FLAG_ORDERS = bytes32(uint256(1)); bytes32 constant internal TRADER_FLAG_LIQUIDATION = bytes32(uint256(2)); bytes32 constant internal TRADER_FLAG_DELEVERAGING = bytes32(uint256(4)); } // File: contracts/protocol/lib/BaseMath.sol /** * @title BaseMath * @author dYdX * * @dev Arithmetic for fixed-point numbers with 18 decimals of precision. */ library BaseMath { using SafeMath for uint256; // The number One in the BaseMath system. uint256 constant internal BASE = 10 ** 18; /** * @dev Getter function since constants can't be read directly from libraries. */ function base() internal pure returns (uint256) { return BASE; } /** * @dev Multiplies a value by a base value (result is rounded down). */ function baseMul( uint256 value, uint256 baseValue ) internal pure returns (uint256) { return value.mul(baseValue).div(BASE); } /** * @dev Multiplies a value by a base value (result is rounded down). * Intended as an alternaltive to baseMul to prevent overflow, when `value` is known * to be divisible by `BASE`. */ function baseDivMul( uint256 value, uint256 baseValue ) internal pure returns (uint256) { return value.div(BASE).mul(baseValue); } /** * @dev Multiplies a value by a base value (result is rounded up). */ function baseMulRoundUp( uint256 value, uint256 baseValue ) internal pure returns (uint256) { if (value == 0 || baseValue == 0) { return 0; } return value.mul(baseValue).sub(1).div(BASE).add(1); } } // File: contracts/protocol/lib/Math.sol /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return target * (numerator / denominator), rounded down. */ function getFraction( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /** * @dev Return target * (numerator / denominator), rounded up. */ function getFractionRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // File: contracts/protocol/lib/Storage.sol /** * @title Storage * @author dYdX * * @dev Storage library for reading/writing storage at a low level. */ library Storage { /** * @dev Performs an SLOAD and returns the data in the slot. */ function load( bytes32 slot ) internal view returns (bytes32) { bytes32 result; /* solium-disable-next-line security/no-inline-assembly */ assembly { result := sload(slot) } return result; } /** * @dev Performs an SSTORE to save the value to the slot. */ function store( bytes32 slot, bytes32 value ) internal { /* solium-disable-next-line security/no-inline-assembly */ assembly { sstore(slot, value) } } } // File: contracts/protocol/lib/Adminable.sol /** * @title Adminable * @author dYdX * * @dev EIP-1967 Proxy Admin contract. */ contract Adminable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will revert. */ modifier onlyAdmin() { require( msg.sender == getAdmin(), "Adminable: caller is not admin" ); _; } /** * @return The EIP-1967 proxy admin */ function getAdmin() public view returns (address) { return address(uint160(uint256(Storage.load(ADMIN_SLOT)))); } } // File: contracts/protocol/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ 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; } } // File: contracts/protocol/v1/lib/P1Types.sol /** * @title P1Types * @author dYdX * * @dev Library for common types used in PerpetualV1 contracts. */ library P1Types { // ============ Structs ============ /** * @dev Used to represent the global index and each account's cached index. * Used to settle funding paymennts on a per-account basis. */ struct Index { uint32 timestamp; bool isPositive; uint128 value; } /** * @dev Used to track the signed margin balance and position balance values for each account. */ struct Balance { bool marginIsPositive; bool positionIsPositive; uint120 margin; uint120 position; } /** * @dev Used to cache commonly-used variables that are relatively gas-intensive to obtain. */ struct Context { uint256 price; uint256 minCollateral; Index index; } /** * @dev Used by contracts implementing the I_P1Trader interface to return the result of a trade. */ struct TradeResult { uint256 marginAmount; uint256 positionAmount; bool isBuy; // From taker's perspective. bytes32 traderFlags; } } // File: contracts/protocol/v1/impl/P1Storage.sol /** * @title P1Storage * @author dYdX * * @notice Storage contract. Contains or inherits from all contracts that have ordered storage. */ contract P1Storage is Adminable, ReentrancyGuard { mapping(address => P1Types.Balance) internal _BALANCES_; mapping(address => P1Types.Index) internal _LOCAL_INDEXES_; mapping(address => bool) internal _GLOBAL_OPERATORS_; mapping(address => mapping(address => bool)) internal _LOCAL_OPERATORS_; address internal _TOKEN_; address internal _ORACLE_; address internal _FUNDER_; P1Types.Index internal _GLOBAL_INDEX_; uint256 internal _MIN_COLLATERAL_; bool internal _FINAL_SETTLEMENT_ENABLED_; uint256 internal _FINAL_SETTLEMENT_PRICE_; } // File: contracts/protocol/v1/intf/I_P1Oracle.sol /** * @title I_P1Oracle * @author dYdX * * @notice Interface that PerpetualV1 Price Oracles must implement. */ interface I_P1Oracle { /** * @notice Returns the price of the underlying asset relative to the margin token. * * @return The price as a fixed-point number with 18 decimals. */ function getPrice() external view returns (uint256); } // File: contracts/protocol/v1/impl/P1Getters.sol /** * @title P1Getters * @author dYdX * * @notice Contract for read-only getters. */ contract P1Getters is P1Storage { // ============ Account Getters ============ /** * @notice Get the balance of an account, without accounting for changes in the index. * * @param account The address of the account to query the balances of. * @return The balances of the account. */ function getAccountBalance( address account ) public //inject PUBLIC FUNC TO EXTERNAL view returns (P1Types.Balance memory) { return _BALANCES_[account]; } /** * @notice Gets the most recently cached index of an account. * * @param account The address of the account to query the index of. * @return The index of the account. */ function getAccountIndex( address account ) public //inject PUBLIC FUNC TO EXTERNAL view returns (P1Types.Index memory) { return _LOCAL_INDEXES_[account]; } /** * @notice Gets the local operator status of an operator for a particular account. * * @param account The account to query the operator for. * @param operator The address of the operator to query the status of. * @return True if the operator is a local operator of the account, false otherwise. */ function getIsLocalOperator( address account, address operator ) public //inject PUBLIC FUNC TO EXTERNAL view returns (bool) { return _LOCAL_OPERATORS_[account][operator]; } // ============ Global Getters ============ /** * @notice Gets the global operator status of an address. * * @param operator The address of the operator to query the status of. * @return True if the address is a global operator, false otherwise. */ function getIsGlobalOperator( address operator ) public //inject PUBLIC FUNC TO EXTERNAL view returns (bool) { return _GLOBAL_OPERATORS_[operator]; } /** * @notice Gets the address of the ERC20 margin contract used for margin deposits. * * @return The address of the ERC20 token. */ function getTokenContract() public //inject PUBLIC FUNC TO EXTERNAL view returns (address) { return _TOKEN_; } /** * @notice Gets the current address of the price oracle contract. * * @return The address of the price oracle contract. */ function getOracleContract() public //inject PUBLIC FUNC TO EXTERNAL view returns (address) { return _ORACLE_; } /** * @notice Gets the current address of the funder contract. * * @return The address of the funder contract. */ function getFunderContract() public //inject PUBLIC FUNC TO EXTERNAL view returns (address) { return _FUNDER_; } /** * @notice Gets the most recently cached global index. * * @return The most recently cached global index. */ function getGlobalIndex() public //inject PUBLIC FUNC TO EXTERNAL view returns (P1Types.Index memory) { return _GLOBAL_INDEX_; } /** * @notice Gets minimum collateralization ratio of the protocol. * * @return The minimum-acceptable collateralization ratio, returned as a fixed-point number with * 18 decimals of precision. */ function getMinCollateral() public //inject PUBLIC FUNC TO EXTERNAL view returns (uint256) { return _MIN_COLLATERAL_; } /** * @notice Gets the status of whether final-settlement was initiated by the Admin. * * @return True if final-settlement was enabled, false otherwise. */ function getFinalSettlementEnabled() public //inject PUBLIC FUNC TO EXTERNAL view returns (bool) { return _FINAL_SETTLEMENT_ENABLED_; } // ============ Authorized External Getters ============ /** * @notice Gets the price returned by the oracle. * @dev Only able to be called by global operators. * * @return The price returned by the current price oracle. */ function getOraclePrice() public //inject PUBLIC FUNC TO EXTERNAL view returns (uint256) { require( _GLOBAL_OPERATORS_[msg.sender], "Oracle price requester not global operator" ); return I_P1Oracle(_ORACLE_).getPrice(); } // ============ Public Getters ============ /** * @notice Gets whether an address has permissions to operate an account. * * @param account The account to query. * @param operator The address to query. * @return True if the operator has permission to operate the account, * and false otherwise. */ function hasAccountPermissions( address account, address operator ) public view returns (bool) { return account == operator || _GLOBAL_OPERATORS_[operator] || _LOCAL_OPERATORS_[account][operator]; } } // File: contracts/protocol/lib/SafeCast.sol /** * @title SafeCast * @author dYdX * * @dev Library for casting uint256 to other types of uint. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (i.e. when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * - `value` must fit into 128 bits. */ function toUint128( uint256 value ) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (i.e. when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * - `value` must fit into 120 bits. */ function toUint120( uint256 value ) internal pure returns (uint120) { require(value < 2**120, "SafeCast: value doesn\'t fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (i.e. when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * - `value` must fit into 32 bits. */ function toUint32( uint256 value ) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } } // File: contracts/protocol/lib/SignedMath.sol /** * @title SignedMath * @author dYdX * * @dev SignedMath library for doing math with signed integers. */ library SignedMath { using SafeMath for uint256; // ============ Structs ============ struct Int { uint256 value; bool isPositive; } // ============ Functions ============ /** * @dev Returns a new signed integer equal to a signed integer plus an unsigned integer. */ function add( Int memory sint, uint256 value ) internal pure returns (Int memory) { if (sint.isPositive) { return Int({ value: value.add(sint.value), isPositive: true }); } if (sint.value < value) { return Int({ value: value.sub(sint.value), isPositive: true }); } return Int({ value: sint.value.sub(value), isPositive: false }); } /** * @dev Returns a new signed integer equal to a signed integer minus an unsigned integer. */ function sub( Int memory sint, uint256 value ) internal pure returns (Int memory) { if (!sint.isPositive) { return Int({ value: value.add(sint.value), isPositive: false }); } if (sint.value > value) { return Int({ value: sint.value.sub(value), isPositive: true }); } return Int({ value: value.sub(sint.value), isPositive: false }); } /** * @dev Returns a new signed integer equal to a signed integer plus another signed integer. */ function signedAdd( Int memory augend, Int memory addend ) internal pure returns (Int memory) { return addend.isPositive ? add(augend, addend.value) : sub(augend, addend.value); } /** * @dev Returns a new signed integer equal to a signed integer minus another signed integer. */ function signedSub( Int memory minuend, Int memory subtrahend ) internal pure returns (Int memory) { return subtrahend.isPositive ? sub(minuend, subtrahend.value) : add(minuend, subtrahend.value); } /** * @dev Returns true if signed integer `a` is greater than signed integer `b`, false otherwise. */ function gt( Int memory a, Int memory b ) internal pure returns (bool) { if (a.isPositive) { if (b.isPositive) { return a.value > b.value; } else { // True, unless both values are zero. return a.value != 0 || b.value != 0; } } else { if (b.isPositive) { return false; } else { return a.value < b.value; } } } /** * @dev Returns the minimum of signed integers `a` and `b`. */ function min( Int memory a, Int memory b ) internal pure returns (Int memory) { return gt(b, a) ? a : b; } /** * @dev Returns the maximum of signed integers `a` and `b`. */ function max( Int memory a, Int memory b ) internal pure returns (Int memory) { return gt(a, b) ? a : b; } } // File: contracts/protocol/v1/lib/P1BalanceMath.sol /** * @title P1BalanceMath * @author dYdX * * @dev Library for manipulating P1Types.Balance structs. */ library P1BalanceMath { using BaseMath for uint256; using SafeCast for uint256; using SafeMath for uint256; using SignedMath for SignedMath.Int; using P1BalanceMath for P1Types.Balance; // ============ Constants ============ uint256 private constant FLAG_MARGIN_IS_POSITIVE = 1 << (8 * 31); uint256 private constant FLAG_POSITION_IS_POSITIVE = 1 << (8 * 15); // ============ Functions ============ /** * @dev Create a copy of the balance struct. */ function copy( P1Types.Balance memory balance ) internal pure returns (P1Types.Balance memory) { return P1Types.Balance({ marginIsPositive: balance.marginIsPositive, positionIsPositive: balance.positionIsPositive, margin: balance.margin, position: balance.position }); } /** * @dev In-place add amount to balance.margin. */ function addToMargin( P1Types.Balance memory balance, uint256 amount ) internal pure { SignedMath.Int memory signedMargin = balance.getMargin(); signedMargin = signedMargin.add(amount); balance.setMargin(signedMargin); } /** * @dev In-place subtract amount from balance.margin. */ function subFromMargin( P1Types.Balance memory balance, uint256 amount ) internal pure { SignedMath.Int memory signedMargin = balance.getMargin(); signedMargin = signedMargin.sub(amount); balance.setMargin(signedMargin); } /** * @dev In-place add amount to balance.position. */ function addToPosition( P1Types.Balance memory balance, uint256 amount ) internal pure { SignedMath.Int memory signedPosition = balance.getPosition(); signedPosition = signedPosition.add(amount); balance.setPosition(signedPosition); } /** * @dev In-place subtract amount from balance.position. */ function subFromPosition( P1Types.Balance memory balance, uint256 amount ) internal pure { SignedMath.Int memory signedPosition = balance.getPosition(); signedPosition = signedPosition.sub(amount); balance.setPosition(signedPosition); } /** * @dev Returns the positive and negative values of the margin and position together, given a * price, which is used as a conversion rate between the two currencies. * * No rounding occurs here--the returned values are "base values" with extra precision. */ function getPositiveAndNegativeValue( P1Types.Balance memory balance, uint256 price ) internal pure returns (uint256, uint256) { uint256 positiveValue = 0; uint256 negativeValue = 0; // add value of margin if (balance.marginIsPositive) { positiveValue = uint256(balance.margin).mul(BaseMath.base()); } else { negativeValue = uint256(balance.margin).mul(BaseMath.base()); } // add value of position uint256 positionValue = uint256(balance.position).mul(price); if (balance.positionIsPositive) { positiveValue = positiveValue.add(positionValue); } else { negativeValue = negativeValue.add(positionValue); } return (positiveValue, negativeValue); } /** * @dev Returns a compressed bytes32 representation of the balance for logging. */ function toBytes32( P1Types.Balance memory balance ) internal pure returns (bytes32) { uint256 result = uint256(balance.position) | (uint256(balance.margin) << 128) | (balance.marginIsPositive ? FLAG_MARGIN_IS_POSITIVE : 0) | (balance.positionIsPositive ? FLAG_POSITION_IS_POSITIVE : 0); return bytes32(result); } // ============ Helper Functions ============ /** * @dev Returns a SignedMath.Int version of the margin in balance. */ function getMargin( P1Types.Balance memory balance ) internal pure returns (SignedMath.Int memory) { return SignedMath.Int({ value: balance.margin, isPositive: balance.marginIsPositive }); } /** * @dev Returns a SignedMath.Int version of the position in balance. */ function getPosition( P1Types.Balance memory balance ) internal pure returns (SignedMath.Int memory) { return SignedMath.Int({ value: balance.position, isPositive: balance.positionIsPositive }); } /** * @dev In-place modify the signed margin value of a balance. */ function setMargin( P1Types.Balance memory balance, SignedMath.Int memory newMargin ) internal pure { balance.margin = newMargin.value.toUint120(); balance.marginIsPositive = newMargin.isPositive; } /** * @dev In-place modify the signed position value of a balance. */ function setPosition( P1Types.Balance memory balance, SignedMath.Int memory newPosition ) internal pure { balance.position = newPosition.value.toUint120(); balance.positionIsPositive = newPosition.isPositive; } } // File: contracts/protocol/v1/traders/P1Liquidation.sol /** * @title P1Liquidation * @author dYdX * * @notice Contract allowing accounts to be liquidated by other accounts. */ contract P1Liquidation is P1TraderConstants { using SafeMath for uint256; using Math for uint256; using P1BalanceMath for P1Types.Balance; // ============ Structs ============ struct TradeData { uint256 amount; bool isBuy; // from taker's perspective bool allOrNothing; // if true, will revert if maker's position is less than the amount } // ============ Events ============ event LogLiquidated( address indexed maker, address indexed taker, uint256 amount, bool isBuy, // from taker's perspective uint256 oraclePrice ); // ============ Immutable Storage ============ // address of the perpetual contract address public _PERPETUAL_V1_; // ============ Constructor ============ constructor ( address perpetualV1 ) public { _PERPETUAL_V1_ = perpetualV1; } // ============ External Functions ============ /** * @notice Allows an account below the minimum collateralization to be liquidated by another * account. This allows the account to be partially or fully subsumed by the liquidator. * @dev Emits the LogLiquidated event. * * @param sender The address that called the trade() function on PerpetualV1. * @param maker The account to be liquidated. * @param taker The account of the liquidator. * @param price The current oracle price of the underlying asset. * @param data A struct of type TradeData. * @return The amounts to be traded, and flags indicating that a liquidation occurred. */ function trade( address sender, address maker, address taker, uint256 price, bytes calldata data, bytes32 /* traderFlags */ ) external returns (P1Types.TradeResult memory) { address perpetual = _PERPETUAL_V1_; require( msg.sender == perpetual, "msg.sender must be PerpetualV1" ); require( P1Getters(perpetual).getIsGlobalOperator(sender), "Sender is not a global operator" ); TradeData memory tradeData = abi.decode(data, (TradeData)); P1Types.Balance memory makerBalance = P1Getters(perpetual).getAccountBalance(maker); _verifyTrade( tradeData, makerBalance, perpetual, price ); // Bound the execution amount by the size of the maker position. uint256 amount = Math.min(tradeData.amount, makerBalance.position); // When partially liquidating the maker, maintain the same position/margin ratio. // Ensure the collateralization of the maker does not decrease. uint256 marginAmount; if (tradeData.isBuy) { marginAmount = uint256(makerBalance.margin).getFractionRoundUp( amount, makerBalance.position ); } else { marginAmount = uint256(makerBalance.margin).getFraction(amount, makerBalance.position); } emit LogLiquidated( maker, taker, amount, tradeData.isBuy, price ); return P1Types.TradeResult({ marginAmount: marginAmount, positionAmount: amount, isBuy: tradeData.isBuy, traderFlags: TRADER_FLAG_LIQUIDATION }); } // ============ Helper Functions ============ function _verifyTrade( TradeData memory tradeData, P1Types.Balance memory makerBalance, address perpetual, uint256 price ) private view { require( _isUndercollateralized(makerBalance, perpetual, price), "Cannot liquidate since maker is not undercollateralized" ); require( !tradeData.allOrNothing || makerBalance.position >= tradeData.amount, "allOrNothing is set and maker position is less than amount" ); require( tradeData.isBuy == makerBalance.positionIsPositive, "liquidation must not increase maker's position size" ); } function _isUndercollateralized( P1Types.Balance memory balance, address perpetual, uint256 price ) private view returns (bool) { uint256 minCollateral = P1Getters(perpetual).getMinCollateral(); (uint256 positive, uint256 negative) = balance.getPositiveAndNegativeValue(price); // See P1Settlement.sol for discussion of overflow risk. return positive.mul(BaseMath.base()) < negative.mul(minCollateral); } }
Gets the current address of the price oracle contract. return The address of the price oracle contract./
function getOracleContract() view returns (address) { return _ORACLE_; }
15,861,704
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title A contract to store and withdraw ether * @dev This contract is vulnerable to re-entrancy attack * see explanation from solidity-by-example.org bellow: * 1. Deploy EtherStore * 2. Deposit 1 Ether each from Account 1 (Alice) and Account 2 (Bob) into EtherStore * 3. Deploy Attack with address of EtherStore * 4. Call Attack.attack sending 1 ether (using Account 3 (Eve)). * You will get 3 Ethers back (2 Ether stolen from Alice and Bob, * plus 1 Ether sent from this contract). * * What happened? * Attack was able to call EtherStore.withdraw multiple times before * EtherStore.withdraw finished executing. * * Here is how the functions were called * - Attack.attack * - EtherStore.deposit * - EtherStore.withdraw * - Attack fallback (receives 1 Ether) * - EtherStore.withdraw * - Attack.fallback (receives 1 Ether) * - EtherStore.withdraw * - Attack fallback (receives 1 Ether) */ contract Etherstore { mapping(address => uint256) public balances; /** * @notice Deposits an amount of ether to Etherstore. */ function deposit() public payable { balances[msg.sender] += msg.value; } /** * @notice Withdraws sender balance from Etherstore. */ function withdraw() public { uint256 balance = balances[msg.sender]; require(balance > 0, "Sender does not have balance"); (bool sent, ) = msg.sender.call{value: balance}(""); require(sent, "Failed to send Ether"); balances[msg.sender] = 0; } /** * @notice Helper funcion to return the Etherstore current balance. */ function getBalance() public view returns (uint256) { return address(this).balance; } }
Withdraws sender balance from Etherstore./
function withdraw() public { uint256 balance = balances[msg.sender]; require(balance > 0, "Sender does not have balance"); require(sent, "Failed to send Ether"); balances[msg.sender] = 0; }
15,858,379
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; interface IERC20 { function approve(address spender, uint256 amount) external returns (bool); function transfer(address _to, uint256 _value) external returns (bool success); } 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 { function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } /* * FlashBorrowerExample is a simple smart contract that enables * to borrow and returns a flash loan. */ contract FlashloanBorrower is IERC3156FlashBorrower { uint public MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; address public admin; constructor() { admin = msg.sender; } //For `flashloanProviderAddress, search for FlashLoanProvider here: //https://docs.equalizer.finance/equalizer-deep-dive/smart-contracts function initiateFlashloan( address flashloanProviderAddress, address token, uint amount, bytes calldata data ) external { IERC3156FlashLender(flashloanProviderAddress).flashLoan( IERC3156FlashBorrower(address(this)), token, amount, data ); } // @dev ERC-3156 Flash loan callback function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external override returns (bytes32) { // Set the allowance to payback the flash loan IERC20(token).approve(msg.sender, MAX_INT); // Build your trading business logic here // e.g., sell on uniswapv2 // e.g., buy on uniswapv3 // Return success to the lender, he will transfer get the funds back if allowance is set accordingly return keccak256('ERC3156FlashBorrower.onFlashLoan'); } function withdraw(address recipient, address token, uint amount) external { require(msg.sender == admin, 'only admin'); IERC20(token).transfer(recipient, amount); } }
For `flashloanProviderAddress, search for FlashLoanProvider here:https:docs.equalizer.finance/equalizer-deep-dive/smart-contracts
function initiateFlashloan( address flashloanProviderAddress, address token, uint amount, bytes calldata data ) external { IERC3156FlashLender(flashloanProviderAddress).flashLoan( IERC3156FlashBorrower(address(this)), token, amount, data ); }
6,428,267
/** *Submitted for verification at Etherscan.io on 2021-04-02 */ /** *Submitted for verification at Etherscan.io on 2020-11-11 */ /** *Submitted for verification at Etherscan.io on 2020-02-28 */ /** *Submitted for verification at Etherscan.io on 2020-01-11 */ pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { using SafeMath for uint256; uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return one ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return one wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev multiplies two wad, rounding half up to the nearest wad * @param a wad * @param b wad * @return the result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { return halfWAD.add(a.mul(b)).div(WAD); } /** * @dev divides two wad, rounding half up to the nearest wad * @param a wad * @param b wad * @return the result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(WAD)).div(b); } /** * @dev multiplies two ray, rounding half up to the nearest ray * @param a ray * @param b ray * @return the result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { return halfRAY.add(a.mul(b)).div(RAY); } /** * @dev divides two ray, rounding half up to the nearest ray * @param a ray * @param b ray * @return the result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(RAY)).div(b); } /** * @dev casts ray down to wad * @param a ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; return halfRatio.add(a).div(WAD_RAY_RATIO); } /** * @dev convert wad up to ray * @param a wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { return a.mul(WAD_RAY_RATIO); } /** * @dev calculates base^exp. The code uses the ModExp precompile * @return base^exp, in ray */ //solium-disable-next-line function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rayMul(x, x); if (n % 2 != 0) { z = rayMul(z, x); } } } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @title VersionedInitializable * * @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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(initializing || isConstructor() || revision > lastInitializedRevision, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure returns(uint256); /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { //solium-disable-next-line assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } } /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } contract AddressStorage { mapping(bytes32 => address) private addresses; function getAddress(bytes32 _key) public view returns (address) { return addresses[_key]; } function _setAddress(bytes32 _key, address _value) internal { addresses[_key] = _value; } } /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } } /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ contract ILendingPoolAddressesProvider { function getLendingPool() public view returns (address); function setLendingPoolImpl(address _pool) public; function getLendingPoolCore() public view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public; function getLendingPoolConfigurator() public view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public; function getLendingPoolDataProvider() public view returns (address); function setLendingPoolDataProviderImpl(address _provider) public; function getLendingPoolParametersProvider() public view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public; function getTokenDistributor() public view returns (address); function setTokenDistributor(address _tokenDistributor) public; function getFeeProvider() public view returns (address); function setFeeProviderImpl(address _feeProvider) public; function getLendingPoolLiquidationManager() public view returns (address); function setLendingPoolLiquidationManager(address _manager) public; function getLendingPoolManager() public view returns (address); function setLendingPoolManager(address _lendingPoolManager) public; function getPriceOracle() public view returns (address); function setPriceOracle(address _priceOracle) public; function getLendingRateOracle() public view returns (address); function setLendingRateOracle(address _lendingRateOracle) public; } /** * @title LendingPoolAddressesProvider contract * @notice Is the main registry of the protocol. All the different components of the protocol are accessible * through the addresses provider. * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider, AddressStorage { //events event LendingPoolUpdated(address indexed newAddress); event LendingPoolCoreUpdated(address indexed newAddress); event LendingPoolParametersProviderUpdated(address indexed newAddress); event LendingPoolManagerUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolLiquidationManagerUpdated(address indexed newAddress); event LendingPoolDataProviderUpdated(address indexed newAddress); event EthereumAddressUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event FeeProviderUpdated(address indexed newAddress); event TokenDistributorUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); bytes32 private constant LENDING_POOL = "LENDING_POOL"; bytes32 private constant LENDING_POOL_CORE = "LENDING_POOL_CORE"; bytes32 private constant LENDING_POOL_CONFIGURATOR = "LENDING_POOL_CONFIGURATOR"; bytes32 private constant LENDING_POOL_PARAMETERS_PROVIDER = "PARAMETERS_PROVIDER"; bytes32 private constant LENDING_POOL_MANAGER = "LENDING_POOL_MANAGER"; bytes32 private constant LENDING_POOL_LIQUIDATION_MANAGER = "LIQUIDATION_MANAGER"; bytes32 private constant LENDING_POOL_FLASHLOAN_PROVIDER = "FLASHLOAN_PROVIDER"; bytes32 private constant DATA_PROVIDER = "DATA_PROVIDER"; bytes32 private constant ETHEREUM_ADDRESS = "ETHEREUM_ADDRESS"; bytes32 private constant PRICE_ORACLE = "PRICE_ORACLE"; bytes32 private constant LENDING_RATE_ORACLE = "LENDING_RATE_ORACLE"; bytes32 private constant FEE_PROVIDER = "FEE_PROVIDER"; bytes32 private constant WALLET_BALANCE_PROVIDER = "WALLET_BALANCE_PROVIDER"; bytes32 private constant TOKEN_DISTRIBUTOR = "TOKEN_DISTRIBUTOR"; /** * @dev returns the address of the LendingPool proxy * @return the lending pool proxy address **/ function getLendingPool() public view returns (address) { return getAddress(LENDING_POOL); } /** * @dev updates the implementation of the lending pool * @param _pool the new lending pool implementation **/ function setLendingPoolImpl(address _pool) public onlyOwner { updateImplInternal(LENDING_POOL, _pool); emit LendingPoolUpdated(_pool); } /** * @dev returns the address of the LendingPoolCore proxy * @return the lending pool core proxy address */ function getLendingPoolCore() public view returns (address payable) { address payable core = address(uint160(getAddress(LENDING_POOL_CORE))); return core; } /** * @dev updates the implementation of the lending pool core * @param _lendingPoolCore the new lending pool core implementation **/ function setLendingPoolCoreImpl(address _lendingPoolCore) public onlyOwner { updateImplInternal(LENDING_POOL_CORE, _lendingPoolCore); emit LendingPoolCoreUpdated(_lendingPoolCore); } /** * @dev returns the address of the LendingPoolConfigurator proxy * @return the lending pool configurator proxy address **/ function getLendingPoolConfigurator() public view returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev updates the implementation of the lending pool configurator * @param _configurator the new lending pool configurator implementation **/ function setLendingPoolConfiguratorImpl(address _configurator) public onlyOwner { updateImplInternal(LENDING_POOL_CONFIGURATOR, _configurator); emit LendingPoolConfiguratorUpdated(_configurator); } /** * @dev returns the address of the LendingPoolDataProvider proxy * @return the lending pool data provider proxy address */ function getLendingPoolDataProvider() public view returns (address) { return getAddress(DATA_PROVIDER); } /** * @dev updates the implementation of the lending pool data provider * @param _provider the new lending pool data provider implementation **/ function setLendingPoolDataProviderImpl(address _provider) public onlyOwner { updateImplInternal(DATA_PROVIDER, _provider); emit LendingPoolDataProviderUpdated(_provider); } /** * @dev returns the address of the LendingPoolParametersProvider proxy * @return the address of the Lending pool parameters provider proxy **/ function getLendingPoolParametersProvider() public view returns (address) { return getAddress(LENDING_POOL_PARAMETERS_PROVIDER); } /** * @dev updates the implementation of the lending pool parameters provider * @param _parametersProvider the new lending pool parameters provider implementation **/ function setLendingPoolParametersProviderImpl(address _parametersProvider) public onlyOwner { updateImplInternal(LENDING_POOL_PARAMETERS_PROVIDER, _parametersProvider); emit LendingPoolParametersProviderUpdated(_parametersProvider); } /** * @dev returns the address of the FeeProvider proxy * @return the address of the Fee provider proxy **/ function getFeeProvider() public view returns (address) { return getAddress(FEE_PROVIDER); } /** * @dev updates the implementation of the FeeProvider proxy * @param _feeProvider the new lending pool fee provider implementation **/ function setFeeProviderImpl(address _feeProvider) public onlyOwner { updateImplInternal(FEE_PROVIDER, _feeProvider); emit FeeProviderUpdated(_feeProvider); } /** * @dev returns the address of the LendingPoolLiquidationManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly. * @return the address of the Lending pool liquidation manager **/ function getLendingPoolLiquidationManager() public view returns (address) { return getAddress(LENDING_POOL_LIQUIDATION_MANAGER); } /** * @dev updates the address of the Lending pool liquidation manager * @param _manager the new lending pool liquidation manager address **/ function setLendingPoolLiquidationManager(address _manager) public onlyOwner { _setAddress(LENDING_POOL_LIQUIDATION_MANAGER, _manager); emit LendingPoolLiquidationManagerUpdated(_manager); } /** * @dev the functions below are storing specific addresses that are outside the context of the protocol * hence the upgradable proxy pattern is not used **/ function getLendingPoolManager() public view returns (address) { return getAddress(LENDING_POOL_MANAGER); } function setLendingPoolManager(address _lendingPoolManager) public onlyOwner { _setAddress(LENDING_POOL_MANAGER, _lendingPoolManager); emit LendingPoolManagerUpdated(_lendingPoolManager); } function getPriceOracle() public view returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address _priceOracle) public onlyOwner { _setAddress(PRICE_ORACLE, _priceOracle); emit PriceOracleUpdated(_priceOracle); } function getLendingRateOracle() public view returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address _lendingRateOracle) public onlyOwner { _setAddress(LENDING_RATE_ORACLE, _lendingRateOracle); emit LendingRateOracleUpdated(_lendingRateOracle); } function getTokenDistributor() public view returns (address) { return getAddress(TOKEN_DISTRIBUTOR); } function setTokenDistributor(address _tokenDistributor) public onlyOwner { _setAddress(TOKEN_DISTRIBUTOR, _tokenDistributor); emit TokenDistributorUpdated(_tokenDistributor); } /** * @dev internal function to update the implementation of a specific component of the protocol * @param _id the id of the contract to be updated * @param _newAddress the address of the new implementation **/ function updateImplInternal(bytes32 _id, address _newAddress) internal { address payable proxyAddress = address(uint160(getAddress(_id))); InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature("initialize(address)", address(this)); if (proxyAddress == address(0)) { proxy = new InitializableAdminUpgradeabilityProxy(); proxy.initialize(_newAddress, address(this), params); _setAddress(_id, address(proxy)); emit ProxyCreated(_id, address(proxy)); } else { proxy.upgradeToAndCall(_newAddress, params); } } } contract UintStorage { mapping(bytes32 => uint256) private uints; function getUint(bytes32 _key) public view returns (uint256) { return uints[_key]; } function _setUint(bytes32 _key, uint256 _value) internal { uints[_key] = _value; } } /** * @title LendingPoolParametersProvider * @author Aave * @notice stores the configuration parameters of the Lending Pool contract **/ contract LendingPoolParametersProvider is VersionedInitializable { uint256 private constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; uint256 private constant REBALANCE_DOWN_RATE_DELTA = (1e27)/5; uint256 private constant FLASHLOAN_FEE_TOTAL = 35; uint256 private constant FLASHLOAN_FEE_PROTOCOL = 3000; uint256 constant private DATA_PROVIDER_REVISION = 0x1; function getRevision() internal pure returns(uint256) { return DATA_PROVIDER_REVISION; } /** * @dev initializes the LendingPoolParametersProvider after it's added to the proxy * @param _addressesProvider the address of the LendingPoolAddressesProvider */ function initialize(address _addressesProvider) public initializer { } /** * @dev returns the maximum stable rate borrow size, in percentage of the available liquidity. **/ function getMaxStableRateBorrowSizePercent() external pure returns (uint256) { return MAX_STABLE_RATE_BORROW_SIZE_PERCENT; } /** * @dev returns the delta between the current stable rate and the user stable rate at * which the borrow position of the user will be rebalanced (scaled down) **/ function getRebalanceDownRateDelta() external pure returns (uint256) { return REBALANCE_DOWN_RATE_DELTA; } /** * @dev returns the fee applied to a flashloan and the portion to redirect to the protocol, in basis points. **/ function getFlashLoanFeesInBips() external pure returns (uint256, uint256) { return (FLASHLOAN_FEE_TOTAL, FLASHLOAN_FEE_PROTOCOL); } } /** * @title CoreLibrary library * @author Aave * @notice Defines the data structures of the reserves and the user data **/ library CoreLibrary { using SafeMath for uint256; using WadRayMath for uint256; enum InterestRateMode {NONE, STABLE, VARIABLE} uint256 internal constant SECONDS_PER_YEAR = 365 days; struct UserReserveData { //principal amount borrowed by the user. uint256 principalBorrowBalance; //cumulated variable borrow index for the user. Expressed in ray uint256 lastVariableBorrowCumulativeIndex; //origination fee cumulated by the user uint256 originationFee; // stable borrow rate at which the user has borrowed. Expressed in ray uint256 stableBorrowRate; uint40 lastUpdateTimestamp; //defines if a specific deposit should or not be used as a collateral in borrows bool useAsCollateral; } struct ReserveData { /** * @dev refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. **/ //the liquidity index. Expressed in ray uint256 lastLiquidityCumulativeIndex; //the current supply rate. Expressed in ray uint256 currentLiquidityRate; //the total borrows of the reserve at a stable rate. Expressed in the currency decimals uint256 totalBorrowsStable; //the total borrows of the reserve at a variable rate. Expressed in the currency decimals uint256 totalBorrowsVariable; //the current variable borrow rate. Expressed in ray uint256 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint256 currentStableBorrowRate; //the current average stable borrow rate (weighted average of all the different stable rate loans). Expressed in ray uint256 currentAverageStableBorrowRate; //variable borrow index. Expressed in ray uint256 lastVariableBorrowCumulativeIndex; //the ltv of the reserve. Expressed in percentage (0-100) uint256 baseLTVasCollateral; //the liquidation threshold of the reserve. Expressed in percentage (0-100) uint256 liquidationThreshold; //the liquidation bonus of the reserve. Expressed in percentage uint256 liquidationBonus; //the decimals of the reserve asset uint256 decimals; /** * @dev address of the aToken representing the asset **/ address aTokenAddress; /** * @dev address of the interest rate strategy contract **/ address interestRateStrategyAddress; uint40 lastUpdateTimestamp; // borrowingEnabled = true means users can borrow from this reserve bool borrowingEnabled; // usageAsCollateralEnabled = true means users can use this reserve as collateral bool usageAsCollateralEnabled; // isStableBorrowRateEnabled = true means users can borrow at a stable rate bool isStableBorrowRateEnabled; // isActive = true means the reserve has been activated and properly configured bool isActive; // isFreezed = true means the reserve only allows repays and redeems, but not deposits, new borrowings or rate swap bool isFreezed; } /** * @dev returns the ongoing normalized income for the reserve. * a value of 1e27 means there is no income. As time passes, the income is accrued. * A value of 2*1e27 means that the income of the reserve is double the initial amount. * @param _reserve the reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(CoreLibrary.ReserveData storage _reserve) internal view returns (uint256) { uint256 cumulated = calculateLinearInterest( _reserve .currentLiquidityRate, _reserve .lastUpdateTimestamp ) .rayMul(_reserve.lastLiquidityCumulativeIndex); return cumulated; } /** * @dev Updates the liquidity cumulative index Ci and variable borrow cumulative index Bvc. Refer to the whitepaper for * a formal specification. * @param _self the reserve object **/ function updateCumulativeIndexes(ReserveData storage _self) internal { uint256 totalBorrows = getTotalBorrows(_self); if (totalBorrows > 0) { //only cumulating if there is any income being produced uint256 cumulatedLiquidityInterest = calculateLinearInterest( _self.currentLiquidityRate, _self.lastUpdateTimestamp ); _self.lastLiquidityCumulativeIndex = cumulatedLiquidityInterest.rayMul( _self.lastLiquidityCumulativeIndex ); uint256 cumulatedVariableBorrowInterest = calculateCompoundedInterest( _self.currentVariableBorrowRate, _self.lastUpdateTimestamp ); _self.lastVariableBorrowCumulativeIndex = cumulatedVariableBorrowInterest.rayMul( _self.lastVariableBorrowCumulativeIndex ); } } /** * @dev accumulates a predefined amount of asset to the reserve as a fixed, one time income. Used for example to accumulate * the flashloan fee to the reserve, and spread it through the depositors. * @param _self the reserve object * @param _totalLiquidity the total liquidity available in the reserve * @param _amount the amount to accomulate **/ function cumulateToLiquidityIndex( ReserveData storage _self, uint256 _totalLiquidity, uint256 _amount ) internal { uint256 amountToLiquidityRatio = _amount.wadToRay().rayDiv(_totalLiquidity.wadToRay()); uint256 cumulatedLiquidity = amountToLiquidityRatio.add(WadRayMath.ray()); _self.lastLiquidityCumulativeIndex = cumulatedLiquidity.rayMul( _self.lastLiquidityCumulativeIndex ); } /** * @dev initializes a reserve * @param _self the reserve object * @param _aTokenAddress the address of the overlying atoken contract * @param _decimals the number of decimals of the underlying asset * @param _interestRateStrategyAddress the address of the interest rate strategy contract **/ function init( ReserveData storage _self, address _aTokenAddress, uint256 _decimals, address _interestRateStrategyAddress ) external { require(_self.aTokenAddress == address(0), "Reserve has already been initialized"); if (_self.lastLiquidityCumulativeIndex == 0) { //if the reserve has not been initialized yet _self.lastLiquidityCumulativeIndex = WadRayMath.ray(); } if (_self.lastVariableBorrowCumulativeIndex == 0) { _self.lastVariableBorrowCumulativeIndex = WadRayMath.ray(); } _self.aTokenAddress = _aTokenAddress; _self.decimals = _decimals; _self.interestRateStrategyAddress = _interestRateStrategyAddress; _self.isActive = true; _self.isFreezed = false; } /** * @dev enables borrowing on a reserve * @param _self the reserve object * @param _stableBorrowRateEnabled true if the stable borrow rate must be enabled by default, false otherwise **/ function enableBorrowing(ReserveData storage _self, bool _stableBorrowRateEnabled) external { require(_self.borrowingEnabled == false, "Reserve is already enabled"); _self.borrowingEnabled = true; _self.isStableBorrowRateEnabled = _stableBorrowRateEnabled; } /** * @dev disables borrowing on a reserve * @param _self the reserve object **/ function disableBorrowing(ReserveData storage _self) external { _self.borrowingEnabled = false; } /** * @dev enables a reserve to be used as collateral * @param _self the reserve object * @param _baseLTVasCollateral the loan to value of the asset when used as collateral * @param _liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized * @param _liquidationBonus the bonus liquidators receive to liquidate this asset **/ function enableAsCollateral( ReserveData storage _self, uint256 _baseLTVasCollateral, uint256 _liquidationThreshold, uint256 _liquidationBonus ) external { require( _self.usageAsCollateralEnabled == false, "Reserve is already enabled as collateral" ); _self.usageAsCollateralEnabled = true; _self.baseLTVasCollateral = _baseLTVasCollateral; _self.liquidationThreshold = _liquidationThreshold; _self.liquidationBonus = _liquidationBonus; if (_self.lastLiquidityCumulativeIndex == 0) _self.lastLiquidityCumulativeIndex = WadRayMath.ray(); } /** * @dev disables a reserve as collateral * @param _self the reserve object **/ function disableAsCollateral(ReserveData storage _self) external { _self.usageAsCollateralEnabled = false; } /** * @dev calculates the compounded borrow balance of a user * @param _self the userReserve object * @param _reserve the reserve object * @return the user compounded borrow balance **/ function getCompoundedBorrowBalance( CoreLibrary.UserReserveData storage _self, CoreLibrary.ReserveData storage _reserve ) internal view returns (uint256) { if (_self.principalBorrowBalance == 0) return 0; uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToRay(); uint256 compoundedBalance = 0; uint256 cumulatedInterest = 0; if (_self.stableBorrowRate > 0) { cumulatedInterest = calculateCompoundedInterest( _self.stableBorrowRate, _self.lastUpdateTimestamp ); } else { //variable interest cumulatedInterest = calculateCompoundedInterest( _reserve .currentVariableBorrowRate, _reserve .lastUpdateTimestamp ) .rayMul(_reserve.lastVariableBorrowCumulativeIndex) .rayDiv(_self.lastVariableBorrowCumulativeIndex); } compoundedBalance = principalBorrowBalanceRay.rayMul(cumulatedInterest).rayToWad(); if (compoundedBalance == _self.principalBorrowBalance) { //solium-disable-next-line if (_self.lastUpdateTimestamp != block.timestamp) { //no interest cumulation because of the rounding - we add 1 wei //as symbolic cumulated interest to avoid interest free loans. return _self.principalBorrowBalance.add(1 wei); } } return compoundedBalance; } /** * @dev increases the total borrows at a stable rate on a specific reserve and updates the * average stable rate consequently * @param _reserve the reserve object * @param _amount the amount to add to the total borrows stable * @param _rate the rate at which the amount has been borrowed **/ function increaseTotalBorrowsStableAndUpdateAverageRate( ReserveData storage _reserve, uint256 _amount, uint256 _rate ) internal { if(_amount == 0) { return; } uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable; //updating reserve borrows stable _reserve.totalBorrowsStable = _reserve.totalBorrowsStable.add(_amount); //update the average stable rate //weighted average of all the borrows uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate); uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul( _reserve.currentAverageStableBorrowRate ); _reserve.currentAverageStableBorrowRate = weightedLastBorrow .add(weightedPreviousTotalBorrows) .rayDiv(_reserve.totalBorrowsStable.wadToRay()); } /** * @dev decreases the total borrows at a stable rate on a specific reserve and updates the * average stable rate consequently * @param _reserve the reserve object * @param _amount the amount to substract to the total borrows stable * @param _rate the rate at which the amount has been repaid **/ function decreaseTotalBorrowsStableAndUpdateAverageRate( ReserveData storage _reserve, uint256 _amount, uint256 _rate ) internal { uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable; if (previousTotalBorrowStable == 0 || _amount >= previousTotalBorrowStable) { _reserve.totalBorrowsStable = 0; _reserve.currentAverageStableBorrowRate = 0; // no income if there are no stable rate borrows return; } //updating reserve borrows stable _reserve.totalBorrowsStable = _reserve.totalBorrowsStable.sub(_amount); //update the average stable rate //weighted average of all the borrows uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate); uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul( _reserve.currentAverageStableBorrowRate ); if( weightedPreviousTotalBorrows <= weightedLastBorrow ) { _reserve.totalBorrowsStable = 0; _reserve.currentAverageStableBorrowRate = 0; // no income if there are no stable rate borrows return; } _reserve.currentAverageStableBorrowRate = weightedPreviousTotalBorrows .sub(weightedLastBorrow) .rayDiv(_reserve.totalBorrowsStable.wadToRay()); } /** * @dev increases the total borrows at a variable rate * @param _reserve the reserve object * @param _amount the amount to add to the total borrows variable **/ function increaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal { _reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.add(_amount); } /** * @dev decreases the total borrows at a variable rate * @param _reserve the reserve object * @param _amount the amount to substract to the total borrows variable **/ function decreaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal { require( _reserve.totalBorrowsVariable >= _amount, "The amount that is being subtracted from the variable total borrows is incorrect" ); _reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.sub(_amount); } /** * @dev function to calculate the interest using a linear interest rate formula * @param _rate the interest rate, in ray * @param _lastUpdateTimestamp the timestamp of the last update of the interest * @return the interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 _rate, uint40 _lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp)); uint256 timeDelta = timeDifference.wadToRay().rayDiv(SECONDS_PER_YEAR.wadToRay()); return _rate.rayMul(timeDelta).add(WadRayMath.ray()); } /** * @dev function to calculate the interest using a compounded interest rate formula * @param _rate the interest rate, in ray * @param _lastUpdateTimestamp the timestamp of the last update of the interest * @return the interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest(uint256 _rate, uint40 _lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp)); uint256 ratePerSecond = _rate.div(SECONDS_PER_YEAR); return ratePerSecond.add(WadRayMath.ray()).rayPow(timeDifference); } /** * @dev returns the total borrows on the reserve * @param _reserve the reserve object * @return the total borrows (stable + variable) **/ function getTotalBorrows(CoreLibrary.ReserveData storage _reserve) internal view returns (uint256) { return _reserve.totalBorrowsStable.add(_reserve.totalBorrowsVariable); } } /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param _asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address _asset) external view returns (uint256); } /** * @title IFeeProvider interface * @notice Interface for the Aave fee provider. **/ interface IFeeProvider { function calculateLoanOriginationFee(address _user, uint256 _amount) external view returns (uint256); function getLoanOriginationFeePercentage() external view returns (uint256); } /** * @title LendingPoolDataProvider contract * @author Aave * @notice Implements functions to fetch data from the core, and aggregate them in order to allow computation * on the compounded balances and the account balances in ETH **/ contract LendingPoolDataProvider is VersionedInitializable { using SafeMath for uint256; using WadRayMath for uint256; LendingPoolCore public core; LendingPoolAddressesProvider public addressesProvider; /** * @dev specifies the health factor threshold at which the user position is liquidated. * 1e18 by default, if the health factor drops below 1e18, the loan can be liquidated. **/ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; uint256 public constant DATA_PROVIDER_REVISION = 0x1; function getRevision() internal pure returns (uint256) { return DATA_PROVIDER_REVISION; } function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer { addressesProvider = _addressesProvider; core = LendingPoolCore(_addressesProvider.getLendingPoolCore()); } /** * @dev struct to hold calculateUserGlobalData() local computations **/ struct UserGlobalDataLocalVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 reserveDecimals; uint256 baseLtv; uint256 liquidationThreshold; uint256 originationFee; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; address currentReserve; } /** * @dev calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param _user the address of the user * @return the total liquidity, total collateral, total borrow balances of the user in ETH. * also the average Ltv, liquidation threshold, and the health factor **/ function calculateUserGlobalData(address _user) public view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ) { IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables UserGlobalDataLocalVars memory vars; address[] memory reserves = core.getReserves(); for (uint256 i = 0; i < reserves.length; i++) { vars.currentReserve = reserves[i]; ( vars.compoundedLiquidityBalance, vars.compoundedBorrowBalance, vars.originationFee, vars.userUsesReserveAsCollateral ) = core.getUserBasicReserveData(vars.currentReserve, _user); if (vars.compoundedLiquidityBalance == 0 && vars.compoundedBorrowBalance == 0) { continue; } //fetch reserve data ( vars.reserveDecimals, vars.baseLtv, vars.liquidationThreshold, vars.usageAsCollateralEnabled ) = core.getReserveConfiguration(vars.currentReserve); vars.tokenUnit = 10 ** vars.reserveDecimals; vars.reserveUnitPrice = oracle.getAssetPrice(vars.currentReserve); //liquidity and collateral balance if (vars.compoundedLiquidityBalance > 0) { uint256 liquidityBalanceETH = vars .reserveUnitPrice .mul(vars.compoundedLiquidityBalance) .div(vars.tokenUnit); totalLiquidityBalanceETH = totalLiquidityBalanceETH.add(liquidityBalanceETH); if (vars.usageAsCollateralEnabled && vars.userUsesReserveAsCollateral) { totalCollateralBalanceETH = totalCollateralBalanceETH.add(liquidityBalanceETH); currentLtv = currentLtv.add(liquidityBalanceETH.mul(vars.baseLtv)); currentLiquidationThreshold = currentLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } } if (vars.compoundedBorrowBalance > 0) { totalBorrowBalanceETH = totalBorrowBalanceETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); totalFeesETH = totalFeesETH.add( vars.originationFee.mul(vars.reserveUnitPrice).div(vars.tokenUnit) ); } } currentLtv = totalCollateralBalanceETH > 0 ? currentLtv.div(totalCollateralBalanceETH) : 0; currentLiquidationThreshold = totalCollateralBalanceETH > 0 ? currentLiquidationThreshold.div(totalCollateralBalanceETH) : 0; healthFactor = calculateHealthFactorFromBalancesInternal( totalCollateralBalanceETH, totalBorrowBalanceETH, totalFeesETH, currentLiquidationThreshold ); healthFactorBelowThreshold = healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 collateralBalanceETH; uint256 borrowBalanceETH; uint256 totalFeesETH; uint256 currentLiquidationThreshold; uint256 reserveLiquidationThreshold; uint256 amountToDecreaseETH; uint256 collateralBalancefterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev check if a specific balance decrease is allowed (i.e. doesn't bring the user borrow position health factor under 1e18) * @param _reserve the address of the reserve * @param _user the address of the user * @param _amount the amount to decrease * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed(address _reserve, address _user, uint256 _amount) external view returns (bool) { // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables balanceDecreaseAllowedLocalVars memory vars; ( vars.decimals, , vars.reserveLiquidationThreshold, vars.reserveUsageAsCollateralEnabled ) = core.getReserveConfiguration(_reserve); if ( !vars.reserveUsageAsCollateralEnabled || !core.isUserUseReserveAsCollateralEnabled(_reserve, _user) ) { return true; //if reserve is not used as collateral, no reasons to block the transfer } ( , vars.collateralBalanceETH, vars.borrowBalanceETH, vars.totalFeesETH, , vars.currentLiquidationThreshold, , ) = calculateUserGlobalData(_user); if (vars.borrowBalanceETH == 0) { return true; //no borrows - no reasons to block the transfer } IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); vars.amountToDecreaseETH = oracle.getAssetPrice(_reserve).mul(_amount).div( 10 ** vars.decimals ); vars.collateralBalancefterDecrease = vars.collateralBalanceETH.sub( vars.amountToDecreaseETH ); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalancefterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .collateralBalanceETH .mul(vars.currentLiquidationThreshold) .sub(vars.amountToDecreaseETH.mul(vars.reserveLiquidationThreshold)) .div(vars.collateralBalancefterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalancesInternal( vars.collateralBalancefterDecrease, vars.borrowBalanceETH, vars.totalFeesETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease > HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } /** * @notice calculates the amount of collateral needed in ETH to cover a new borrow. * @param _reserve the reserve from which the user wants to borrow * @param _amount the amount the user wants to borrow * @param _fee the fee for the amount that the user needs to cover * @param _userCurrentBorrowBalanceTH the current borrow balance of the user (before the borrow) * @param _userCurrentLtv the average ltv of the user given his current collateral * @return the total amount of collateral in ETH to cover the current borrow balance + the new amount + fee **/ function calculateCollateralNeededInETH( address _reserve, uint256 _amount, uint256 _fee, uint256 _userCurrentBorrowBalanceTH, uint256 _userCurrentFeesETH, uint256 _userCurrentLtv ) external view returns (uint256) { uint256 reserveDecimals = core.getReserveDecimals(_reserve); IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); uint256 requestedBorrowAmountETH = oracle .getAssetPrice(_reserve) .mul(_amount.add(_fee)) .div(10 ** reserveDecimals); //price is in ether //add the current already borrowed amount to the amount requested to calculate the total collateral needed. uint256 collateralNeededInETH = _userCurrentBorrowBalanceTH .add(_userCurrentFeesETH) .add(requestedBorrowAmountETH) .mul(100) .div(_userCurrentLtv); //LTV is calculated in percentage return collateralNeededInETH; } /** * @dev calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value. * @param collateralBalanceETH the total collateral balance * @param borrowBalanceETH the total borrow balance * @param totalFeesETH the total fees * @param ltv the average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETHInternal( uint256 collateralBalanceETH, uint256 borrowBalanceETH, uint256 totalFeesETH, uint256 ltv ) internal view returns (uint256) { uint256 availableBorrowsETH = collateralBalanceETH.mul(ltv).div(100); //ltv is in percentage if (availableBorrowsETH < borrowBalanceETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(borrowBalanceETH.add(totalFeesETH)); //calculate fee uint256 borrowFee = IFeeProvider(addressesProvider.getFeeProvider()) .calculateLoanOriginationFee(msg.sender, availableBorrowsETH); return availableBorrowsETH.sub(borrowFee); } /** * @dev calculates the health factor from the corresponding balances * @param collateralBalanceETH the total collateral balance in ETH * @param borrowBalanceETH the total borrow balance in ETH * @param totalFeesETH the total fees in ETH * @param liquidationThreshold the avg liquidation threshold **/ function calculateHealthFactorFromBalancesInternal( uint256 collateralBalanceETH, uint256 borrowBalanceETH, uint256 totalFeesETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (borrowBalanceETH == 0) return uint256(-1); return (collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv( borrowBalanceETH.add(totalFeesETH) ); } /** * @dev returns the health factor liquidation threshold **/ function getHealthFactorLiquidationThreshold() public pure returns (uint256) { return HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } /** * @dev accessory functions to fetch data from the lendingPoolCore **/ function getReserveConfigurationData(address _reserve) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ) { (, ltv, liquidationThreshold, usageAsCollateralEnabled) = core.getReserveConfiguration( _reserve ); stableBorrowRateEnabled = core.getReserveIsStableBorrowRateEnabled(_reserve); borrowingEnabled = core.isReserveBorrowingEnabled(_reserve); isActive = core.getReserveIsActive(_reserve); liquidationBonus = core.getReserveLiquidationBonus(_reserve); rateStrategyAddress = core.getReserveInterestRateStrategyAddress(_reserve); } function getReserveData(address _reserve) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsStable, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp ) { totalLiquidity = core.getReserveTotalLiquidity(_reserve); availableLiquidity = core.getReserveAvailableLiquidity(_reserve); totalBorrowsStable = core.getReserveTotalBorrowsStable(_reserve); totalBorrowsVariable = core.getReserveTotalBorrowsVariable(_reserve); liquidityRate = core.getReserveCurrentLiquidityRate(_reserve); variableBorrowRate = core.getReserveCurrentVariableBorrowRate(_reserve); stableBorrowRate = core.getReserveCurrentStableBorrowRate(_reserve); averageStableBorrowRate = core.getReserveCurrentAverageStableBorrowRate(_reserve); utilizationRate = core.getReserveUtilizationRate(_reserve); liquidityIndex = core.getReserveLiquidityCumulativeIndex(_reserve); variableBorrowIndex = core.getReserveVariableBorrowsCumulativeIndex(_reserve); aTokenAddress = core.getReserveATokenAddress(_reserve); lastUpdateTimestamp = core.getReserveLastUpdate(_reserve); } function getUserAccountData(address _user) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 totalFeesETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalLiquidityETH, totalCollateralETH, totalBorrowsETH, totalFeesETH, ltv, currentLiquidationThreshold, healthFactor, ) = calculateUserGlobalData(_user); availableBorrowsETH = calculateAvailableBorrowsETHInternal( totalCollateralETH, totalBorrowsETH, totalFeesETH, ltv ); } function getUserReserveData(address _reserve, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled ) { currentATokenBalance = AToken(core.getReserveATokenAddress(_reserve)).balanceOf(_user); CoreLibrary.InterestRateMode mode = core.getUserCurrentBorrowRateMode(_reserve, _user); (principalBorrowBalance, currentBorrowBalance, ) = core.getUserBorrowBalances( _reserve, _user ); //default is 0, if mode == CoreLibrary.InterestRateMode.NONE if (mode == CoreLibrary.InterestRateMode.STABLE) { borrowRate = core.getUserCurrentStableBorrowRate(_reserve, _user); } else if (mode == CoreLibrary.InterestRateMode.VARIABLE) { borrowRate = core.getReserveCurrentVariableBorrowRate(_reserve); } borrowRateMode = uint256(mode); liquidityRate = core.getReserveCurrentLiquidityRate(_reserve); originationFee = core.getUserOriginationFee(_reserve, _user); variableBorrowIndex = core.getUserVariableBorrowCumulativeIndex(_reserve, _user); lastUpdateTimestamp = core.getUserLastUpdate(_reserve, _user); usageAsCollateralEnabled = core.isUserUseReserveAsCollateralEnabled(_reserve, _user); } } /** * @title Aave ERC20 AToken * * @dev Implementation of the interest bearing token for the DLP protocol. * @author Aave */ contract AToken is ERC20, ERC20Detailed { using WadRayMath for uint256; uint256 public constant UINT_MAX_VALUE = uint256(-1); /** * @dev emitted after the redeem action * @param _from the address performing the redeem * @param _value the amount to be redeemed * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _fromIndex the last index of the user **/ event Redeem( address indexed _from, uint256 _value, uint256 _fromBalanceIncrease, uint256 _fromIndex ); /** * @dev emitted after the mint action * @param _from the address performing the mint * @param _value the amount to be minted * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _fromIndex the last index of the user **/ event MintOnDeposit( address indexed _from, uint256 _value, uint256 _fromBalanceIncrease, uint256 _fromIndex ); /** * @dev emitted during the liquidation action, when the liquidator reclaims the underlying * asset * @param _from the address from which the tokens are being burned * @param _value the amount to be burned * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _fromIndex the last index of the user **/ event BurnOnLiquidation( address indexed _from, uint256 _value, uint256 _fromBalanceIncrease, uint256 _fromIndex ); /** * @dev emitted during the transfer action * @param _from the address from which the tokens are being transferred * @param _to the adress of the destination * @param _value the amount to be minted * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _toBalanceIncrease the cumulated balance since the last update of the destination * @param _fromIndex the last index of the user * @param _toIndex the last index of the liquidator **/ event BalanceTransfer( address indexed _from, address indexed _to, uint256 _value, uint256 _fromBalanceIncrease, uint256 _toBalanceIncrease, uint256 _fromIndex, uint256 _toIndex ); /** * @dev emitted when the accumulation of the interest * by an user is redirected to another user * @param _from the address from which the interest is being redirected * @param _to the adress of the destination * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _fromIndex the last index of the user **/ event InterestStreamRedirected( address indexed _from, address indexed _to, uint256 _redirectedBalance, uint256 _fromBalanceIncrease, uint256 _fromIndex ); /** * @dev emitted when the redirected balance of an user is being updated * @param _targetAddress the address of which the balance is being updated * @param _targetBalanceIncrease the cumulated balance since the last update of the target * @param _targetIndex the last index of the user * @param _redirectedBalanceAdded the redirected balance being added * @param _redirectedBalanceRemoved the redirected balance being removed **/ event RedirectedBalanceUpdated( address indexed _targetAddress, uint256 _targetBalanceIncrease, uint256 _targetIndex, uint256 _redirectedBalanceAdded, uint256 _redirectedBalanceRemoved ); event InterestRedirectionAllowanceChanged( address indexed _from, address indexed _to ); address public underlyingAssetAddress; mapping (address => uint256) private userIndexes; mapping (address => address) private interestRedirectionAddresses; mapping (address => uint256) private redirectedBalances; mapping (address => address) private interestRedirectionAllowances; LendingPoolAddressesProvider private addressesProvider; LendingPoolCore private core; LendingPool private pool; LendingPoolDataProvider private dataProvider; modifier onlyLendingPool { require( msg.sender == address(pool), "The caller of this function must be a lending pool" ); _; } modifier whenTransferAllowed(address _from, uint256 _amount) { require(isTransferAllowed(_from, _amount), "Transfer cannot be allowed."); _; } constructor( LendingPoolAddressesProvider _addressesProvider, address _underlyingAsset, uint8 _underlyingAssetDecimals, string memory _name, string memory _symbol ) public ERC20Detailed(_name, _symbol, _underlyingAssetDecimals) { addressesProvider = _addressesProvider; core = LendingPoolCore(addressesProvider.getLendingPoolCore()); pool = LendingPool(addressesProvider.getLendingPool()); dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider()); underlyingAssetAddress = _underlyingAsset; } /** * @notice ERC20 implementation internal function backing transfer() and transferFrom() * @dev validates the transfer before allowing it. NOTE: This is not standard ERC20 behavior **/ function _transfer(address _from, address _to, uint256 _amount) internal whenTransferAllowed(_from, _amount) { executeTransferInternal(_from, _to, _amount); } /** * @dev redirects the interest generated to a target address. * when the interest is redirected, the user balance is added to * the recepient redirected balance. * @param _to the address to which the interest will be redirected **/ function redirectInterestStream(address _to) external { redirectInterestStreamInternal(msg.sender, _to); } /** * @dev redirects the interest generated by _from to a target address. * when the interest is redirected, the user balance is added to * the recepient redirected balance. The caller needs to have allowance on * the interest redirection to be able to execute the function. * @param _from the address of the user whom interest is being redirected * @param _to the address to which the interest will be redirected **/ function redirectInterestStreamOf(address _from, address _to) external { require( msg.sender == interestRedirectionAllowances[_from], "Caller is not allowed to redirect the interest of the user" ); redirectInterestStreamInternal(_from,_to); } /** * @dev gives allowance to an address to execute the interest redirection * on behalf of the caller. * @param _to the address to which the interest will be redirected. Pass address(0) to reset * the allowance. **/ function allowInterestRedirectionTo(address _to) external { require(_to != msg.sender, "User cannot give allowance to himself"); interestRedirectionAllowances[msg.sender] = _to; emit InterestRedirectionAllowanceChanged( msg.sender, _to ); } /** * @dev redeems aToken for the underlying asset * @param _amount the amount being redeemed **/ function redeem(uint256 _amount) external { require(_amount > 0, "Amount to redeem needs to be > 0"); //cumulates the balance of the user (, uint256 currentBalance, uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(msg.sender); uint256 amountToRedeem = _amount; //if amount is equal to uint(-1), the user wants to redeem everything if(_amount == UINT_MAX_VALUE){ amountToRedeem = currentBalance; } require(amountToRedeem <= currentBalance, "User cannot redeem more than the available balance"); //check that the user is allowed to redeem the amount require(isTransferAllowed(msg.sender, amountToRedeem), "Transfer cannot be allowed."); //if the user is redirecting his interest towards someone else, //we update the redirected balance of the redirection address by adding the accrued interest, //and removing the amount to redeem updateRedirectedBalanceOfRedirectionAddressInternal(msg.sender, balanceIncrease, amountToRedeem); // burns tokens equivalent to the amount requested _burn(msg.sender, amountToRedeem); bool userIndexReset = false; //reset the user data if the remaining balance is 0 if(currentBalance.sub(amountToRedeem) == 0){ userIndexReset = resetDataOnZeroBalanceInternal(msg.sender); } // executes redeem of the underlying asset pool.redeemUnderlying( underlyingAssetAddress, msg.sender, amountToRedeem, currentBalance.sub(amountToRedeem) ); emit Redeem(msg.sender, amountToRedeem, balanceIncrease, userIndexReset ? 0 : index); } /** * @dev mints token in the event of users depositing the underlying asset into the lending pool * only lending pools can call this function * @param _account the address receiving the minted tokens * @param _amount the amount of tokens to mint */ function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool { //cumulates the balance of the user (, , uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(_account); //if the user is redirecting his interest towards someone else, //we update the redirected balance of the redirection address by adding the accrued interest //and the amount deposited updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0); //mint an equivalent amount of tokens to cover the new deposit _mint(_account, _amount); emit MintOnDeposit(_account, _amount, balanceIncrease, index); } /** * @dev burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset * Transfer of the liquidated asset is executed by the lending pool contract. * only lending pools can call this function * @param _account the address from which burn the aTokens * @param _value the amount to burn **/ function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool { //cumulates the balance of the user being liquidated (,uint256 accountBalance,uint256 balanceIncrease,uint256 index) = cumulateBalanceInternal(_account); //adds the accrued interest and substracts the burned amount to //the redirected balance updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease, _value); //burns the requested amount of tokens _burn(_account, _value); bool userIndexReset = false; //reset the user data if the remaining balance is 0 if(accountBalance.sub(_value) == 0){ userIndexReset = resetDataOnZeroBalanceInternal(_account); } emit BurnOnLiquidation(_account, _value, balanceIncrease, userIndexReset ? 0 : index); } /** * @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * only lending pools can call this function * @param _from the address from which transfer the aTokens * @param _to the destination address * @param _value the amount to transfer **/ function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool { //being a normal transfer, the Transfer() and BalanceTransfer() are emitted //so no need to emit a specific event here executeTransferInternal(_from, _to, _value); } /** * @dev calculates the balance of the user, which is the * principal balance + interest generated by the principal balance + interest generated by the redirected balance * @param _user the user for which the balance is being calculated * @return the total balance of the user **/ function balanceOf(address _user) public view returns(uint256) { //current principal balance of the user uint256 currentPrincipalBalance = super.balanceOf(_user); //balance redirected by other users to _user for interest rate accrual uint256 redirectedBalance = redirectedBalances[_user]; if(currentPrincipalBalance == 0 && redirectedBalance == 0){ return 0; } //if the _user is not redirecting the interest to anybody, accrues //the interest for himself if(interestRedirectionAddresses[_user] == address(0)){ //accruing for himself means that both the principal balance and //the redirected balance partecipate in the interest return calculateCumulatedBalanceInternal( _user, currentPrincipalBalance.add(redirectedBalance) ) .sub(redirectedBalance); } else { //if the user redirected the interest, then only the redirected //balance generates interest. In that case, the interest generated //by the redirected balance is added to the current principal balance. return currentPrincipalBalance.add( calculateCumulatedBalanceInternal( _user, redirectedBalance ) .sub(redirectedBalance) ); } } /** * @dev returns the principal balance of the user. The principal balance is the last * updated stored balance, which does not consider the perpetually accruing interest. * @param _user the address of the user * @return the principal balance of the user **/ function principalBalanceOf(address _user) external view returns(uint256) { return super.balanceOf(_user); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view returns(uint256) { uint256 currentSupplyPrincipal = super.totalSupply(); if(currentSupplyPrincipal == 0){ return 0; } return currentSupplyPrincipal .wadToRay() .rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress)) .rayToWad(); } /** * @dev Used to validate transfers before actually executing them. * @param _user address of the user to check * @param _amount the amount to check * @return true if the _user can transfer _amount, false otherwise **/ function isTransferAllowed(address _user, uint256 _amount) public view returns (bool) { return dataProvider.balanceDecreaseAllowed(underlyingAssetAddress, _user, _amount); } /** * @dev returns the last index of the user, used to calculate the balance of the user * @param _user address of the user * @return the last user index **/ function getUserIndex(address _user) external view returns(uint256) { return userIndexes[_user]; } /** * @dev returns the address to which the interest is redirected * @param _user address of the user * @return 0 if there is no redirection, an address otherwise **/ function getInterestRedirectionAddress(address _user) external view returns(address) { return interestRedirectionAddresses[_user]; } /** * @dev returns the redirected balance of the user. The redirected balance is the balance * redirected by other accounts to the user, that is accrueing interest for him. * @param _user address of the user * @return the total redirected balance **/ function getRedirectedBalance(address _user) external view returns(uint256) { return redirectedBalances[_user]; } /** * @dev accumulates the accrued interest of the user to the principal balance * @param _user the address of the user for which the interest is being accumulated * @return the previous principal balance, the new principal balance, the balance increase * and the new user index **/ function cumulateBalanceInternal(address _user) internal returns(uint256, uint256, uint256, uint256) { uint256 previousPrincipalBalance = super.balanceOf(_user); //calculate the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance); //mints an amount of tokens equivalent to the amount accumulated _mint(_user, balanceIncrease); //updates the user index uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease, index ); } /** * @dev updates the redirected balance of the user. If the user is not redirecting his * interest, nothing is executed. * @param _user the address of the user for which the interest is being accumulated * @param _balanceToAdd the amount to add to the redirected balance * @param _balanceToRemove the amount to remove from the redirected balance **/ function updateRedirectedBalanceOfRedirectionAddressInternal( address _user, uint256 _balanceToAdd, uint256 _balanceToRemove ) internal { address redirectionAddress = interestRedirectionAddresses[_user]; //if there isn't any redirection, nothing to be done if(redirectionAddress == address(0)){ return; } //compound balances of the redirected address (,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress); //updating the redirected balance redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress] .add(_balanceToAdd) .sub(_balanceToRemove); //if the interest of redirectionAddress is also being redirected, we need to update //the redirected balance of the redirection target by adding the balance increase address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress]; if(targetOfRedirectionAddress != address(0)){ redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease); } emit RedirectedBalanceUpdated( redirectionAddress, balanceIncrease, index, _balanceToAdd, _balanceToRemove ); } /** * @dev calculate the interest accrued by _user on a specific balance * @param _user the address of the user for which the interest is being accumulated * @param _balance the balance on which the interest is calculated * @return the interest rate accrued **/ function calculateCumulatedBalanceInternal( address _user, uint256 _balance ) internal view returns (uint256) { return _balance .wadToRay() .rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress)) .rayDiv(userIndexes[_user]) .rayToWad(); } /** * @dev executes the transfer of aTokens, invoked by both _transfer() and * transferOnLiquidation() * @param _from the address from which transfer the aTokens * @param _to the destination address * @param _value the amount to transfer **/ function executeTransferInternal( address _from, address _to, uint256 _value ) internal { require(_value > 0, "Transferred amount needs to be greater than zero"); //cumulate the balance of the sender (, uint256 fromBalance, uint256 fromBalanceIncrease, uint256 fromIndex ) = cumulateBalanceInternal(_from); //cumulate the balance of the receiver (, , uint256 toBalanceIncrease, uint256 toIndex ) = cumulateBalanceInternal(_to); //if the sender is redirecting his interest towards someone else, //adds to the redirected balance the accrued interest and removes the amount //being transferred updateRedirectedBalanceOfRedirectionAddressInternal(_from, fromBalanceIncrease, _value); //if the receiver is redirecting his interest towards someone else, //adds to the redirected balance the accrued interest and the amount //being transferred updateRedirectedBalanceOfRedirectionAddressInternal(_to, toBalanceIncrease.add(_value), 0); //performs the transfer super._transfer(_from, _to, _value); bool fromIndexReset = false; //reset the user data if the remaining balance is 0 if(fromBalance.sub(_value) == 0){ fromIndexReset = resetDataOnZeroBalanceInternal(_from); } emit BalanceTransfer( _from, _to, _value, fromBalanceIncrease, toBalanceIncrease, fromIndexReset ? 0 : fromIndex, toIndex ); } /** * @dev executes the redirection of the interest from one address to another. * immediately after redirection, the destination address will start to accrue interest. * @param _from the address from which transfer the aTokens * @param _to the destination address **/ function redirectInterestStreamInternal( address _from, address _to ) internal { address currentRedirectionAddress = interestRedirectionAddresses[_from]; require(_to != currentRedirectionAddress, "Interest is already redirected to the user"); //accumulates the accrued interest to the principal (uint256 previousPrincipalBalance, uint256 fromBalance, uint256 balanceIncrease, uint256 fromIndex) = cumulateBalanceInternal(_from); require(fromBalance > 0, "Interest stream can only be redirected if there is a valid balance"); //if the user is already redirecting the interest to someone, before changing //the redirection address we substract the redirected balance of the previous //recipient if(currentRedirectionAddress != address(0)){ updateRedirectedBalanceOfRedirectionAddressInternal(_from,0, previousPrincipalBalance); } //if the user is redirecting the interest back to himself, //we simply set to 0 the interest redirection address if(_to == _from) { interestRedirectionAddresses[_from] = address(0); emit InterestStreamRedirected( _from, address(0), fromBalance, balanceIncrease, fromIndex ); return; } //first set the redirection address to the new recipient interestRedirectionAddresses[_from] = _to; //adds the user balance to the redirected balance of the destination updateRedirectedBalanceOfRedirectionAddressInternal(_from,fromBalance,0); emit InterestStreamRedirected( _from, _to, fromBalance, balanceIncrease, fromIndex ); } /** * @dev function to reset the interest stream redirection and the user index, if the * user has no balance left. * @param _user the address of the user * @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value **/ function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) { //if the user has 0 principal balance, the interest stream redirection gets reset interestRedirectionAddresses[_user] = address(0); //emits a InterestStreamRedirected event to notify that the redirection has been reset emit InterestStreamRedirected(_user, address(0),0,0,0); //if the redirected balance is also 0, we clear up the user index if(redirectedBalances[_user] == 0){ userIndexes[_user] = 0; return true; } else{ return false; } } } /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address _asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address _asset, uint256 _rate) external; } /** @title IReserveInterestRateStrategyInterface interface @notice Interface for the calculation of the interest rates. */ interface IReserveInterestRateStrategy { /** * @dev returns the base variable borrow rate, in rays */ function getBaseVariableBorrowRate() external view returns (uint256); /** * @dev calculates the liquidity, stable, and variable rates depending on the current utilization rate * and the base parameters * */ function calculateInterestRates( address _reserve, uint256 _utilizationRate, uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _averageStableBorrowRate) external view returns (uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate); } library EthAddressLib { /** * @dev returns the address used within the protocol to identify ETH * @return the address assigned to ETH */ function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } /** * @title LendingPool contract * @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data * @author Aave **/ contract LendingPool is ReentrancyGuard, VersionedInitializable { using SafeMath for uint256; using WadRayMath for uint256; using Address for address; LendingPoolAddressesProvider public addressesProvider; LendingPoolCore public core; LendingPoolDataProvider public dataProvider; LendingPoolParametersProvider public parametersProvider; IFeeProvider feeProvider; /** * @dev emitted on deposit * @param _reserve the address of the reserve * @param _user the address of the user * @param _amount the amount to be deposited * @param _referral the referral number of the action * @param _timestamp the timestamp of the action **/ event Deposit( address indexed _reserve, address indexed _user, uint256 _amount, uint16 indexed _referral, uint256 _timestamp ); /** * @dev emitted during a redeem action. * @param _reserve the address of the reserve * @param _user the address of the user * @param _amount the amount to be deposited * @param _timestamp the timestamp of the action **/ event RedeemUnderlying( address indexed _reserve, address indexed _user, uint256 _amount, uint256 _timestamp ); /** * @dev emitted on borrow * @param _reserve the address of the reserve * @param _user the address of the user * @param _amount the amount to be deposited * @param _borrowRateMode the rate mode, can be either 1-stable or 2-variable * @param _borrowRate the rate at which the user has borrowed * @param _originationFee the origination fee to be paid by the user * @param _borrowBalanceIncrease the balance increase since the last borrow, 0 if it's the first time borrowing * @param _referral the referral number of the action * @param _timestamp the timestamp of the action **/ event Borrow( address indexed _reserve, address indexed _user, uint256 _amount, uint256 _borrowRateMode, uint256 _borrowRate, uint256 _originationFee, uint256 _borrowBalanceIncrease, uint16 indexed _referral, uint256 _timestamp ); /** * @dev emitted on repay * @param _reserve the address of the reserve * @param _user the address of the user for which the repay has been executed * @param _repayer the address of the user that has performed the repay action * @param _amountMinusFees the amount repaid minus fees * @param _fees the fees repaid * @param _borrowBalanceIncrease the balance increase since the last action * @param _timestamp the timestamp of the action **/ event Repay( address indexed _reserve, address indexed _user, address indexed _repayer, uint256 _amountMinusFees, uint256 _fees, uint256 _borrowBalanceIncrease, uint256 _timestamp ); /** * @dev emitted when a user performs a rate swap * @param _reserve the address of the reserve * @param _user the address of the user executing the swap * @param _newRateMode the new interest rate mode * @param _newRate the new borrow rate * @param _borrowBalanceIncrease the balance increase since the last action * @param _timestamp the timestamp of the action **/ event Swap( address indexed _reserve, address indexed _user, uint256 _newRateMode, uint256 _newRate, uint256 _borrowBalanceIncrease, uint256 _timestamp ); /** * @dev emitted when a user enables a reserve as collateral * @param _reserve the address of the reserve * @param _user the address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed _reserve, address indexed _user); /** * @dev emitted when a user disables a reserve as collateral * @param _reserve the address of the reserve * @param _user the address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed _reserve, address indexed _user); /** * @dev emitted when the stable rate of a user gets rebalanced * @param _reserve the address of the reserve * @param _user the address of the user for which the rebalance has been executed * @param _newStableRate the new stable borrow rate after the rebalance * @param _borrowBalanceIncrease the balance increase since the last action * @param _timestamp the timestamp of the action **/ event RebalanceStableBorrowRate( address indexed _reserve, address indexed _user, uint256 _newStableRate, uint256 _borrowBalanceIncrease, uint256 _timestamp ); /** * @dev emitted when a flashloan is executed * @param _target the address of the flashLoanReceiver * @param _reserve the address of the reserve * @param _amount the amount requested * @param _totalFee the total fee on the amount * @param _protocolFee the part of the fee for the protocol * @param _timestamp the timestamp of the action **/ event FlashLoan( address indexed _target, address indexed _reserve, uint256 _amount, uint256 _totalFee, uint256 _protocolFee, uint256 _timestamp ); /** * @dev these events are not emitted directly by the LendingPool * but they are declared here as the LendingPoolLiquidationManager * is executed using a delegateCall(). * This allows to have the events in the generated ABI for LendingPool. **/ /** * @dev emitted when a borrow fee is liquidated * @param _collateral the address of the collateral being liquidated * @param _reserve the address of the reserve * @param _user the address of the user being liquidated * @param _feeLiquidated the total fee liquidated * @param _liquidatedCollateralForFee the amount of collateral received by the protocol in exchange for the fee * @param _timestamp the timestamp of the action **/ event OriginationFeeLiquidated( address indexed _collateral, address indexed _reserve, address indexed _user, uint256 _feeLiquidated, uint256 _liquidatedCollateralForFee, uint256 _timestamp ); /** * @dev emitted when a borrower is liquidated * @param _collateral the address of the collateral being liquidated * @param _reserve the address of the reserve * @param _user the address of the user being liquidated * @param _purchaseAmount the total amount liquidated * @param _liquidatedCollateralAmount the amount of collateral being liquidated * @param _accruedBorrowInterest the amount of interest accrued by the borrower since the last action * @param _liquidator the address of the liquidator * @param _receiveAToken true if the liquidator wants to receive aTokens, false otherwise * @param _timestamp the timestamp of the action **/ event LiquidationCall( address indexed _collateral, address indexed _reserve, address indexed _user, uint256 _purchaseAmount, uint256 _liquidatedCollateralAmount, uint256 _accruedBorrowInterest, address _liquidator, bool _receiveAToken, uint256 _timestamp ); /** * @dev functions affected by this modifier can only be invoked by the * aToken.sol contract * @param _reserve the address of the reserve **/ modifier onlyOverlyingAToken(address _reserve) { require( msg.sender == core.getReserveATokenAddress(_reserve), "The caller of this function can only be the aToken contract of this reserve" ); _; } /** * @dev functions affected by this modifier can only be invoked if the reserve is active * @param _reserve the address of the reserve **/ modifier onlyActiveReserve(address _reserve) { requireReserveActiveInternal(_reserve); _; } /** * @dev functions affected by this modifier can only be invoked if the reserve is not freezed. * A freezed reserve only allows redeems, repays, rebalances and liquidations. * @param _reserve the address of the reserve **/ modifier onlyUnfreezedReserve(address _reserve) { requireReserveNotFreezedInternal(_reserve); _; } /** * @dev functions affected by this modifier can only be invoked if the provided _amount input parameter * is not zero. * @param _amount the amount provided **/ modifier onlyAmountGreaterThanZero(uint256 _amount) { requireAmountGreaterThanZeroInternal(_amount); _; } uint256 public constant UINT_MAX_VALUE = uint256(-1); uint256 public constant LENDINGPOOL_REVISION = 0x3; function getRevision() internal pure returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev this function is invoked by the proxy contract when the LendingPool contract is added to the * AddressesProvider. * @param _addressesProvider the address of the LendingPoolAddressesProvider registry **/ function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer { addressesProvider = _addressesProvider; core = LendingPoolCore(addressesProvider.getLendingPoolCore()); dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider()); parametersProvider = LendingPoolParametersProvider( addressesProvider.getLendingPoolParametersProvider() ); feeProvider = IFeeProvider(addressesProvider.getFeeProvider()); } /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param _reserve the address of the reserve * @param _amount the amount to be deposited * @param _referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external payable nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) onlyAmountGreaterThanZero(_amount) { AToken aToken = AToken(core.getReserveATokenAddress(_reserve)); bool isFirstDeposit = aToken.balanceOf(msg.sender) == 0; core.updateStateOnDeposit(_reserve, msg.sender, _amount, isFirstDeposit); //minting AToken to user 1:1 with the specific exchange rate aToken.mintOnDeposit(msg.sender, _amount); //transfer to the core contract core.transferToReserve.value(msg.value)(_reserve, msg.sender, _amount); //solium-disable-next-line emit Deposit(_reserve, msg.sender, _amount, _referralCode, block.timestamp); } /** * @dev Redeems the underlying amount of assets requested by _user. * This function is executed by the overlying aToken contract in response to a redeem action. * @param _reserve the address of the reserve * @param _user the address of the user performing the action * @param _amount the underlying amount to be redeemed **/ function redeemUnderlying( address _reserve, address payable _user, uint256 _amount, uint256 _aTokenBalanceAfterRedeem ) external nonReentrant onlyOverlyingAToken(_reserve) onlyActiveReserve(_reserve) onlyAmountGreaterThanZero(_amount) { uint256 currentAvailableLiquidity = core.getReserveAvailableLiquidity(_reserve); require( currentAvailableLiquidity >= _amount, "There is not enough liquidity available to redeem" ); core.updateStateOnRedeem(_reserve, _user, _amount, _aTokenBalanceAfterRedeem == 0); core.transferToUser(_reserve, _user, _amount); //solium-disable-next-line emit RedeemUnderlying(_reserve, _user, _amount, block.timestamp); } /** * @dev data structures for local computations in the borrow() method. */ struct BorrowLocalVars { uint256 principalBorrowBalance; uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 borrowFee; uint256 requestedBorrowAmountETH; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 userTotalFeesETH; uint256 borrowBalanceIncrease; uint256 currentReserveStableRate; uint256 availableLiquidity; uint256 reserveDecimals; uint256 finalUserBorrowRate; CoreLibrary.InterestRateMode rateMode; bool healthFactorBelowThreshold; } /** * @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower * already deposited enough collateral. * @param _reserve the address of the reserve * @param _amount the amount to be borrowed * @param _interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE) **/ function borrow( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) onlyAmountGreaterThanZero(_amount) { // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables BorrowLocalVars memory vars; //check that the reserve is enabled for borrowing require(core.isReserveBorrowingEnabled(_reserve), "Reserve is not enabled for borrowing"); //validate interest rate mode require( uint256(CoreLibrary.InterestRateMode.VARIABLE) == _interestRateMode || uint256(CoreLibrary.InterestRateMode.STABLE) == _interestRateMode, "Invalid interest rate mode selected" ); //cast the rateMode to coreLibrary.interestRateMode vars.rateMode = CoreLibrary.InterestRateMode(_interestRateMode); //check that the amount is available in the reserve vars.availableLiquidity = core.getReserveAvailableLiquidity(_reserve); require( vars.availableLiquidity >= _amount, "There is not enough liquidity available in the reserve" ); ( , vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.userTotalFeesETH, vars.currentLtv, vars.currentLiquidationThreshold, , vars.healthFactorBelowThreshold ) = dataProvider.calculateUserGlobalData(msg.sender); require(vars.userCollateralBalanceETH > 0, "The collateral balance is 0"); require( !vars.healthFactorBelowThreshold, "The borrower can already be liquidated so he cannot borrow more" ); //calculating fees vars.borrowFee = feeProvider.calculateLoanOriginationFee(msg.sender, _amount); require(vars.borrowFee > 0, "The amount to borrow is too small"); vars.amountOfCollateralNeededETH = dataProvider.calculateCollateralNeededInETH( _reserve, _amount, vars.borrowFee, vars.userBorrowBalanceETH, vars.userTotalFeesETH, vars.currentLtv ); require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, "There is not enough collateral to cover a new borrow" ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a relatively small, configurable amount of the total * liquidity **/ if (vars.rateMode == CoreLibrary.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require( core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, _amount), "User cannot borrow the selected amount with a stable rate" ); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanPercent = parametersProvider.getMaxStableRateBorrowSizePercent(); uint256 maxLoanSizeStable = vars.availableLiquidity.mul(maxLoanPercent).div(100); require( _amount <= maxLoanSizeStable, "User is trying to borrow too much liquidity at a stable rate" ); } //all conditions passed - borrow is accepted (vars.finalUserBorrowRate, vars.borrowBalanceIncrease) = core.updateStateOnBorrow( _reserve, msg.sender, _amount, vars.borrowFee, vars.rateMode ); //if we reached this point, we can transfer core.transferToUser(_reserve, msg.sender, _amount); emit Borrow( _reserve, msg.sender, _amount, _interestRateMode, vars.finalUserBorrowRate, vars.borrowFee, vars.borrowBalanceIncrease, _referralCode, //solium-disable-next-line block.timestamp ); } /** * @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @dev the target user is defined by _onBehalfOf. If there is no repayment on behalf of another account, * _onBehalfOf must be equal to msg.sender. * @param _reserve the address of the reserve on which the user borrowed * @param _amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param _onBehalfOf the address for which msg.sender is repaying. **/ struct RepayLocalVars { uint256 principalBorrowBalance; uint256 compoundedBorrowBalance; uint256 borrowBalanceIncrease; bool isETH; uint256 paybackAmount; uint256 paybackAmountMinusFees; uint256 currentStableRate; uint256 originationFee; } function repay(address _reserve, uint256 _amount, address payable _onBehalfOf) external payable nonReentrant onlyActiveReserve(_reserve) onlyAmountGreaterThanZero(_amount) { // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables RepayLocalVars memory vars; ( vars.principalBorrowBalance, vars.compoundedBorrowBalance, vars.borrowBalanceIncrease ) = core.getUserBorrowBalances(_reserve, _onBehalfOf); vars.originationFee = core.getUserOriginationFee(_reserve, _onBehalfOf); vars.isETH = EthAddressLib.ethAddress() == _reserve; require(vars.compoundedBorrowBalance > 0, "The user does not have any borrow pending"); require( _amount != UINT_MAX_VALUE || msg.sender == _onBehalfOf, "To repay on behalf of an user an explicit amount to repay is needed." ); //default to max amount vars.paybackAmount = vars.compoundedBorrowBalance.add(vars.originationFee); if (_amount != UINT_MAX_VALUE && _amount < vars.paybackAmount) { vars.paybackAmount = _amount; } require( !vars.isETH || msg.value >= vars.paybackAmount, "Invalid msg.value sent for the repayment" ); //if the amount is smaller than the origination fee, just transfer the amount to the fee destination address if (vars.paybackAmount <= vars.originationFee) { core.updateStateOnRepay( _reserve, _onBehalfOf, 0, vars.paybackAmount, vars.borrowBalanceIncrease, false ); core.transferToFeeCollectionAddress.value(vars.isETH ? vars.paybackAmount : 0)( _reserve, _onBehalfOf, vars.paybackAmount, addressesProvider.getTokenDistributor() ); emit Repay( _reserve, _onBehalfOf, msg.sender, 0, vars.paybackAmount, vars.borrowBalanceIncrease, //solium-disable-next-line block.timestamp ); return; } vars.paybackAmountMinusFees = vars.paybackAmount.sub(vars.originationFee); core.updateStateOnRepay( _reserve, _onBehalfOf, vars.paybackAmountMinusFees, vars.originationFee, vars.borrowBalanceIncrease, vars.compoundedBorrowBalance == vars.paybackAmountMinusFees ); //if the user didn't repay the origination fee, transfer the fee to the fee collection address if(vars.originationFee > 0) { core.transferToFeeCollectionAddress.value(vars.isETH ? vars.originationFee : 0)( _reserve, _onBehalfOf, vars.originationFee, addressesProvider.getTokenDistributor() ); } //sending the total msg.value if the transfer is ETH. //the transferToReserve() function will take care of sending the //excess ETH back to the caller core.transferToReserve.value(vars.isETH ? msg.value.sub(vars.originationFee) : 0)( _reserve, msg.sender, vars.paybackAmountMinusFees ); emit Repay( _reserve, _onBehalfOf, msg.sender, vars.paybackAmountMinusFees, vars.originationFee, vars.borrowBalanceIncrease, //solium-disable-next-line block.timestamp ); } /** * @dev borrowers can user this function to swap between stable and variable borrow rate modes. * @param _reserve the address of the reserve on which the user borrowed **/ function swapBorrowRateMode(address _reserve) external nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) { (uint256 principalBorrowBalance, uint256 compoundedBorrowBalance, uint256 borrowBalanceIncrease) = core .getUserBorrowBalances(_reserve, msg.sender); require( compoundedBorrowBalance > 0, "User does not have a borrow in progress on this reserve" ); CoreLibrary.InterestRateMode currentRateMode = core.getUserCurrentBorrowRateMode( _reserve, msg.sender ); if (currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require( core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, compoundedBorrowBalance), "User cannot borrow the selected amount at stable" ); } (CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core .updateStateOnSwapRate( _reserve, msg.sender, principalBorrowBalance, compoundedBorrowBalance, borrowBalanceIncrease, currentRateMode ); emit Swap( _reserve, msg.sender, uint256(newRateMode), newBorrowRate, borrowBalanceIncrease, //solium-disable-next-line block.timestamp ); } /** * @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate. * this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair * rate. The rebalance mechanism is updated in the context of the V1 -> V2 transition to automatically switch the user to variable. * @param _reserve the address of the reserve * @param _user the address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address _reserve, address _user) external nonReentrant onlyActiveReserve(_reserve) { (uint256 principalBalance, uint256 compoundedBalance, uint256 borrowBalanceIncrease) = core.getUserBorrowBalances( _reserve, _user ); //step 1: user must be borrowing on _reserve at a stable rate require(compoundedBalance > 0, "User does not have any borrow for this reserve"); CoreLibrary.InterestRateMode rateMode = core.getUserCurrentBorrowRateMode(_reserve, _user); require( rateMode == CoreLibrary.InterestRateMode.STABLE, "The user borrow is variable and cannot be rebalanced" ); uint256 userCurrentStableRate = core.getUserCurrentStableBorrowRate(_reserve, _user); uint256 liquidityRate = core.getReserveCurrentLiquidityRate(_reserve); if (userCurrentStableRate < liquidityRate) { (CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core .updateStateOnSwapRate( _reserve, _user, principalBalance, compoundedBalance, borrowBalanceIncrease, rateMode ); emit Swap( _reserve, _user, uint256(newRateMode), newBorrowRate, borrowBalanceIncrease, //solium-disable-next-line block.timestamp ); } revert("Interest rate rebalance conditions were not met"); } /** * @dev allows depositors to enable or disable a specific deposit as collateral. * @param _reserve the address of the reserve * @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. **/ function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) { uint256 underlyingBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender); require(underlyingBalance > 0, "User does not have any liquidity deposited"); require( dataProvider.balanceDecreaseAllowed(_reserve, msg.sender, underlyingBalance), "User deposit is already being used as collateral" ); core.setUserUseReserveAsCollateral(_reserve, msg.sender, _useAsCollateral); if (_useAsCollateral) { emit ReserveUsedAsCollateralEnabled(_reserve, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender); } } /** * @dev users can invoke this function to liquidate an undercollateralized position. * @param _reserve the address of the collateral to liquidated * @param _reserve the address of the principal reserve * @param _user the address of the borrower * @param _purchaseAmount the amount of principal that the liquidator wants to repay * @param _receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken ) external payable nonReentrant onlyActiveReserve(_reserve) onlyActiveReserve(_collateral) { address liquidationManager = addressesProvider.getLendingPoolLiquidationManager(); //solium-disable-next-line (bool success, bytes memory result) = liquidationManager.delegatecall( abi.encodeWithSignature( "liquidationCall(address,address,address,uint256,bool)", _collateral, _reserve, _user, _purchaseAmount, _receiveAToken ) ); require(success, "Liquidation call failed"); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); if (returnCode != 0) { //error found revert(string(abi.encodePacked("Liquidation failed: ", returnMessage))); } } /** * @dev allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts * that must be kept into consideration. For further details please visit https://developers.aave.com * @param _receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. * @param _reserve the address of the principal reserve * @param _amount the amount requested for this flashloan **/ function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes memory _params) public nonReentrant onlyActiveReserve(_reserve) onlyAmountGreaterThanZero(_amount) { //check that the reserve has enough available liquidity //we avoid using the getAvailableLiquidity() function in LendingPoolCore to save gas uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress() ? address(core).balance : IERC20(_reserve).balanceOf(address(core)); require( availableLiquidityBefore >= _amount, "There is not enough liquidity available to borrow" ); (uint256 totalFeeBips, uint256 protocolFeeBips) = parametersProvider .getFlashLoanFeesInBips(); //calculate amount fee uint256 amountFee = _amount.mul(totalFeeBips).div(10000); //protocol fee is the part of the amountFee reserved for the protocol - the rest goes to depositors uint256 protocolFee = amountFee.mul(protocolFeeBips).div(10000); require( amountFee > 0 && protocolFee > 0, "The requested amount is too small for a flashLoan." ); //get the FlashLoanReceiver instance IFlashLoanReceiver receiver = IFlashLoanReceiver(_receiver); address payable userPayable = address(uint160(_receiver)); //transfer funds to the receiver core.transferToUser(_reserve, userPayable, _amount); //execute action of the receiver receiver.executeOperation(_reserve, _amount, amountFee, _params); //check that the actual balance of the core contract includes the returned amount uint256 availableLiquidityAfter = _reserve == EthAddressLib.ethAddress() ? address(core).balance : IERC20(_reserve).balanceOf(address(core)); require( availableLiquidityAfter == availableLiquidityBefore.add(amountFee), "The actual balance of the protocol is inconsistent" ); core.updateStateOnFlashLoan( _reserve, availableLiquidityBefore, amountFee.sub(protocolFee), protocolFee ); //solium-disable-next-line emit FlashLoan(_receiver, _reserve, _amount, amountFee, protocolFee, block.timestamp); } /** * @dev accessory functions to fetch data from the core contract **/ function getReserveConfigurationData(address _reserve) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ) { return dataProvider.getReserveConfigurationData(_reserve); } function getReserveData(address _reserve) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsStable, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp ) { return dataProvider.getReserveData(_reserve); } function getUserAccountData(address _user) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 totalFeesETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { return dataProvider.getUserAccountData(_user); } function getUserReserveData(address _reserve, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled ) { return dataProvider.getUserReserveData(_reserve, _user); } function getReserves() external view returns (address[] memory) { return core.getReserves(); } /** * @dev internal function to save on code size for the onlyActiveReserve modifier **/ function requireReserveActiveInternal(address _reserve) internal view { require(core.getReserveIsActive(_reserve), "Action requires an active reserve"); } /** * @notice internal function to save on code size for the onlyUnfreezedReserve modifier **/ function requireReserveNotFreezedInternal(address _reserve) internal view { require(!core.getReserveIsFreezed(_reserve), "Action requires an unfreezed reserve"); } /** * @notice internal function to save on code size for the onlyAmountGreaterThanZero modifier **/ function requireAmountGreaterThanZeroInternal(uint256 _amount) internal pure { require(_amount > 0, "Amount must be greater than 0"); } } /** * @title LendingPoolCore contract * @author Aave * @notice Holds the state of the lending pool and all the funds deposited * @dev NOTE: The core does not enforce security checks on the update of the state * (eg, updateStateOnBorrow() does not enforce that borrowed is enabled on the reserve). * The check that an action can be performed is a duty of the overlying LendingPool contract. **/ contract LendingPoolCore is VersionedInitializable { using SafeMath for uint256; using WadRayMath for uint256; using CoreLibrary for CoreLibrary.ReserveData; using CoreLibrary for CoreLibrary.UserReserveData; using SafeERC20 for ERC20; using Address for address payable; /** * @dev Emitted when the state of a reserve is updated * @param reserve the address of the reserve * @param liquidityRate the new liquidity rate * @param stableBorrowRate the new stable borrow rate * @param variableBorrowRate the new variable borrow rate * @param liquidityIndex the new liquidity index * @param variableBorrowIndex the new variable borrow index **/ event ReserveUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); address public lendingPoolAddress; LendingPoolAddressesProvider public addressesProvider; /** * @dev only lending pools can use functions affected by this modifier **/ modifier onlyLendingPool { require(lendingPoolAddress == msg.sender, "The caller must be a lending pool contract"); _; } /** * @dev only lending pools configurator can use functions affected by this modifier **/ modifier onlyLendingPoolConfigurator { require( addressesProvider.getLendingPoolConfigurator() == msg.sender, "The caller must be a lending pool configurator contract" ); _; } mapping(address => CoreLibrary.ReserveData) internal reserves; mapping(address => mapping(address => CoreLibrary.UserReserveData)) internal usersReserveData; address[] public reservesList; uint256 public constant CORE_REVISION = 0x7; /** * @dev returns the revision number of the contract **/ function getRevision() internal pure returns (uint256) { return CORE_REVISION; } /** * @dev initializes the Core contract, invoked upon registration on the AddressesProvider * @param _addressesProvider the addressesProvider contract **/ function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer { addressesProvider = _addressesProvider; refreshConfigInternal(); } /** * @dev updates the state of the core as a result of a deposit action * @param _reserve the address of the reserve in which the deposit is happening * @param _user the address of the the user depositing * @param _amount the amount being deposited * @param _isFirstDeposit true if the user is depositing for the first time **/ function updateStateOnDeposit( address _reserve, address _user, uint256 _amount, bool _isFirstDeposit ) external onlyLendingPool { reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0); if (_isFirstDeposit) { //if this is the first deposit of the user, we configure the deposit as enabled to be used as collateral setUserUseReserveAsCollateral(_reserve, _user, true); } } /** * @dev updates the state of the core as a result of a redeem action * @param _reserve the address of the reserve in which the redeem is happening * @param _user the address of the the user redeeming * @param _amountRedeemed the amount being redeemed * @param _userRedeemedEverything true if the user is redeeming everything **/ function updateStateOnRedeem( address _reserve, address _user, uint256 _amountRedeemed, bool _userRedeemedEverything ) external onlyLendingPool { //compound liquidity and variable borrow interests reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed); //if user redeemed everything the useReserveAsCollateral flag is reset if (_userRedeemedEverything) { setUserUseReserveAsCollateral(_reserve, _user, false); } } /** * @dev updates the state of the core as a result of a flashloan action * @param _reserve the address of the reserve in which the flashloan is happening * @param _income the income of the protocol as a result of the action **/ function updateStateOnFlashLoan( address _reserve, uint256 _availableLiquidityBefore, uint256 _income, uint256 _protocolFee ) external onlyLendingPool { transferFlashLoanProtocolFeeInternal(_reserve, _protocolFee); //compounding the cumulated interest reserves[_reserve].updateCumulativeIndexes(); uint256 totalLiquidityBefore = _availableLiquidityBefore.add( getReserveTotalBorrows(_reserve) ); //compounding the received fee into the reserve reserves[_reserve].cumulateToLiquidityIndex(totalLiquidityBefore, _income); //refresh interest rates updateReserveInterestRatesAndTimestampInternal(_reserve, _income, 0); } /** * @dev updates the state of the core as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _amountBorrowed the new amount borrowed * @param _borrowFee the fee on the amount borrowed * @param _rateMode the borrow rate mode (stable, variable) * @return the new borrow rate for the user **/ function updateStateOnBorrow( address _reserve, address _user, uint256 _amountBorrowed, uint256 _borrowFee, CoreLibrary.InterestRateMode _rateMode ) external onlyLendingPool returns (uint256, uint256) { // getting the previous borrow data of the user (uint256 principalBorrowBalance, , uint256 balanceIncrease) = getUserBorrowBalances( _reserve, _user ); updateReserveStateOnBorrowInternal( _reserve, _user, principalBorrowBalance, balanceIncrease, _amountBorrowed, _rateMode ); updateUserStateOnBorrowInternal( _reserve, _user, _amountBorrowed, balanceIncrease, _borrowFee, _rateMode ); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed); return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease); } /** * @dev updates the state of the core as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _originationFeeRepaid the fee on the amount that is being repaid * @param _balanceIncrease the accrued interest on the borrowed amount * @param _repaidWholeLoan true if the user is repaying the whole loan **/ function updateStateOnRepay( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) external onlyLendingPool { updateReserveStateOnRepayInternal( _reserve, _user, _paybackAmountMinusFees, _balanceIncrease ); updateUserStateOnRepayInternal( _reserve, _user, _paybackAmountMinusFees, _originationFeeRepaid, _balanceIncrease, _repaidWholeLoan ); updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0); } /** * @dev updates the state of the core as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _principalBorrowBalance the amount borrowed by the user * @param _compoundedBorrowBalance the amount borrowed plus accrued interest * @param _balanceIncrease the accrued interest on the borrowed amount * @param _currentRateMode the current interest rate mode for the user **/ function updateStateOnSwapRate( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) { updateReserveStateOnSwapRateInternal( _reserve, _user, _principalBorrowBalance, _compoundedBorrowBalance, _currentRateMode ); CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal( _reserve, _user, _balanceIncrease, _currentRateMode ); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0); return (newRateMode, getUserCurrentBorrowRate(_reserve, _user)); } /** * @dev updates the state of the core as a consequence of a liquidation action. * @param _principalReserve the address of the principal reserve that is being repaid * @param _collateralReserve the address of the collateral reserve that is being liquidated * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _collateralToLiquidate the amount of collateral being liquidated * @param _feeLiquidated the amount of origination fee being liquidated * @param _liquidatedCollateralForFee the amount of collateral equivalent to the origination fee + bonus * @param _balanceIncrease the accrued interest on the borrowed amount * @param _liquidatorReceivesAToken true if the liquidator will receive aTokens, false otherwise **/ function updateStateOnLiquidation( address _principalReserve, address _collateralReserve, address _user, uint256 _amountToLiquidate, uint256 _collateralToLiquidate, uint256 _feeLiquidated, uint256 _liquidatedCollateralForFee, uint256 _balanceIncrease, bool _liquidatorReceivesAToken ) external onlyLendingPool { updatePrincipalReserveStateOnLiquidationInternal( _principalReserve, _user, _amountToLiquidate, _balanceIncrease ); updateCollateralReserveStateOnLiquidationInternal( _collateralReserve ); updateUserStateOnLiquidationInternal( _principalReserve, _user, _amountToLiquidate, _feeLiquidated, _balanceIncrease ); updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0); if (!_liquidatorReceivesAToken) { updateReserveInterestRatesAndTimestampInternal( _collateralReserve, 0, _collateralToLiquidate.add(_liquidatedCollateralForFee) ); } } /** * @dev updates the state of the core as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @return the new stable rate for the user **/ function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease) external onlyLendingPool returns (uint256) { updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); //update user data and rebalance the rate updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0); return usersReserveData[_user][_reserve].stableBorrowRate; } /** * @dev enables or disables a reserve as collateral * @param _reserve the address of the principal reserve where the user deposited * @param _user the address of the depositor * @param _useAsCollateral true if the depositor wants to use the reserve as collateral **/ function setUserUseReserveAsCollateral(address _reserve, address _user, bool _useAsCollateral) public onlyLendingPool { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; user.useAsCollateral = _useAsCollateral; } /** * @notice ETH/token transfer functions **/ /** * @dev fallback function enforces that the caller is a contract, to support flashloan transfers **/ function() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), "Only contracts can send ether to the Lending pool core"); } /** * @dev transfers to the user a specific amount from the reserve. * @param _reserve the address of the reserve where the transfer is happening * @param _user the address of the user receiving the transfer * @param _amount the amount being transferred **/ function transferToUser(address _reserve, address payable _user, uint256 _amount) external onlyLendingPool { if (_reserve != EthAddressLib.ethAddress()) { ERC20(_reserve).safeTransfer(_user, _amount); } else { //solium-disable-next-line (bool result, ) = _user.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers the protocol fees to the fees collection address * @param _token the address of the token being transferred * @param _user the address of the user from where the transfer is happening * @param _amount the amount being transferred * @param _destination the fee receiver address **/ function transferToFeeCollectionAddress( address _token, address _user, uint256 _amount, address _destination ) external payable onlyLendingPool { address payable feeAddress = address(uint160(_destination)); //cast the address to payable if (_token != EthAddressLib.ethAddress()) { require( msg.value == 0, "User is sending ETH along with the ERC20 transfer. Check the value attribute of the transaction" ); ERC20(_token).safeTransferFrom(_user, feeAddress, _amount); } else { require(msg.value >= _amount, "The amount and the value sent to deposit do not match"); //solium-disable-next-line (bool result, ) = feeAddress.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers the fees to the fees collection address in the case of liquidation * @param _token the address of the token being transferred * @param _amount the amount being transferred * @param _destination the fee receiver address **/ function liquidateFee( address _token, uint256 _amount, address _destination ) external payable onlyLendingPool { address payable feeAddress = address(uint160(_destination)); //cast the address to payable require( msg.value == 0, "Fee liquidation does not require any transfer of value" ); if (_token != EthAddressLib.ethAddress()) { ERC20(_token).safeTransfer(feeAddress, _amount); } else { //solium-disable-next-line (bool result, ) = feeAddress.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers an amount from a user to the destination reserve * @param _reserve the address of the reserve where the amount is being transferred * @param _user the address of the user from where the transfer is happening * @param _amount the amount being transferred **/ function transferToReserve(address _reserve, address payable _user, uint256 _amount) external payable onlyLendingPool { if (_reserve != EthAddressLib.ethAddress()) { require(msg.value == 0, "User is sending ETH along with the ERC20 transfer."); ERC20(_reserve).safeTransferFrom(_user, address(this), _amount); } else { require(msg.value >= _amount, "The amount and the value sent to deposit do not match"); if (msg.value > _amount) { //send back excess ETH uint256 excessAmount = msg.value.sub(_amount); //solium-disable-next-line (bool result, ) = _user.call.value(excessAmount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } } /** * @notice data access functions **/ /** * @dev returns the basic data (balances, fee accrued, reserve enabled/disabled as collateral) * needed to calculate the global account data in the LendingPoolDataProvider * @param _reserve the address of the reserve * @param _user the address of the user * @return the user deposited balance, the principal borrow balance, the fee, and if the reserve is enabled as collateral or not **/ function getUserBasicReserveData(address _reserve, address _user) external view returns (uint256, uint256, uint256, bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user); if (user.principalBorrowBalance == 0) { return (underlyingBalance, 0, 0, user.useAsCollateral); } return ( underlyingBalance, user.getCompoundedBorrowBalance(reserve), user.originationFee, user.useAsCollateral ); } /** * @dev checks if a user is allowed to borrow at a stable rate * @param _reserve the reserve address * @param _user the user * @param _amount the amount the the user wants to borrow * @return true if the user is allowed to borrow at a stable rate, false otherwise **/ function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (!reserve.isStableBorrowRateEnabled) return false; return !user.useAsCollateral || !reserve.usageAsCollateralEnabled || _amount > getUserUnderlyingAssetBalance(_reserve, _user); } /** * @dev gets the underlying asset balance of a user based on the corresponding aToken balance. * @param _reserve the reserve address * @param _user the user address * @return the underlying deposit balance of the user **/ function getUserUnderlyingAssetBalance(address _reserve, address _user) public view returns (uint256) { AToken aToken = AToken(reserves[_reserve].aTokenAddress); return aToken.balanceOf(_user); } /** * @dev gets the interest rate strategy contract address for the reserve * @param _reserve the reserve address * @return the address of the interest rate strategy contract **/ function getReserveInterestRateStrategyAddress(address _reserve) public view returns (address) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.interestRateStrategyAddress; } /** * @dev gets the aToken contract address for the reserve * @param _reserve the reserve address * @return the address of the aToken contract **/ function getReserveATokenAddress(address _reserve) public view returns (address) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.aTokenAddress; } /** * @dev gets the available liquidity in the reserve. The available liquidity is the balance of the core contract * @param _reserve the reserve address * @return the available liquidity **/ function getReserveAvailableLiquidity(address _reserve) public view returns (uint256) { uint256 balance = 0; if (_reserve == EthAddressLib.ethAddress()) { balance = address(this).balance; } else { balance = IERC20(_reserve).balanceOf(address(this)); } return balance; } /** * @dev gets the total liquidity in the reserve. The total liquidity is the balance of the core contract + total borrows * @param _reserve the reserve address * @return the total liquidity **/ function getReserveTotalLiquidity(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return getReserveAvailableLiquidity(_reserve).add(reserve.getTotalBorrows()); } /** * @dev gets the normalized income of the reserve. a value of 1e27 means there is no income. A value of 2e27 means there * there has been 100% income. * @param _reserve the reserve address * @return the reserve normalized income **/ function getReserveNormalizedIncome(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.getNormalizedIncome(); } /** * @dev gets the reserve total borrows * @param _reserve the reserve address * @return the total borrows (stable + variable) **/ function getReserveTotalBorrows(address _reserve) public view returns (uint256) { return reserves[_reserve].getTotalBorrows(); } /** * @dev gets the reserve total borrows stable * @param _reserve the reserve address * @return the total borrows stable **/ function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.totalBorrowsStable; } /** * @dev gets the reserve total borrows variable * @param _reserve the reserve address * @return the total borrows variable **/ function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.totalBorrowsVariable; } /** * @dev gets the reserve liquidation threshold * @param _reserve the reserve address * @return the reserve liquidation threshold **/ function getReserveLiquidationThreshold(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.liquidationThreshold; } /** * @dev gets the reserve liquidation bonus * @param _reserve the reserve address * @return the reserve liquidation bonus **/ function getReserveLiquidationBonus(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.liquidationBonus; } /** * @dev gets the reserve current variable borrow rate. Is the base variable borrow rate if the reserve is empty * @param _reserve the reserve address * @return the reserve current variable borrow rate **/ function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; if (reserve.currentVariableBorrowRate == 0) { return IReserveInterestRateStrategy(reserve.interestRateStrategyAddress) .getBaseVariableBorrowRate(); } return reserve.currentVariableBorrowRate; } /** * @dev gets the reserve current stable borrow rate. Is the market rate if the reserve is empty * @param _reserve the reserve address * @return the reserve current stable borrow rate **/ function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle()); if (reserve.currentStableBorrowRate == 0) { //no stable rate borrows yet return oracle.getMarketBorrowRate(_reserve); } return reserve.currentStableBorrowRate; } /** * @dev gets the reserve average stable borrow rate. The average stable rate is the weighted average * of all the loans taken at stable rate. * @param _reserve the reserve address * @return the reserve current average borrow rate **/ function getReserveCurrentAverageStableBorrowRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.currentAverageStableBorrowRate; } /** * @dev gets the reserve liquidity rate * @param _reserve the reserve address * @return the reserve liquidity rate **/ function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.currentLiquidityRate; } /** * @dev gets the reserve liquidity cumulative index * @param _reserve the reserve address * @return the reserve liquidity cumulative index **/ function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.lastLiquidityCumulativeIndex; } /** * @dev gets the reserve variable borrow index * @param _reserve the reserve address * @return the reserve variable borrow index **/ function getReserveVariableBorrowsCumulativeIndex(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.lastVariableBorrowCumulativeIndex; } /** * @dev this function aggregates the configuration parameters of the reserve. * It's used in the LendingPoolDataProvider specifically to save gas, and avoid * multiple external contract calls to fetch the same data. * @param _reserve the reserve address * @return the reserve decimals * @return the base ltv as collateral * @return the liquidation threshold * @return if the reserve is used as collateral or not **/ function getReserveConfiguration(address _reserve) external view returns (uint256, uint256, uint256, bool) { uint256 decimals; uint256 baseLTVasCollateral; uint256 liquidationThreshold; bool usageAsCollateralEnabled; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; decimals = reserve.decimals; baseLTVasCollateral = reserve.baseLTVasCollateral; liquidationThreshold = reserve.liquidationThreshold; usageAsCollateralEnabled = reserve.usageAsCollateralEnabled; return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled); } /** * @dev returns the decimals of the reserve * @param _reserve the reserve address * @return the reserve decimals **/ function getReserveDecimals(address _reserve) external view returns (uint256) { return reserves[_reserve].decimals; } /** * @dev returns true if the reserve is enabled for borrowing * @param _reserve the reserve address * @return true if the reserve is enabled for borrowing, false otherwise **/ function isReserveBorrowingEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.borrowingEnabled; } /** * @dev returns true if the reserve is enabled as collateral * @param _reserve the reserve address * @return true if the reserve is enabled as collateral, false otherwise **/ function isReserveUsageAsCollateralEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.usageAsCollateralEnabled; } /** * @dev returns true if the stable rate is enabled on reserve * @param _reserve the reserve address * @return true if the stable rate is enabled on reserve, false otherwise **/ function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isStableBorrowRateEnabled; } /** * @dev returns true if the reserve is active * @param _reserve the reserve address * @return true if the reserve is active, false otherwise **/ function getReserveIsActive(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isActive; } /** * @notice returns if a reserve is freezed * @param _reserve the reserve for which the information is needed * @return true if the reserve is freezed, false otherwise **/ function getReserveIsFreezed(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isFreezed; } /** * @notice returns the timestamp of the last action on the reserve * @param _reserve the reserve for which the information is needed * @return the last updated timestamp of the reserve **/ function getReserveLastUpdate(address _reserve) external view returns (uint40 timestamp) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; timestamp = reserve.lastUpdateTimestamp; } /** * @dev returns the utilization rate U of a specific reserve * @param _reserve the reserve for which the information is needed * @return the utilization rate in ray **/ function getReserveUtilizationRate(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; uint256 totalBorrows = reserve.getTotalBorrows(); if (totalBorrows == 0) { return 0; } uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve); return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows)); } /** * @return the array of reserves configured on the core **/ function getReserves() external view returns (address[] memory) { return reservesList; } /** * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return true if the user has chosen to use the reserve as collateral, false otherwise **/ function isUserUseReserveAsCollateralEnabled(address _reserve, address _user) external view returns (bool) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.useAsCollateral; } /** * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the origination fee for the user **/ function getUserOriginationFee(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.originationFee; } /** * @dev users with no loans in progress have NONE as borrow rate mode * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the borrow rate mode for the user, **/ function getUserCurrentBorrowRateMode(address _reserve, address _user) public view returns (CoreLibrary.InterestRateMode) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return CoreLibrary.InterestRateMode.NONE; } return user.stableBorrowRate > 0 ? CoreLibrary.InterestRateMode.STABLE : CoreLibrary.InterestRateMode.VARIABLE; } /** * @dev gets the current borrow rate of the user * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the borrow rate for the user, **/ function getUserCurrentBorrowRate(address _reserve, address _user) internal view returns (uint256) { CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user); if (rateMode == CoreLibrary.InterestRateMode.NONE) { return 0; } return rateMode == CoreLibrary.InterestRateMode.STABLE ? usersReserveData[_user][_reserve].stableBorrowRate : reserves[_reserve].currentVariableBorrowRate; } /** * @dev the stable rate returned is 0 if the user is borrowing at variable or not borrowing at all * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the user stable rate **/ function getUserCurrentStableBorrowRate(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.stableBorrowRate; } /** * @dev calculates and returns the borrow balances of the user * @param _reserve the address of the reserve * @param _user the address of the user * @return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance **/ function getUserBorrowBalances(address _reserve, address _user) public view returns (uint256, uint256, uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return (0, 0, 0); } uint256 principal = user.principalBorrowBalance; uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance( user, reserves[_reserve] ); return (principal, compoundedBalance, compoundedBalance.sub(principal)); } /** * @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the variable borrow index for the user **/ function getUserVariableBorrowCumulativeIndex(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.lastVariableBorrowCumulativeIndex; } /** * @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the variable borrow index for the user **/ function getUserLastUpdate(address _reserve, address _user) external view returns (uint256 timestamp) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; timestamp = user.lastUpdateTimestamp; } /** * @dev updates the lending pool core configuration **/ function refreshConfiguration() external onlyLendingPoolConfigurator { refreshConfigInternal(); } /** * @dev initializes a reserve * @param _reserve the address of the reserve * @param _aTokenAddress the address of the overlying aToken contract * @param _decimals the decimals of the reserve currency * @param _interestRateStrategyAddress the address of the interest rate strategy contract **/ function initReserve( address _reserve, address _aTokenAddress, uint256 _decimals, address _interestRateStrategyAddress ) external onlyLendingPoolConfigurator { reserves[_reserve].init(_aTokenAddress, _decimals, _interestRateStrategyAddress); addReserveToListInternal(_reserve); } /** * @dev removes the last added reserve in the reservesList array * @param _reserveToRemove the address of the reserve **/ function removeLastAddedReserve(address _reserveToRemove) external onlyLendingPoolConfigurator { address lastReserve = reservesList[reservesList.length-1]; require(lastReserve == _reserveToRemove, "Reserve being removed is different than the reserve requested"); //as we can't check if totalLiquidity is 0 (since the reserve added might not be an ERC20) we at least check that there is nothing borrowed require(getReserveTotalBorrows(lastReserve) == 0, "Cannot remove a reserve with liquidity deposited"); reserves[lastReserve].isActive = false; reserves[lastReserve].aTokenAddress = address(0); reserves[lastReserve].decimals = 0; reserves[lastReserve].lastLiquidityCumulativeIndex = 0; reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0; reserves[lastReserve].borrowingEnabled = false; reserves[lastReserve].usageAsCollateralEnabled = false; reserves[lastReserve].baseLTVasCollateral = 0; reserves[lastReserve].liquidationThreshold = 0; reserves[lastReserve].liquidationBonus = 0; reserves[lastReserve].interestRateStrategyAddress = address(0); reservesList.pop(); } /** * @dev updates the address of the interest rate strategy contract * @param _reserve the address of the reserve * @param _rateStrategyAddress the address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address _reserve, address _rateStrategyAddress) external onlyLendingPoolConfigurator { reserves[_reserve].interestRateStrategyAddress = _rateStrategyAddress; } /** * @dev enables borrowing on a reserve. Also sets the stable rate borrowing * @param _reserve the address of the reserve * @param _stableBorrowRateEnabled true if the stable rate needs to be enabled, false otherwise **/ function enableBorrowingOnReserve(address _reserve, bool _stableBorrowRateEnabled) external onlyLendingPoolConfigurator { reserves[_reserve].enableBorrowing(_stableBorrowRateEnabled); } /** * @dev disables borrowing on a reserve * @param _reserve the address of the reserve **/ function disableBorrowingOnReserve(address _reserve) external onlyLendingPoolConfigurator { reserves[_reserve].disableBorrowing(); } /** * @dev enables a reserve to be used as collateral * @param _reserve the address of the reserve **/ function enableReserveAsCollateral( address _reserve, uint256 _baseLTVasCollateral, uint256 _liquidationThreshold, uint256 _liquidationBonus ) external onlyLendingPoolConfigurator { reserves[_reserve].enableAsCollateral( _baseLTVasCollateral, _liquidationThreshold, _liquidationBonus ); } /** * @dev disables a reserve to be used as collateral * @param _reserve the address of the reserve **/ function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator { reserves[_reserve].disableAsCollateral(); } /** * @dev enable the stable borrow rate mode on a reserve * @param _reserve the address of the reserve **/ function enableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = true; } /** * @dev disable the stable borrow rate mode on a reserve * @param _reserve the address of the reserve **/ function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = false; } /** * @dev activates a reserve * @param _reserve the address of the reserve **/ function activateReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; require( reserve.lastLiquidityCumulativeIndex > 0 && reserve.lastVariableBorrowCumulativeIndex > 0, "Reserve has not been initialized yet" ); reserve.isActive = true; } /** * @dev deactivates a reserve * @param _reserve the address of the reserve **/ function deactivateReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isActive = false; } /** * @notice allows the configurator to freeze the reserve. * A freezed reserve does not allow any action apart from repay, redeem, liquidationCall, rebalance. * @param _reserve the address of the reserve **/ function freezeReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isFreezed = true; } /** * @notice allows the configurator to unfreeze the reserve. A unfreezed reserve allows any action to be executed. * @param _reserve the address of the reserve **/ function unfreezeReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isFreezed = false; } /** * @notice allows the configurator to update the loan to value of a reserve * @param _reserve the address of the reserve * @param _ltv the new loan to value **/ function setReserveBaseLTVasCollateral(address _reserve, uint256 _ltv) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.baseLTVasCollateral = _ltv; } /** * @notice allows the configurator to update the liquidation threshold of a reserve * @param _reserve the address of the reserve * @param _threshold the new liquidation threshold **/ function setReserveLiquidationThreshold(address _reserve, uint256 _threshold) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.liquidationThreshold = _threshold; } /** * @notice allows the configurator to update the liquidation bonus of a reserve * @param _reserve the address of the reserve * @param _bonus the new liquidation bonus **/ function setReserveLiquidationBonus(address _reserve, uint256 _bonus) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.liquidationBonus = _bonus; } /** * @notice allows the configurator to update the reserve decimals * @param _reserve the address of the reserve * @param _decimals the decimals of the reserve **/ function setReserveDecimals(address _reserve, uint256 _decimals) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.decimals = _decimals; } /** * @notice internal functions **/ /** * @dev updates the state of a reserve as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _principalBorrowBalance the previous borrow balance of the borrower before the action * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount * @param _amountBorrowed the new amount borrowed * @param _rateMode the borrow rate mode (stable, variable) **/ function updateReserveStateOnBorrowInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _rateMode ) internal { reserves[_reserve].updateCumulativeIndexes(); //increasing reserve total borrows to account for the new borrow balance of the user //NOTE: Depending on the previous borrow mode, the borrows might need to be switched from variable to stable or vice versa updateReserveTotalBorrowsByRateModeInternal( _reserve, _user, _principalBorrowBalance, _balanceIncrease, _amountBorrowed, _rateMode ); } /** * @dev updates the state of a user as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _amountBorrowed the amount borrowed * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount * @param _rateMode the borrow rate mode (stable, variable) * @return the final borrow rate for the user. Emitted by the borrow() event **/ function updateUserStateOnBorrowInternal( address _reserve, address _user, uint256 _amountBorrowed, uint256 _balanceIncrease, uint256 _fee, CoreLibrary.InterestRateMode _rateMode ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (_rateMode == CoreLibrary.InterestRateMode.STABLE) { //stable //reset the user variable index, and update the stable rate user.stableBorrowRate = reserve.currentStableBorrowRate; user.lastVariableBorrowCumulativeIndex = 0; } else if (_rateMode == CoreLibrary.InterestRateMode.VARIABLE) { //variable //reset the user stable rate, and store the new borrow index user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } else { revert("Invalid borrow rate mode"); } //increase the principal borrows and the origination fee user.principalBorrowBalance = user.principalBorrowBalance.add(_amountBorrowed).add( _balanceIncrease ); user.originationFee = user.originationFee.add(_fee); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the reserve as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateReserveStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user); //update the indexes reserves[_reserve].updateCumulativeIndexes(); //compound the cumulated interest to the borrow balance and then subtracting the payback amount if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _paybackAmountMinusFees, user.stableBorrowRate ); } else { reserve.increaseTotalBorrowsVariable(_balanceIncrease); reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees); } } /** * @dev updates the state of the user as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _originationFeeRepaid the fee on the amount that is being repaid * @param _balanceIncrease the accrued interest on the borrowed amount * @param _repaidWholeLoan true if the user is repaying the whole loan **/ function updateUserStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; //update the user principal borrow balance, adding the cumulated interest and then subtracting the payback amount user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub( _paybackAmountMinusFees ); user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; //if the balance decrease is equal to the previous principal (user is repaying the whole loan) //and the rate mode is stable, we reset the interest rate mode of the user if (_repaidWholeLoan) { user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = 0; } user.originationFee = user.originationFee.sub(_originationFeeRepaid); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the user as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is performing the rate swap * @param _user the address of the borrower * @param _principalBorrowBalance the the principal amount borrowed by the user * @param _compoundedBorrowBalance the principal amount plus the accrued interest * @param _currentRateMode the rate mode at which the user borrowed **/ function updateReserveStateOnSwapRateInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, CoreLibrary.InterestRateMode _currentRateMode ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; //compounding reserve indexes reserve.updateCumulativeIndexes(); if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) { uint256 userCurrentStableRate = user.stableBorrowRate; //swap to variable reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _principalBorrowBalance, userCurrentStableRate ); //decreasing stable from old principal balance reserve.increaseTotalBorrowsVariable(_compoundedBorrowBalance); //increase variable borrows } else if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { //swap to stable uint256 currentStableRate = reserve.currentStableBorrowRate; reserve.decreaseTotalBorrowsVariable(_principalBorrowBalance); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _compoundedBorrowBalance, currentStableRate ); } else { revert("Invalid rate mode received"); } } /** * @dev updates the state of the user as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is performing the swap * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @param _currentRateMode the current rate mode of the user **/ function updateUserStateOnSwapRateInternal( address _reserve, address _user, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) internal returns (CoreLibrary.InterestRateMode) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE; if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { //switch to stable newMode = CoreLibrary.InterestRateMode.STABLE; user.stableBorrowRate = reserve.currentStableBorrowRate; user.lastVariableBorrowCumulativeIndex = 0; } else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) { newMode = CoreLibrary.InterestRateMode.VARIABLE; user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } else { revert("Invalid interest rate mode received"); } //compounding cumulated interest user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); return newMode; } /** * @dev updates the state of the principal reserve as a consequence of a liquidation action. * @param _principalReserve the address of the principal reserve that is being repaid * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updatePrincipalReserveStateOnLiquidationInternal( address _principalReserve, address _user, uint256 _amountToLiquidate, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_principalReserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve]; //update principal reserve data reserve.updateCumulativeIndexes(); CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode( _principalReserve, _user ); if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { //increase the total borrows by the compounded interest reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); //decrease by the actual amount to liquidate reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _amountToLiquidate, user.stableBorrowRate ); } else { //increase the total borrows by the compounded interest reserve.increaseTotalBorrowsVariable(_balanceIncrease); //decrease by the actual amount to liquidate reserve.decreaseTotalBorrowsVariable(_amountToLiquidate); } } /** * @dev updates the state of the collateral reserve as a consequence of a liquidation action. * @param _collateralReserve the address of the collateral reserve that is being liquidated **/ function updateCollateralReserveStateOnLiquidationInternal( address _collateralReserve ) internal { //update collateral reserve reserves[_collateralReserve].updateCumulativeIndexes(); } /** * @dev updates the state of the user being liquidated as a consequence of a liquidation action. * @param _reserve the address of the principal reserve that is being repaid * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _feeLiquidated the amount of origination fee being liquidated * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateUserStateOnLiquidationInternal( address _reserve, address _user, uint256 _amountToLiquidate, uint256 _feeLiquidated, uint256 _balanceIncrease ) internal { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; //first increase by the compounded interest, then decrease by the liquidated amount user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub( _amountToLiquidate ); if ( getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.VARIABLE ) { user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } if(_feeLiquidated > 0){ user.originationFee = user.originationFee.sub(_feeLiquidated); } //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the reserve as a consequence of a stable rate rebalance * DEPRECATED FOR THE V1 -> V2 migration * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateReserveStateOnRebalanceInternal( address _reserve, address _user, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.updateCumulativeIndexes(); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); } /** * @dev updates the state of the user as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateUserStateOnRebalanceInternal( address _reserve, address _user, uint256 _balanceIncrease ) internal { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease); user.stableBorrowRate = reserve.currentStableBorrowRate; //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the user as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @param _amountBorrowed the accrued interest on the borrowed amount **/ function updateReserveTotalBorrowsByRateModeInternal( address _reserve, address _user, uint256 _principalBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _newBorrowRateMode ) internal { CoreLibrary.InterestRateMode previousRateMode = getUserCurrentBorrowRateMode( _reserve, _user ); CoreLibrary.ReserveData storage reserve = reserves[_reserve]; if (previousRateMode == CoreLibrary.InterestRateMode.STABLE) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _principalBalance, user.stableBorrowRate ); } else if (previousRateMode == CoreLibrary.InterestRateMode.VARIABLE) { reserve.decreaseTotalBorrowsVariable(_principalBalance); } uint256 newPrincipalAmount = _principalBalance.add(_balanceIncrease).add(_amountBorrowed); if (_newBorrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( newPrincipalAmount, reserve.currentStableBorrowRate ); } else if (_newBorrowRateMode == CoreLibrary.InterestRateMode.VARIABLE) { reserve.increaseTotalBorrowsVariable(newPrincipalAmount); } else { revert("Invalid new borrow rate mode"); } } /** * @dev Updates the reserve current stable borrow rate Rf, the current variable borrow rate Rv and the current liquidity rate Rl. * Also updates the lastUpdateTimestamp value. Please refer to the whitepaper for further information. * @param _reserve the address of the reserve to be updated * @param _liquidityAdded the amount of liquidity added to the protocol (deposit or repay) in the previous action * @param _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow) **/ function updateReserveInterestRatesAndTimestampInternal( address _reserve, uint256 _liquidityAdded, uint256 _liquidityTaken ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; (uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate) = IReserveInterestRateStrategy( reserve .interestRateStrategyAddress ) .calculateInterestRates( _reserve, getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken), reserve.totalBorrowsStable, reserve.totalBorrowsVariable, reserve.currentAverageStableBorrowRate ); reserve.currentLiquidityRate = newLiquidityRate; reserve.currentStableBorrowRate = newStableRate; reserve.currentVariableBorrowRate = newVariableRate; //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); emit ReserveUpdated( _reserve, newLiquidityRate, newStableRate, newVariableRate, reserve.lastLiquidityCumulativeIndex, reserve.lastVariableBorrowCumulativeIndex ); } /** * @dev transfers to the protocol fees of a flashloan to the fees collection address * @param _token the address of the token being transferred * @param _amount the amount being transferred **/ function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal { address payable receiver = address(uint160(addressesProvider.getTokenDistributor())); if (_token != EthAddressLib.ethAddress()) { ERC20(_token).safeTransfer(receiver, _amount); } else { //solium-disable-next-line (bool result, ) = receiver.call.value(_amount)(""); require(result, "Transfer to token distributor failed"); } } /** * @dev updates the internal configuration of the core **/ function refreshConfigInternal() internal { lendingPoolAddress = addressesProvider.getLendingPool(); } /** * @dev adds a reserve to the array of the reserves address **/ function addReserveToListInternal(address _reserve) internal { bool reserveAlreadyAdded = false; for (uint256 i = 0; i < reservesList.length; i++) if (reservesList[i] == _reserve) { reserveAlreadyAdded = true; } if (!reserveAlreadyAdded) reservesList.push(_reserve); } }
updates the implementation of the lending pool configurator _configurator the new lending pool configurator implementation/
function setLendingPoolConfiguratorImpl(address _configurator) public onlyOwner { updateImplInternal(LENDING_POOL_CONFIGURATOR, _configurator); emit LendingPoolConfiguratorUpdated(_configurator); }
2,063,733
./full_match/1/0x4A7AAce1B48905560Fd8d33D536461bE6fF00F6d/sources/contracts/XRP2_Staking.sol
Staking function Transfer tokens from user to contract Assuming the token contract is already deployed and the transferFrom function is implemented in the token contract You may need to adjust the function signature and parameters based on your specific token contract
function stake(uint256 _amount) external { require(_amount > 0, "Insufficient token balance"); require(block.timestamp < endTime, "Staking duration is ended"); xrp2.safeTransferFrom(address(msg.sender), address(this), _amount); stakers[msg.sender] = Staker((stakers[msg.sender].amount.add(_amount)), block.timestamp); totalStakedAmount = totalStakedAmount.add(_amount); }
16,468,920
./full_match/1/0x146657fd93AA4869934383c9c899891078E6b94C/sources/src/FeeBonding.sol
Getter for fee bond details. tokenId The tokenId to fetch info for. return bondDetails The bond details./
function feeBonds(uint256 tokenId) public view returns (FeeBond memory) { return _bonds[tokenId]; }
2,983,300
./partial_match/1/0x4B2c41dD64c43EdaCf741EE0b9B549e3E00B3D3a/sources/StarNFTV3.sol
Get Star NFT CID/
function cid(uint256 tokenId) public view returns (uint256) { return _cids[tokenId]; }
9,397,562
pragma solidity 0.4.25; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address 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. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ 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/MultiOwnable.sol /** * @title MultiOwnable.sol * @dev Provide multi-ownable functionality to a smart contract. * @dev Note this contract preserves the idea of a master owner where this owner * cannot be removed or deleted. Master owner's are the only owner's who can add * and remove other owner's. Transfer of master ownership is supported and can * also only be transferred by the current master owner * @dev When master ownership is transferred the original master owner is not * removed from the additional owners list */ pragma solidity 0.4.25; /** * @dev OpenZeppelin Solidity v2.0.0 imports (Using: npm [email protected]) */ contract MultiOwnable is Ownable { /** * @dev Mapping of additional addresses that are considered owners */ mapping (address => bool) additionalOwners; /** * @dev Modifier that overrides 'Ownable' to support multiple owners */ modifier onlyOwner() { // Ensure that msg.sender is an owner or revert require(isOwner(msg.sender), "Permission denied [owner]."); _; } /** * @dev Modifier that provides additional testing to ensure msg.sender * is master owner, or first address to deploy contract */ modifier onlyMaster() { // Ensure that msg.sender is the master user require(super.isOwner(), "Permission denied [master]."); _; } /** * @dev Ownership added event for Dapps interested in this event */ event OwnershipAdded ( address indexed addedOwner ); /** * @dev Ownership removed event for Dapps interested in this event */ event OwnershipRemoved ( address indexed removedOwner ); /** * @dev MultiOwnable .cTor responsible for initialising the masterOwner * or contract super-user * @dev The super user cannot be deleted from the ownership mapping and * can only be transferred */ constructor() Ownable() public { // Obtain owner of the contract (msg.sender) address masterOwner = owner(); // Add the master owner to the additional owners list additionalOwners[masterOwner] = true; } /** * @dev Returns the owner status of the specified address */ function isOwner(address _ownerAddressToLookup) public view returns (bool) { // Return the ownership state of the specified owner address return additionalOwners[_ownerAddressToLookup]; } /** * @dev Returns the master status of the specfied address */ function isMaster(address _masterAddressToLookup) public view returns (bool) { return (super.owner() == _masterAddressToLookup); } /** * @dev Add a new owner address to additional owners mapping * @dev Only the master owner can add additional owner addresses */ function addOwner(address _ownerToAdd) onlyMaster public returns (bool) { // Ensure the new owner address is not address(0) require(_ownerToAdd != address(0), "Invalid address specified (0x0)"); // Ensure that new owner address is not already in the owners list require(!isOwner(_ownerToAdd), "Address specified already in owners list."); // Add new owner to additional owners mapping additionalOwners[_ownerToAdd] = true; emit OwnershipAdded(_ownerToAdd); return true; } /** * @dev Add a new owner address to additional owners mapping * @dev Only the master owner can add additional owner addresses */ function removeOwner(address _ownerToRemove) onlyMaster public returns (bool) { // Ensure that the address to remove is not the master owner require(_ownerToRemove != super.owner(), "Permission denied [master]."); // Ensure that owner address to remove is actually an owner require(isOwner(_ownerToRemove), "Address specified not found in owners list."); // Add remove ownership from address in the additional owners mapping additionalOwners[_ownerToRemove] = false; emit OwnershipRemoved(_ownerToRemove); return true; } /** * @dev Transfer ownership of this contract to another address * @dev Only the master owner can transfer ownership to another address * @dev Only existing owners can have ownership transferred to them */ function transferOwnership(address _newOwnership) onlyMaster public { // Ensure the new ownership is not address(0) require(_newOwnership != address(0), "Invalid address specified (0x0)"); // Ensure the new ownership address is not the current ownership addressess require(_newOwnership != owner(), "Address specified must not match current owner address."); // Ensure that the new ownership is promoted from existing owners require(isOwner(_newOwnership), "Master ownership can only be transferred to an existing owner address."); // Call into the parent class and transfer ownership super.transferOwnership(_newOwnership); // If we get here, then add the new ownership address to the additional owners mapping // Note that the original master owner address was not removed and is still an owner until removed additionalOwners[_newOwnership] = true; } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private pausers; constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @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() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _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 decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(uint256 rate, address wallet, IERC20 token) internal { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen()); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor(uint256 openingTime, uint256 closingTime) internal { // solium-disable-next-line security/no-block-members require(openingTime >= block.timestamp); require(closingTime > openingTime); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns(uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns(uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } } // File: contracts/SparkleBaseCrowdsale.sol /** * @dev SparkelBaseCrowdsale: Core crowdsale functionality */ contract SparkleBaseCrowdsale is MultiOwnable, Pausable, TimedCrowdsale { using SafeMath for uint256; /** * @dev CrowdsaleStage enumeration indicating which operational stage this contract is running */ enum CrowdsaleStage { preICO, bonusICO, mainICO } /** * @dev Internal contract variable stored */ ERC20 public tokenAddress; uint256 public tokenRate; uint256 public tokenCap; uint256 public startTime; uint256 public endTime; address public depositWallet; bool public kycRequired; bool public refundRemainingOk; uint256 public tokensSold; /** * @dev Contribution structure representing a token purchase */ struct OrderBook { uint256 weiAmount; // Amount of Wei that has been contributed towards tokens by this address uint256 pendingTokens; // Total pending tokens held by this address waiting for KYC verification, and user to claim their tokens(pending restrictions) bool kycVerified; // Has this address been kyc validated } // Contributions mapping to user addresses mapping(address => OrderBook) private orders; // Initialize the crowdsale stage to preICO (this stage will change) CrowdsaleStage public crowdsaleStage = CrowdsaleStage.preICO; /** * @dev Event signaling that a number of addresses have been approved for KYC */ event ApprovedKYCAddresses (address indexed _appovedByAddress, uint256 _numberOfApprovals); /** * @dev Event signaling that a number of addresses have been revoked from KYC */ event RevokedKYCAddresses (address indexed _revokedByAddress, uint256 _numberOfRevokals); /** * @dev Event signalling that tokens have been claimed from the crowdsale */ event TokensClaimed (address indexed _claimingAddress, uint256 _tokensClaimed); /** * @dev Event signaling that tokens were sold and how many were sold */ event TokensSold(address indexed _beneficiary, uint256 _tokensSold); /** * @dev Event signaling that toke burn approval has been changed */ event TokenRefundApprovalChanged(address indexed _approvingAddress, bool tokenBurnApproved); /** * @dev Event signaling that token burn approval has been changed */ event CrowdsaleStageChanged(address indexed _changingAddress, uint _newStageValue); /** * @dev Event signaling that crowdsale tokens have been burned */ event CrowdsaleTokensRefunded(address indexed _refundingToAddress, uint256 _numberOfTokensBurned); /** * @dev SparkleTokenCrowdsale Contract contructor */ constructor(ERC20 _tokenAddress, uint256 _tokenRate, uint256 _tokenCap, uint256 _startTime, uint256 _endTime, address _depositWallet, bool _kycRequired) public Crowdsale(_tokenRate, _depositWallet, _tokenAddress) TimedCrowdsale(_startTime, _endTime) MultiOwnable() Pausable() { tokenAddress = _tokenAddress; tokenRate = _tokenRate; tokenCap = _tokenCap; startTime = _startTime; endTime = _endTime; depositWallet = _depositWallet; kycRequired = _kycRequired; refundRemainingOk = false; } /** * @dev claimPendingTokens() provides users with a function to receive their purchase tokens * after their KYC Verification */ function claimTokens() whenNotPaused onlyWhileOpen public { // Ensure calling address is not address(0) require(msg.sender != address(0), "Invalid address specified: address(0)"); // Obtain a copy of the caller's order record OrderBook storage order = orders[msg.sender]; // Ensure caller has been KYC Verified require(order.kycVerified, "Address attempting to claim tokens is not KYC Verified."); // Ensure caller has pending tokens to claim require(order.pendingTokens > 0, "Address does not have any pending tokens to claim."); // For security sake grab the pending token value uint256 localPendingTokens = order.pendingTokens; // zero out pendingTokens to prevent potential re-entrancy vulnverability order.pendingTokens = 0; // Deliver the callers tokens _deliverTokens(msg.sender, localPendingTokens); // Emit event emit TokensClaimed(msg.sender, localPendingTokens); } /** * @dev getExchangeRate() provides a public facing manner in which to * determine the current rate of exchange in the crowdsale * @param _weiAmount is the amount of wei to purchase tokens with * @return number of tokens the specified wei amount would purchase */ function getExchangeRate(uint256 _weiAmount) whenNotPaused onlyWhileOpen public view returns (uint256) { if (crowdsaleStage == CrowdsaleStage.preICO) { // Ensure _weiAmount is > than current stage minimum require(_weiAmount >= 1 ether, "PreICO minimum ether required: 1 ETH."); } else if (crowdsaleStage == CrowdsaleStage.bonusICO || crowdsaleStage == CrowdsaleStage.mainICO) { // Ensure _weiAmount is > than current stage minimum require(_weiAmount >= 500 finney, "bonusICO/mainICO minimum ether required: 0.5 ETH."); } // Calculate the number of tokens this amount of wei is worth uint256 tokenAmount = _getTokenAmount(_weiAmount); // Ensure the number of tokens requests will not exceed available tokens require(getRemainingTokens() >= tokenAmount, "Specified wei value woudld exceed amount of tokens remaining."); // Calculate and return the token amount this amount of wei is worth (includes bonus factor) return tokenAmount; } /** * @dev getRemainingTokens() provides function to return the current remaining token count * @return number of tokens remaining in the crowdsale to be sold */ function getRemainingTokens() whenNotPaused public view returns (uint256) { // Return the balance of the contract (IE: tokenCap - tokensSold) return tokenCap.sub(tokensSold); } /** * @dev refundRemainingTokens provides functionn to refund remaining tokens to the specified address * @param _addressToRefund is the address in which the remaining tokens will be refunded to */ function refundRemainingTokens(address _addressToRefund) onlyOwner whenNotPaused public { // Ensure the specified address is not address(0) require(_addressToRefund != address(0), "Specified address is invalid [0x0]"); // Ensure the crowdsale has closed before burning tokens require(hasClosed(), "Crowdsale must be finished to burn tokens."); // Ensure that step-1 of the burning process is satisfied (owner set to true) require(refundRemainingOk, "Crowdsale remaining token refund is disabled."); uint256 tempBalance = token().balanceOf(this); // Transfer the remaining tokens to specified address _deliverTokens(_addressToRefund, tempBalance); // Emit event emit CrowdsaleTokensRefunded(_addressToRefund, tempBalance); } /** * @dev approveRemainingTokenRefund approves the function to withdraw any remaining tokens * after the crowdsale ends * @dev This was put in place as a two-step process to burn tokens so burning was secure */ function approveRemainingTokenRefund() onlyOwner whenNotPaused public { // Ensure calling address is not address(0) require(msg.sender != address(0), "Calling address invalid [0x0]"); // Ensure the crowdsale has closed before approving token burning require(hasClosed(), "Token burn approval can only be set after crowdsale closes"); refundRemainingOk = true; emit TokenRefundApprovalChanged(msg.sender, refundRemainingOk); } /** * @dev setStage() sets the current crowdsale stage to the specified value * @param _newStageValue is the new stage to be changed to */ function changeCrowdsaleStage(uint _newStageValue) onlyOwner whenNotPaused onlyWhileOpen public { // Create temporary stage variable CrowdsaleStage _stage; // Determine if caller is trying to set: preICO if (uint(CrowdsaleStage.preICO) == _newStageValue) { // Set the internal stage to the new value _stage = CrowdsaleStage.preICO; } // Determine if caller is trying to set: bonusICO else if (uint(CrowdsaleStage.bonusICO) == _newStageValue) { // Set the internal stage to the new value _stage = CrowdsaleStage.bonusICO; } // Determine if caller is trying to set: mainICO else if (uint(CrowdsaleStage.mainICO) == _newStageValue) { // Set the internal stage to the new value _stage = CrowdsaleStage.mainICO; } else { revert("Invalid stage selected"); } // Update the internal crowdsale stage to the new stage crowdsaleStage = _stage; // Emit event emit CrowdsaleStageChanged(msg.sender, uint(_stage)); } /** * @dev isAddressKYCVerified() checks the KYV Verification status of the specified address * @param _addressToLookuo address to check status of KYC Verification * @return kyc status of the specified address */ function isKYCVerified(address _addressToLookuo) whenNotPaused onlyWhileOpen public view returns (bool) { // Ensure _addressToLookuo is not address(0) require(_addressToLookuo != address(0), "Invalid address specified: address(0)"); // Obtain the addresses order record OrderBook storage order = orders[_addressToLookuo]; // Return the JYC Verification status for the specified address return order.kycVerified; } /** * @dev Approve in bulk the specified addfresses indicating they were KYC Verified * @param _addressesForApproval is a list of addresses that are to be KYC Verified */ function bulkApproveKYCAddresses(address[] _addressesForApproval) onlyOwner whenNotPaused onlyWhileOpen public { // Ensure that there are any address(es) in the provided array require(_addressesForApproval.length > 0, "Specified address array is empty"); // Interate through all addresses provided for (uint i = 0; i <_addressesForApproval.length; i++) { // Approve this address using the internal function _approveKYCAddress(_addressesForApproval[i]); } // Emit event indicating address(es) have been approved for KYC Verification emit ApprovedKYCAddresses(msg.sender, _addressesForApproval.length); } /** * @dev Revoke in bulk the specified addfresses indicating they were denied KYC Verified * @param _addressesToRevoke is a list of addresses that are to be KYC Verified */ function bulkRevokeKYCAddresses(address[] _addressesToRevoke) onlyOwner whenNotPaused onlyWhileOpen public { // Ensure that there are any address(es) in the provided array require(_addressesToRevoke.length > 0, "Specified address array is empty"); // Interate through all addresses provided for (uint i = 0; i <_addressesToRevoke.length; i++) { // Approve this address using the internal function _revokeKYCAddress(_addressesToRevoke[i]); } // Emit event indicating address(es) have been revoked for KYC Verification emit RevokedKYCAddresses(msg.sender, _addressesToRevoke.length); } /** * @dev tokensPending() provides owners the function to retrieve an addresses pending * token amount * @param _addressToLookup is the address to return the pending token value for * @return the number of pending tokens waiting to be claimed from specified address */ function tokensPending(address _addressToLookup) onlyOwner whenNotPaused onlyWhileOpen public view returns (uint256) { // Ensure specified address is not address(0) require(_addressToLookup != address(0), "Specified address is invalid [0x0]"); // Obtain the order for specified address OrderBook storage order = orders[_addressToLookup]; // Return the pendingTokens amount return order.pendingTokens; } /** * @dev contributionAmount() provides owners the function to retrieve an addresses total * contribution amount in eth * @param _addressToLookup is the address to return the contribution amount value for * @return the number of ether contribured to the crowdsale by specified address */ function contributionAmount(address _addressToLookup) onlyOwner whenNotPaused onlyWhileOpen public view returns (uint256) { // Ensure specified address is not address(0) require(_addressToLookup != address(0), "Specified address is Invalid [0x0]"); // Obtain the order for specified address OrderBook storage order = orders[_addressToLookup]; // Return the contribution amount in wei return order.weiAmount; } /** * @dev _approveKYCAddress provides the function to approve the specified address * indicating KYC Verified * @param _addressToApprove of the user that is being verified */ function _approveKYCAddress(address _addressToApprove) onlyOwner internal { // Ensure that _addressToApprove is not address(0) require(_addressToApprove != address(0), "Invalid address specified: address(0)"); // Get this addesses contribution record OrderBook storage order = orders[_addressToApprove]; // Set the contribution record to indicate address has been kyc verified order.kycVerified = true; } /** * @dev _revokeKYCAddress() provides the function to revoke previously * granted KYC verification in cases of fraud or false/invalid KYC data * @param _addressToRevoke is the address to remove KYC verification from */ function _revokeKYCAddress(address _addressToRevoke) onlyOwner internal { // Ensure address is not address(0) require(_addressToRevoke != address(0), "Invalid address specified: address(0)"); // Obtain a copy of this addresses contribution record OrderBook storage order = orders[_addressToRevoke]; // Revoke this addresses KYC verification order.kycVerified = false; } /** * @dev _rate() provides the function of calcualting the rate based on crowdsale stage * @param _weiAmount indicated the amount of ether intended to use for purchase * @return number of tokens worth based on specified Wei value */ function _rate(uint _weiAmount) internal view returns (uint256) { require(_weiAmount > 0, "Specified wei amoount must be > 0"); // Determine if the current operation stage of the crowdsale is preICO if (crowdsaleStage == CrowdsaleStage.preICO) { // Determine if the purchase is >= 21 ether if (_weiAmount >= 21 ether) { // 20% bonus return 480e8; } // Determine if the purchase is >= 11 ether if (_weiAmount >= 11 ether) { // 15% bonus return 460e8; } // Determine if the purchase is >= 5 ether if (_weiAmount >= 5 ether) { // 10% bonus return 440e8; } } else // Determine if the current operation stage of the crowdsale is bonusICO if (crowdsaleStage == CrowdsaleStage.bonusICO) { // Determine if the purchase is >= 21 ether if (_weiAmount >= 21 ether) { // 10% bonus return 440e8; } else if (_weiAmount >= 11 ether) { // 7% bonus return 428e8; } else if (_weiAmount >= 5 ether) { // 5% bonus return 420e8; } } // Rate is either < bounus or is main sale so return base rate only return rate(); } /** * @dev Performs token to wei converstion calculations based on crowdsale specification * @param _weiAmount to spend * @return number of tokens purchasable for the specified _weiAmount at crowdsale stage rates */ function _getTokenAmount(uint256 _weiAmount) whenNotPaused internal view returns (uint256) { // Get the current rate set in the constructor and calculate token units per wei uint256 currentRate = _rate(_weiAmount); // Calculate the total number of tokens buyable at based rate (before adding bonus) uint256 sparkleToBuy = currentRate.mul(_weiAmount).div(10e17); // Return proposed token amount return sparkleToBuy; } /** * @dev _preValidatePurchase provides the functionality of pre validating a potential purchase * @param _beneficiary is the address that is currently purchasing tokens * @param _weiAmount is the number of tokens this address is attempting to purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) whenNotPaused internal view { // Call into the parent validation to ensure _beneficiary and _weiAmount are valid super._preValidatePurchase(_beneficiary, _weiAmount); // Calculate amount of tokens for the specified _weiAmount uint256 requestedTokens = getExchangeRate(_weiAmount); // Calculate the currently sold tokens uint256 tempTotalTokensSold = tokensSold; // Incrememt total tokens tempTotalTokensSold.add(requestedTokens); // Ensure total max token cap is > tempTotalTokensSold require(tempTotalTokensSold <= tokenCap, "Requested wei amount will exceed the max token cap and was not accepted."); // Ensure that requested tokens will not go over the remaining token balance require(requestedTokens <= getRemainingTokens(), "Requested tokens would exceed tokens available and was not accepted."); // Obtain the order record for _beneficiary if one exists OrderBook storage order = orders[_beneficiary]; // Ensure this address has been kyc validated require(order.kycVerified, "Address attempting to purchase is not KYC Verified."); // Update this addresses order to reflect the purchase and ether spent order.weiAmount = order.weiAmount.add(_weiAmount); order.pendingTokens = order.pendingTokens.add(requestedTokens); // increment totalTokens sold tokensSold = tokensSold.add(requestedTokens); // Emit event emit TokensSold(_beneficiary, requestedTokens); } /** * @dev _processPurchase() is overridden and will be called by OpenZep v2.0 internally * @param _beneficiary is the address that is currently purchasing tokens * @param _tokenAmount is the number of tokens this address is attempting to purchase */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) whenNotPaused internal { // We do not call the base class _processPurchase() functions. This is needed here or the base // classes function will be called. } } // File: contracts/SparkleCrowdsale.sol contract SparkleCrowdsale is SparkleBaseCrowdsale { // Token contract address address public initTokenAddress = 0x4b7aD3a56810032782Afce12d7d27122bDb96efF; // Crowdsale specification uint256 public initTokenRate = 400e8; uint256 public initTokenCap = 19698000e8; uint256 public initStartTime = now; uint256 public initEndTime = now + 12 weeks; // Set this accordingly as it cannot be changed address public initDepositWallet = 0x0926a84C83d7B88338588Dca2729b590D787FA34; bool public initKYCRequired = true; constructor() SparkleBaseCrowdsale(ERC20(initTokenAddress), initTokenRate, initTokenCap, initStartTime, initEndTime, initDepositWallet, initKYCRequired) public { } }
Add a new owner address to additional owners mapping Only the master owner can add additional owner addresses/ Ensure that the address to remove is not the master owner Ensure that owner address to remove is actually an owner Add remove ownership from address in the additional owners mapping
function removeOwner(address _ownerToRemove) onlyMaster public returns (bool) { require(_ownerToRemove != super.owner(), "Permission denied [master]."); require(isOwner(_ownerToRemove), "Address specified not found in owners list."); additionalOwners[_ownerToRemove] = false; emit OwnershipRemoved(_ownerToRemove); return true; }
14,059,032
pragma solidity ^0.4.24; contract ProjectContract { address constant public receiver = 0x4FE35e4051D5Ba164eD2738B6ebC7083A4953B62; uint constant public total = 50 ether; uint constant public interest = 5; uint public fundingEnd; enum State { Init, Running, Funded, Failed, Redemption, Closed } State public state = State.Init; mapping(address => uint) public investments; mapping(address => uint) public interests; address[] public investors; // event InvestedAmountIncreased(uint amount); // event FundingStarted(); // event FundingSuccessful(); // event FundingFailed(); // event FundingClosed(); // event InvestmentWithInterestClaimed(address receiver, uint amount); // event FundedAmountTransfered(address receiver, uint amount); modifier verifyAmount() { require(address(this).balance <= total); _; } modifier initPhase() { require(state == State.Init); _; } modifier fundingPhase() { require(state == State.Running && now < fundingEnd); _; } modifier redemptionPhase() { require(state == State.Redemption); _; } modifier closedPhase() { require(state == State.Closed); _; } function startFunding() external initPhase { state = State.Running; fundingEnd = now + 1 days; // emit FundingStarted(); } function getCurrentFundingBalance() external view returns(uint) { return address(this).balance; } function invest() external payable verifyAmount fundingPhase { // emit InvestedAmountIncreased(address(this).balance); investments[msg.sender] += msg.value; interests[msg.sender] += (msg.value / 100 * interest); bool alreadyInvestor = false; for (uint i = 0; i < investors.length; i++) { if (investors[i] == msg.sender) { alreadyInvestor = true; break; } } if (!alreadyInvestor) { investors.push(msg.sender); } if (address(this).balance == total) { state = State.Funded; // emit FundingSuccessful(); } } function transferFunds() external { require(now >= fundingEnd || state == State.Funded); require(total == address(this).balance); receiver.transfer(address(this).balance); // emit FundedAmountTransfered(receiver, address(this).balance); state = State.Redemption; } function payInterest() external payable { require(msg.sender == receiver); require(msg.value == (total / 100 * interest)); } function payLoan() external payable { require(msg.sender == receiver); require(msg.value == total); } function transferInvestedAmountWithInterest() external redemptionPhase { require(address(this).balance == total + (total / 100 * interest)); for (uint i = 0; i < investors.length; i++) { uint interestAmount = interests[investors[i]]; uint investmentAmount = investments[investors[i]]; if (!investors[i].send(interestAmount + investmentAmount)) { interests[investors[i]] = interestAmount; investments[investors[i]] = investmentAmount; } else { investments[investors[i]] = 0; interests[investors[i]] = 0; // emit InvestmentWithInterestClaimed(msg.sender, amount); } } bool interestPayedBack = true; for (uint j = 0; j < investors.length; j++) { if (interests[investors[j]] != 0) { interestPayedBack = false; break; } } if (interestPayedBack) { // emit FundingClosed(); state = State.Closed; } } function getInvestorCount() external constant returns(uint count) { return investors.length; } }
emit InvestedAmountIncreased(address(this).balance); emit FundingSuccessful();
function invest() external payable verifyAmount fundingPhase { investments[msg.sender] += msg.value; interests[msg.sender] += (msg.value / 100 * interest); bool alreadyInvestor = false; for (uint i = 0; i < investors.length; i++) { if (investors[i] == msg.sender) { alreadyInvestor = true; break; } } if (!alreadyInvestor) { investors.push(msg.sender); } if (address(this).balance == total) { state = State.Funded; } }
7,321,143
pragma solidity ^0.4.24; /* Token Subscriptions on the Blockchain WIP POC simplified version of EIP-1337 / ERC-948 Austin Thomas Griffith - https://austingriffith.com https://github.com/austintgriffith/token-subscription Building on previous works: https://gist.github.com/androolloyd/0a62ef48887be00a5eff5c17f2be849a https://media.consensys.net/subscription-services-on-the-blockchain-erc-948-6ef64b083a36 https://medium.com/gitcoin/technical-deep-dive-architecture-choices-for-subscriptions-on-the-blockchain-erc948-5fae89cabc7a https://github.com/ethereum/EIPs/pull/1337 https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1077.md https://github.com/gnosis/safe-contracts Earlier Meta Transaction Demo: https://github.com/austintgriffith/bouncer-proxy Huge thanks to, as always, to OpenZeppelin for the rad contracts: */ import "openzeppelin-solidity/contracts/ECRecovery.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; contract Subscription is Ownable { using ECRecovery for bytes32; using SafeMath for uint256; constructor() public { } // contract will need to hold funds to pay gas // copied from https://github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol function () public payable { emit Received(msg.sender, msg.value); } event Received (address indexed sender, uint value); event ExecuteSubscription( address indexed from, //the subscriber address indexed to, //the publisher address tokenAddress, //the token address paid to the publisher uint256 tokenAmount, //the token amount paid to the publisher uint256 periodSeconds, //the period in seconds between payments address gasToken, //the address of the token to pay relayer (0 for eth) uint256 gasPrice, //the amount of tokens or eth to pay relayer (0 for free) address gasPayer //the address that will pay the tokens to the relayer ); event FailedExecuteSubscription( address indexed from, //the subscriber address indexed to, //the publisher address tokenAddress, //the token address paid to the publisher uint256 tokenAmount, //the token amount paid to the publisher uint256 periodSeconds, //the period in seconds between payments address gasToken, //the address of the token to pay relayer (0 for eth) uint256 gasPrice, //the amount of tokens or eth to pay relayer (0 for free) address gasPayer //the address that will pay the tokens to the relayer ); // similar to a nonce that avoids replay attacks this allows a single execution // every x seconds for a given subscription // subscriptionHash => next valid block number mapping(bytes32 => uint256) public nextValidTimestamp; // for some cases of delegated execution, this contract will pay a third party // to execute the transfer. If this happens, the owner of this contract must // sign the subscriptionHash mapping(bytes32 => bool) public publisherSigned; // only the owner of this contract can sign the subscriptionHash to whitelist // a specific subscription to start rewarding the relayers for paying the // gas of the transactions out of the balance of this contract function signSubscriptionHash(bytes32 subscriptionHash) public onlyOwner returns(bool) { publisherSigned[subscriptionHash] = true; return true; } // this is used by external smart contracts to verify on-chain that a // particular subscription is "paid" and "active" // there must be a small grace period added to allow the publisher // or desktop miner to execute function isSubscriptionActive( bytes32 subscriptionHash, uint256 gracePeriodSeconds ) external view returns (bool) { return (block.timestamp >= nextValidTimestamp[subscriptionHash].add(gracePeriodSeconds) ); } // given the subscription details, generate a hash and try to kind of follow // the eip-191 standard and eip-1077 standard from my dude @avsa function getSubscriptionHash( address from, //the subscriber address to, //the publisher address tokenAddress, //the token address paid to the publisher uint256 tokenAmount, //the token amount paid to the publisher uint256 periodSeconds, //the period in seconds between payments address gasToken, //the address of the token to pay relayer (0 for eth) uint256 gasPrice, //the amount of tokens or eth to pay relayer (0 for free) address gasPayer //the address that will pay the tokens to the relayer ) public view returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), from, to, tokenAddress, tokenAmount, periodSeconds, gasToken, gasPrice, gasPayer )); } //ecrecover the signer from hash and the signature function getSubscriptionSigner( bytes32 subscriptionHash, //hash of subscription bytes signature //proof the subscriber signed the meta trasaction ) public pure returns (address) { return subscriptionHash.toEthSignedMessageHash().recover(signature); } //check if a subscription is signed correctly and the timestamp is ready for // the next execution to happen function isSubscriptionReady( address from, //the subscriber address to, //the publisher address tokenAddress, //the token address paid to the publisher uint256 tokenAmount, //the token amount paid to the publisher uint256 periodSeconds, //the period in seconds between payments address gasToken, //the address of the token to pay relayer (0 for eth) uint256 gasPrice, //the amount of tokens or eth to pay relayer (0 for free) address gasPayer, //the address that will pay the tokens to the relayer bytes signature //proof the subscriber signed the meta trasaction ) public view returns (bool) { bytes32 subscriptionHash = getSubscriptionHash( from, to, tokenAddress, tokenAmount, periodSeconds, gasToken, gasPrice, gasPayer ); address signer = getSubscriptionSigner(subscriptionHash, signature); uint256 allowance = ERC20(tokenAddress).allowance(from, address(this)); return ( signer == from && block.timestamp >= nextValidTimestamp[subscriptionHash] && allowance >= tokenAmount ); } // you don't really need this if you are using the approve/transferFrom method // because you control the flow of tokens by approving this contract address, // but to make the contract an extensible example for later user I'll add this function cancelSubscription( address from, //the subscriber address to, //the publisher address tokenAddress, //the token address paid to the publisher uint256 tokenAmount, //the token amount paid to the publisher uint256 periodSeconds, //the period in seconds between payments address gasToken, //the address of the token to pay relayer (0 for eth) uint256 gasPrice, //the amount of tokens or eth to pay relayer (0 for free) address gasPayer, //the address that will pay the tokens to the relayer bytes signature //proof the subscriber signed the meta trasaction ) public returns (bool success) { bytes32 subscriptionHash = getSubscriptionHash( from, to, tokenAddress, tokenAmount, periodSeconds, gasToken, gasPrice, gasPayer ); address signer = subscriptionHash.toEthSignedMessageHash().recover(signature); //the signature must be valid require(signer == from, "Invalid Signature for subscription cancellation"); //since we can't underflow (SAFEMATH!), we'll just set it to a large number nextValidTimestamp[subscriptionHash]=99999999999; //subscription will become valid again Wednesday, November 16, 5138 9:46:39 AM //at this point the nextValidTimestamp should be a timestamp that will never //be reached during the brief window human existence return true; } // execute the transferFrom to pay the publisher from the subscriber // the subscriber has full control by approving this contract an allowance function executeSubscription( address from, //the subscriber address to, //the publisher address tokenAddress, //the token address paid to the publisher uint256 tokenAmount, //the token amount paid to the publisher uint256 periodSeconds, //the period in seconds between payments address gasToken, //the address of the token to pay relayer (0 for eth) uint256 gasPrice, //the amount of tokens or eth to pay relayer (0 for free) address gasPayer, //the address that will pay the tokens to the relayer bytes signature //proof the subscriber signed the meta trasaction ) public returns (bool success) { // make sure the subscription is valid and ready // pulled this out so I have the hash, should be exact code as "isSubscriptionReady" bytes32 subscriptionHash = getSubscriptionHash( from, to, tokenAddress, tokenAmount, periodSeconds, gasToken, gasPrice, gasPayer ); address signer = getSubscriptionSigner(subscriptionHash, signature); //the signature must be valid require(signer == from, "Invalid Signature"); //timestamp must be equal to or past the next period require( block.timestamp >= nextValidTimestamp[subscriptionHash], "Subscription is not ready" ); // increment the next valid period time //if (nextValidTimestamp[subscriptionHash] == 0) { //I changed this to always use the timestamp // this means desktop miners MUST submit transactions as fast as possible // or subscriptions will start to lag // the upside of doing it this way is the approve/allowance of the erc20 // can now pause and restart the subscription whenever they want nextValidTimestamp[subscriptionHash] = block.timestamp.add(periodSeconds); //if you would like your subscription to be able to submit multiple months // all at once, switch back to the uncommented method, but if the subscriber // pauses the allowance and then later approves... a bunch of funds can all // move at once as you work through past months of unpaid subscriptions //} else { // nextValidTimestamp[subscriptionHash] = // nextValidTimestamp[subscriptionHash].add(periodSeconds); //} // now, let make the transfer from the subscriber to the publisher bool result = ERC20(tokenAddress).transferFrom(from,to,tokenAmount); if (result) { emit ExecuteSubscription( from, to, tokenAddress, tokenAmount, periodSeconds, gasToken, gasPrice, gasPayer ); } else { emit FailedExecuteSubscription( from, to, tokenAddress, tokenAmount, periodSeconds, gasToken, gasPrice, gasPayer ); } // it is possible for the subscription execution to be run by a third party // incentivized in the terms of the subscription with a gasToken and gasPrice // pay that out now... if (gasPrice > 0) { if (gasToken == address(0)) { // this is an interesting case where the service will pay the third party // ethereum out of the subscription contract itself // for this to work the publisher must send ethereum to the contract require( from == owner || publisherSigned[subscriptionHash], "Publisher has not signed this subscriptionHash" ); require(msg.sender.call.value(gasPrice).gas(36000)(),//still unsure about how much gas to use here "Subscription contract failed to pay ether to relayer" ); } else if (gasPayer == address(this) || gasPayer == address(0)) { // in this case, this contract will pay a token to the relayer to // incentivize them to pay the gas for the meta transaction // for security, the publisher must have signed the subscriptionHash require(from == owner || publisherSigned[subscriptionHash], "Publisher has not signed this subscriptionHash" ); require(ERC20(gasToken).transfer(msg.sender, gasPrice), "Failed to pay gas as contract" ); } else if (gasPayer == from) { // in this case the relayer is paid with a token from the subscriber // this works best if it is the same token being transferred to the // publisher because it is already in the allowance require( ERC20(gasToken).transferFrom(from, msg.sender, gasPrice), "Failed to pay gas as from account" ); } else { // the subscriber could craft the gasPayer to be a fellow subscriber that // that has approved this contract to move tokens and then exploit that // don't allow that... revert("The gasPayer is invalid"); // on the other hand it might be really cool to allow *any* account to // pay the third party as long as they have approved this contract // AND the publisher has signed off on it. The downside would be a // publisher not paying attention and signs a subscription that attacks // a different subscriber } } return result; } }
given the subscription details, generate a hash and try to kind of follow the eip-191 standard and eip-1077 standard from my dude @avsa
function getSubscriptionHash( ) public view returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), from, to, tokenAddress, tokenAmount, periodSeconds, gasToken, gasPrice, gasPayer )); }
12,759,572
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; /** * @title WAMPL (Wrapped AMPL). * * @dev A fixed-balance ERC-20 wrapper for the AMPL rebasing token. * * Users deposit AMPL into this contract and are minted wAMPL. * * Each account's wAMPL balance represents the fixed percentage ownership * of AMPL's market cap. * * For example: 100K wAMPL => 1% of the AMPL market cap * when the AMPL supply is 100M, 100K wAMPL will be redeemable for 1M AMPL * when the AMPL supply is 500M, 100K wAMPL will be redeemable for 5M AMPL * and so on. * * We call wAMPL the "wrapper" token and AMPL the "underlying" or "wrapped" token. */ contract WAMPL is ERC20, ERC20Permit { using SafeERC20 for IERC20; //-------------------------------------------------------------------------- // Constants /// @dev The maximum wAMPL supply. uint256 public constant MAX_WAMPL_SUPPLY = 10000000 * (10**18); // 10 M //-------------------------------------------------------------------------- // Attributes /// @dev The reference to the AMPL token. address private immutable _ampl; //-------------------------------------------------------------------------- /// @param ampl The AMPL ERC20 token address. /// @param name_ The wAMPL ERC20 name. /// @param symbol_ The wAMPL ERC20 symbol. constructor( address ampl, string memory name_, string memory symbol_ ) ERC20(name_, symbol_) ERC20Permit(name_) { _ampl = ampl; } //-------------------------------------------------------------------------- // WAMPL write methods /// @notice Transfers AMPLs from {msg.sender} and mints wAMPLs. /// /// @param wamples The amount of wAMPLs to mint. /// @return The amount of AMPLs deposited. function mint(uint256 wamples) external returns (uint256) { uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _deposit(_msgSender(), _msgSender(), amples, wamples); return amples; } /// @notice Transfers AMPLs from {msg.sender} and mints wAMPLs, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @param wamples The amount of wAMPLs to mint. /// @return The amount of AMPLs deposited. function mintFor(address to, uint256 wamples) external returns (uint256) { uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _deposit(_msgSender(), to, amples, wamples); return amples; } /// @notice Burns wAMPLs from {msg.sender} and transfers AMPLs back. /// /// @param wamples The amount of wAMPLs to burn. /// @return The amount of AMPLs withdrawn. function burn(uint256 wamples) external returns (uint256) { uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), _msgSender(), amples, wamples); return amples; } /// @notice Burns wAMPLs from {msg.sender} and transfers AMPLs back, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @param wamples The amount of wAMPLs to burn. /// @return The amount of AMPLs withdrawn. function burnTo(address to, uint256 wamples) external returns (uint256) { uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return amples; } /// @notice Burns all wAMPLs from {msg.sender} and transfers AMPLs back. /// /// @return The amount of AMPLs withdrawn. function burnAll() external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), _msgSender(), amples, wamples); return amples; } /// @notice Burns all wAMPLs from {msg.sender} and transfers AMPLs back, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @return The amount of AMPLs withdrawn. function burnAllTo(address to) external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return amples; } /// @notice Transfers AMPLs from {msg.sender} and mints wAMPLs. /// /// @param amples The amount of AMPLs to deposit. /// @return The amount of wAMPLs minted. function deposit(uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _deposit(_msgSender(), _msgSender(), amples, wamples); return wamples; } /// @notice Transfers AMPLs from {msg.sender} and mints wAMPLs, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @param amples The amount of AMPLs to deposit. /// @return The amount of wAMPLs minted. function depositFor(address to, uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _deposit(_msgSender(), to, amples, wamples); return wamples; } /// @notice Burns wAMPLs from {msg.sender} and transfers AMPLs back. /// /// @param amples The amount of AMPLs to withdraw. /// @return The amount of burnt wAMPLs. function withdraw(uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _withdraw(_msgSender(), _msgSender(), amples, wamples); return wamples; } /// @notice Burns wAMPLs from {msg.sender} and transfers AMPLs back, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @param amples The amount of AMPLs to withdraw. /// @return The amount of burnt wAMPLs. function withdrawTo(address to, uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return wamples; } /// @notice Burns all wAMPLs from {msg.sender} and transfers AMPLs back. /// /// @return The amount of burnt wAMPLs. function withdrawAll() external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), _msgSender(), amples, wamples); return wamples; } /// @notice Burns all wAMPLs from {msg.sender} and transfers AMPLs back, /// to the specified beneficiary. /// /// @param to The beneficiary wallet. /// @return The amount of burnt wAMPLs. function withdrawAllTo(address to) external returns (uint256) { uint256 wamples = balanceOf(_msgSender()); uint256 amples = _wampleToAmple(wamples, _queryAMPLSupply()); _withdraw(_msgSender(), to, amples, wamples); return wamples; } //-------------------------------------------------------------------------- // WAMPL view methods /// @return The address of the underlying "wrapped" token ie) AMPL. function underlying() external view returns (address) { return _ampl; } /// @return The total AMPLs held by this contract. function totalUnderlying() external view returns (uint256) { return _wampleToAmple(totalSupply(), _queryAMPLSupply()); } /// @param owner The account address. /// @return The AMPL balance redeemable by the owner. function balanceOfUnderlying(address owner) external view returns (uint256) { return _wampleToAmple(balanceOf(owner), _queryAMPLSupply()); } /// @param amples The amount of AMPL tokens. /// @return The amount of wAMPL tokens exchangeable. function underlyingToWrapper(uint256 amples) external view returns (uint256) { return _ampleToWample(amples, _queryAMPLSupply()); } /// @param wamples The amount of wAMPL tokens. /// @return The amount of AMPL tokens exchangeable. function wrapperToUnderlying(uint256 wamples) external view returns (uint256) { return _wampleToAmple(wamples, _queryAMPLSupply()); } //-------------------------------------------------------------------------- // Private methods /// @dev Internal helper function to handle deposit state change. /// @param from The initiator wallet. /// @param to The beneficiary wallet. /// @param amples The amount of AMPLs to deposit. /// @param wamples The amount of wAMPLs to mint. function _deposit( address from, address to, uint256 amples, uint256 wamples ) private { IERC20(_ampl).safeTransferFrom(from, address(this), amples); _mint(to, wamples); } /// @dev Internal helper function to handle withdraw state change. /// @param from The initiator wallet. /// @param to The beneficiary wallet. /// @param amples The amount of AMPLs to withdraw. /// @param wamples The amount of wAMPLs to burn. function _withdraw( address from, address to, uint256 amples, uint256 wamples ) private { _burn(from, wamples); IERC20(_ampl).safeTransfer(to, amples); } /// @dev Queries the current total supply of AMPL. /// @return The current AMPL supply. function _queryAMPLSupply() private view returns (uint256) { return IERC20(_ampl).totalSupply(); } //-------------------------------------------------------------------------- // Pure methods /// @dev Converts AMPLs to wAMPL amount. function _ampleToWample(uint256 amples, uint256 totalAMPLSupply) private pure returns (uint256) { return (amples * MAX_WAMPL_SUPPLY) / totalAMPLSupply; } /// @dev Converts wAMPLs amount to AMPLs. function _wampleToAmple(uint256 wamples, uint256 totalAMPLSupply) private pure returns (uint256) { return (wamples * totalAMPLSupply) / MAX_WAMPL_SUPPLY; } } // 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; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation 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. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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.8.0; import "./ECDSA.sol"; /** * @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 */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; 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) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } }
Transfers AMPLs from {msg.sender} and mints wAMPLs. amples The amount of AMPLs to deposit. return The amount of wAMPLs minted.
function deposit(uint256 amples) external returns (uint256) { uint256 wamples = _ampleToWample(amples, _queryAMPLSupply()); _deposit(_msgSender(), _msgSender(), amples, wamples); return wamples; }
10,434,880
pragma solidity 0.5.16; interface ierc207 { //inject NONSTANDARD NAMING function TOTALSUPPLY3() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF6(address ACCOUNT8) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER0(address RECIPIENT4, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE8(address OWNER10, address SPENDER9) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE6(address SPENDER9, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM9(address SENDER7, address RECIPIENT4, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER10(address indexed FROM9, address indexed TO4, uint VALUE10); //inject NONSTANDARD NAMING event APPROVAL6(address indexed OWNER10, address indexed SPENDER9, uint VALUE10); //inject NONSTANDARD NAMING } contract context1 { //inject NONSTANDARD NAMING constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER8() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract erc209 is context1, ierc207 { //inject NONSTANDARD NAMING using safemath3 for uint; mapping (address => uint) private _BALANCES7; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint)) private _ALLOWANCES5; //inject NONSTANDARD NAMING uint private _TOTALSUPPLY10; //inject NONSTANDARD NAMING function TOTALSUPPLY3() public view returns (uint) { //inject NONSTANDARD NAMING return _TOTALSUPPLY10; } function BALANCEOF6(address ACCOUNT8) public view returns (uint) { //inject NONSTANDARD NAMING return _BALANCES7[ACCOUNT8]; } function TRANSFER0(address RECIPIENT4, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER10(_MSGSENDER8(), RECIPIENT4, AMOUNT10); return true; } function ALLOWANCE8(address OWNER10, address SPENDER9) public view returns (uint) { //inject NONSTANDARD NAMING return _ALLOWANCES5[OWNER10][SPENDER9]; } function APPROVE6(address SPENDER9, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE9(_MSGSENDER8(), SPENDER9, AMOUNT10); return true; } function TRANSFERFROM9(address SENDER7, address RECIPIENT4, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER10(SENDER7, RECIPIENT4, AMOUNT10); _APPROVE9(SENDER7, _MSGSENDER8(), _ALLOWANCES5[SENDER7][_MSGSENDER8()].SUB6(AMOUNT10, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE7(address SPENDER9, uint ADDEDVALUE4) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE9(_MSGSENDER8(), SPENDER9, _ALLOWANCES5[_MSGSENDER8()][SPENDER9].ADD8(ADDEDVALUE4)); return true; } function DECREASEALLOWANCE8(address SPENDER9, uint SUBTRACTEDVALUE3) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE9(_MSGSENDER8(), SPENDER9, _ALLOWANCES5[_MSGSENDER8()][SPENDER9].SUB6(SUBTRACTEDVALUE3, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER10(address SENDER7, address RECIPIENT4, uint AMOUNT10) internal { //inject NONSTANDARD NAMING require(SENDER7 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT4 != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER5(SENDER7, RECIPIENT4, AMOUNT10); _BALANCES7[SENDER7] = _BALANCES7[SENDER7].SUB6(AMOUNT10, "ERC20: transfer amount exceeds balance"); _BALANCES7[RECIPIENT4] = _BALANCES7[RECIPIENT4].ADD8(AMOUNT10); emit TRANSFER10(SENDER7, RECIPIENT4, AMOUNT10); } function _MINT8(address ACCOUNT8, uint AMOUNT10) internal { //inject NONSTANDARD NAMING require(ACCOUNT8 != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER5(address(0), ACCOUNT8, AMOUNT10); _TOTALSUPPLY10 = _TOTALSUPPLY10.ADD8(AMOUNT10); _BALANCES7[ACCOUNT8] = _BALANCES7[ACCOUNT8].ADD8(AMOUNT10); emit TRANSFER10(address(0), ACCOUNT8, AMOUNT10); } function _BURN2(address ACCOUNT8, uint AMOUNT10) internal { //inject NONSTANDARD NAMING require(ACCOUNT8 != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER5(ACCOUNT8, address(0), AMOUNT10); _BALANCES7[ACCOUNT8] = _BALANCES7[ACCOUNT8].SUB6(AMOUNT10, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY10 = _TOTALSUPPLY10.SUB6(AMOUNT10); emit TRANSFER10(ACCOUNT8, address(0), AMOUNT10); } function _APPROVE9(address OWNER10, address SPENDER9, uint AMOUNT10) internal { //inject NONSTANDARD NAMING require(OWNER10 != address(0), "ERC20: approve from the zero address"); require(SPENDER9 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES5[OWNER10][SPENDER9] = AMOUNT10; emit APPROVAL6(OWNER10, SPENDER9, AMOUNT10); } function _BEFORETOKENTRANSFER5(address FROM9, address TO4, uint256 AMOUNT10) internal { } //inject NONSTANDARD NAMING } contract erc20detailed3 is ierc207 { //inject NONSTANDARD NAMING string private _NAME4; //inject NONSTANDARD NAMING string private _SYMBOL3; //inject NONSTANDARD NAMING uint8 private _DECIMALS5; //inject NONSTANDARD NAMING uint256 private _CAP1; //inject NONSTANDARD NAMING constructor (string memory NAME1, string memory SYMBOL10, uint8 DECIMALS2, uint256 CAP9) public { //inject NONSTANDARD NAMING _NAME4 = NAME1; _SYMBOL3 = SYMBOL10; _DECIMALS5 = DECIMALS2; _CAP1 = CAP9; } function NAME8() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME4; } function SYMBOL10() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL3; } function DECIMALS8() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS5; } function CAP3() public view returns (uint256) { //inject NONSTANDARD NAMING return _CAP1; } } library safemath3 { //inject NONSTANDARD NAMING function ADD8(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING uint C10 = A10 + B3; //inject NONSTANDARD NAMING require(C10 >= A10, "SafeMath: addition overflow"); return C10; } function SUB6(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB6(A10, B3, "SafeMath: subtraction overflow"); } function SUB6(uint A10, uint B3, string memory ERRORMESSAGE2) internal pure returns (uint) { //inject NONSTANDARD NAMING require(B3 <= A10, ERRORMESSAGE2); uint C10 = A10 - B3; //inject NONSTANDARD NAMING return C10; } function MUL10(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING if (A10 == 0) { return 0; } uint C10 = A10 * B3; //inject NONSTANDARD NAMING require(C10 / A10 == B3, "SafeMath: multiplication overflow"); return C10; } function DIV1(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV1(A10, B3, "SafeMath: division by zero"); } function DIV1(uint A10, uint B3, string memory ERRORMESSAGE2) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(B3 > 0, ERRORMESSAGE2); uint C10 = A10 / B3; //inject NONSTANDARD NAMING return C10; } } library address8 { //inject NONSTANDARD NAMING function ISCONTRACT7(address ACCOUNT8) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 CODEHASH8; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH10 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH8 := extcodehash(ACCOUNT8) } return (CODEHASH8 != 0x0 && CODEHASH8 != ACCOUNTHASH10); } } library safeerc207 { //inject NONSTANDARD NAMING using safemath3 for uint; using address8 for address; function SAFETRANSFER0(ierc207 TOKEN3, address TO4, uint VALUE10) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.TRANSFER0.selector, TO4, VALUE10)); } function SAFETRANSFERFROM0(ierc207 TOKEN3, address FROM9, address TO4, uint VALUE10) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.TRANSFERFROM9.selector, FROM9, TO4, VALUE10)); } function SAFEAPPROVE8(ierc207 TOKEN3, address SPENDER9, uint VALUE10) internal { //inject NONSTANDARD NAMING require((VALUE10 == 0) || (TOKEN3.ALLOWANCE8(address(this), SPENDER9) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.APPROVE6.selector, SPENDER9, VALUE10)); } function CALLOPTIONALRETURN7(ierc207 TOKEN3, bytes memory DATA10) private { //inject NONSTANDARD NAMING require(address(TOKEN3).ISCONTRACT7(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS10, bytes memory RETURNDATA2) = address(TOKEN3).call(DATA10); //inject NONSTANDARD NAMING require(SUCCESS10, "SafeERC20: low-level call failed"); if (RETURNDATA2.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA2, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract hdt1 is erc209, erc20detailed3 { //inject NONSTANDARD NAMING using safeerc207 for ierc207; using address8 for address; using safemath3 for uint; address public GOVERNANCE4; //inject NONSTANDARD NAMING address public PENDINGGOV10; //inject NONSTANDARD NAMING mapping (address => bool) public MINTERS7; //inject NONSTANDARD NAMING event NEWPENDINGGOV1(address OLDPENDINGGOV6, address NEWPENDINGGOV5); //inject NONSTANDARD NAMING event NEWGOV0(address OLDGOV6, address NEWGOV3); //inject NONSTANDARD NAMING // Modifiers modifier ONLYGOV3() { //inject NONSTANDARD NAMING require(msg.sender == GOVERNANCE4, "HUB-Token: !governance"); _; } constructor () public erc20detailed3("HUB.finance", "HDT", 18, 800000000 * 10 ** 18) { GOVERNANCE4 = tx.origin; } function MINT5(address _ACCOUNT7, uint256 _AMOUNT8) public { //inject NONSTANDARD NAMING require(MINTERS7[msg.sender], "HUB-Token: !minter"); _MINT8(_ACCOUNT7, _AMOUNT8); } function ADDMINTER2(address _MINTER6) public ONLYGOV3 { //inject NONSTANDARD NAMING MINTERS7[_MINTER6] = true; } function REMOVEMINTER6(address _MINTER6) public ONLYGOV3 { //inject NONSTANDARD NAMING MINTERS7[_MINTER6] = false; } function SETPENDINGGOV6(address _PENDINGGOV2) //inject NONSTANDARD NAMING external ONLYGOV3 { address OLDPENDINGGOV6 = PENDINGGOV10; //inject NONSTANDARD NAMING PENDINGGOV10 = _PENDINGGOV2; emit NEWPENDINGGOV1(OLDPENDINGGOV6, _PENDINGGOV2); } function ACCEPTGOV3() //inject NONSTANDARD NAMING external { require(msg.sender == PENDINGGOV10, "HUB-Token: !pending"); address OLDGOV6 = GOVERNANCE4; //inject NONSTANDARD NAMING GOVERNANCE4 = PENDINGGOV10; PENDINGGOV10 = address(0); emit NEWGOV0(OLDGOV6, GOVERNANCE4); } function _BEFORETOKENTRANSFER5(address FROM9, address TO4, uint256 AMOUNT10) internal { //inject NONSTANDARD NAMING super._BEFORETOKENTRANSFER5(FROM9, TO4, AMOUNT10); if (FROM9 == address(0)) { // When minting tokens require(TOTALSUPPLY3().ADD8(AMOUNT10) <= CAP3(), "HUB-Token: Cap exceeded"); } } }
inject NONSTANDARD NAMING
function SYMBOL10() public view returns (string memory) {
5,469,237
./full_match/1/0x7f312a75B62846033Bc5471c5BcB94b1abfAf06d/sources/src/EthlizardsV2.sol
Interface for marketplaces/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC2981, ERC721) returns (bool) { return super.supportsInterface(interfaceId); }
16,447,781
./partial_match/1/0x5438Dff89eD8cecF2F8629C739f320ABbc7C4b4f/sources/TwitterAuthenticator.sol
Prevent overwriting existing twitterChallengeId
function linkTwitterAccount(string memory twitterChallengeId) public { require(!walletLinked[msg.sender], "Wallet already linked"); walletLinked[msg.sender] = true; emit TwitterAccountLinked(msg.sender, twitterChallengeId); }
15,726,385
pragma solidity ^0.4.23; //import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; contract BlockSpaceToken is ERC721Token { using SafeMath for uint; /* - Miners is currently the issuer and offerer - Taker is the owner of the NFT - Taker pays the miner for the NFT */ struct Derivative { uint lower; uint upper; uint gasLimit; // refers to the amount of gas in a block address offerer; uint bond; bool settled; bytes executionMessage; // what function to call when the miner settles the contract address executionAddress; // the address of the smart contract to call } event DerivativeCreated(uint indexed id, uint lower, uint upper, uint gasLimit, uint bond, address indexed offerer); event DerivativeSettled(uint indexed id, address indexed maker, address indexed taker, bool executed); event BondClaimed(uint indexed id, address indexed taker, uint bond); event DerivativeCanceled(uint indexed id, address indexed offerer, uint gasLimit, uint bond); mapping (uint => Derivative) public derivativeData; constructor() ERC721Token("BlockSpaceToken","SPACE") public { } // Miners are the issuers and must set the bond when they create the contract function mint(uint _lower, uint _upper, uint _gasLimit) public payable returns (uint) { require(_lower < _upper); require(_lower > block.number); uint id = totalSupply(); address _offerer = msg.sender; uint _bond = msg.value; derivativeData[id] = Derivative(_lower, _upper, _gasLimit, _offerer, _bond, false, "", address(0x0)); emit DerivativeCreated(id, _lower, _upper, _gasLimit, _bond, _offerer); _mint(msg.sender, id); return id; } // Trading the miners / offerer function transferOfferer(uint _id, address _offerer) public { // Need to have the existing offerer allow another agent to take over it // Can copy pattern `safeTransferFrom` require(_id < totalSupply()); Derivative storage d = derivativeData[_id]; require(msg.sender == d.offerer); d.offerer = _offerer; } // Note bond can only be increased, not decreased in current implimentation // No access controls anyone can increase the bond amount function increaseBond(uint _id) public payable { derivativeData[_id].bond += msg.value; } function setExecutionAddress(uint _id, address _executionAddress) public { require(msg.sender == ownerOf(_id)); derivativeData[_id].executionAddress = _executionAddress; } function setExecutionMessage(uint _id, bytes _executionMessage) public { require(msg.sender == ownerOf(_id)); derivativeData[_id].executionMessage = _executionMessage; } function settle(uint _id) public returns (bool) { require(_id < totalSupply()); Derivative storage d = derivativeData[_id]; require(msg.sender == d.offerer); assert(gasleft() > d.gasLimit); address newAddress = d.executionAddress; bool executed = newAddress.call.gas(d.gasLimit)(d.executionMessage); if (executed) { d.offerer.transfer(d.bond); d.settled = true; } emit DerivativeSettled(_id, d.offerer, ownerOf(_id), executed); return executed; } // If the miner / offerer does not execute and the block height has passed // -> then the taker can claim the bond function reclaim(uint _id) public { require(_id < totalSupply()); Derivative storage d = derivativeData[_id]; if (d.upper < block.number) { ownerOf(_id).transfer(d.bond); // is using `ownerOf(_id)` more efficient? d.settled = true; emit BondClaimed(_id, ownerOf(_id), d.bond); } } // Should follow the chicago style futures model for cancelling function cancel(uint _id) public { require(_id < totalSupply()); Derivative storage d = derivativeData[_id]; require(msg.sender == d.offerer); require(ownerOf(_id) != address(0)); require(!d.settled); d.settled = true; d.offerer.transfer(d.bond); emit DerivativeCanceled(_id, d.offerer, d.gasLimit, d.bond); } }
If the miner / offerer does not execute and the block height has passed -> then the taker can claim the bond
function reclaim(uint _id) public { require(_id < totalSupply()); Derivative storage d = derivativeData[_id]; if (d.upper < block.number) { d.settled = true; emit BondClaimed(_id, ownerOf(_id), d.bond); } }
12,905,674
pragma solidity >=0.4.24; import "./Store.sol"; import "./Governance.sol"; import "../libraries/Crypto.sol"; import "./interfaces/IExchange.sol"; contract ExchangeCore is IExchange, Store, Governance, Crypto { //order filled map from user->orderId->filledAmount mapping(address => mapping(bytes32 => uint256)) public userOrders; //order canceled by the user map from user->orderId->true/false mapping(address => mapping(bytes32 => bool)) canceledOrders; event OrderCancel(address indexed user, bytes32 orderId); ///default function.transfer ether to this contract is not allowed by default function() public { revert(); } ///order struct struct Order { address tokenGet; address tokenGive; uint256 amountGet; uint256 amountGive; address user; uint256 fee; uint256 salt; bytes32 orderId; address baseToken; } /** * @dev settle taker and maker's orders * * @param _addresses : * - 0:token address of maker get; * - 1:token address of taker get; * - 2:token address of maker give; * - 3:token address of taker give; * - 4:maker address; * - 5:taker address; * - 6:base token address of maker .default is 0 ,then base token is ETH; * - 7:base token address of taker .default is 0 ,then base token is ETH; * @param _values : * - 0:amount of maker get * - 1:amount of taker get * - 2:amount of maker give * - 3:amount of taker give * - 4:fee(base token) that maker need to pay * - 5:fee(base token) that taker need to pay * - 6:maker's salt number * - 7:taker's salt number * - 8:amount of traded token * @param _makerSig maker's signature in 65 bytes * @param _takerSig maker's signature in 65 bytes **/ function settleOrder(address[8] _addresses, uint256[9] _values, bytes _makerSig, bytes _takerSig) public notPaused onlyRelayer{ Order memory maker = Order({ tokenGet : _addresses[0], tokenGive : _addresses[2], user : _addresses[4], amountGet : _values[0], amountGive : _values[2], fee : _values[4], salt : _values[6], orderId : 0x0, baseToken : _addresses[6] }); Order memory taker = Order({ tokenGet : _addresses[1], tokenGive : _addresses[3], user : _addresses[5], amountGet : _values[1], amountGive : _values[3], fee : _values[5], salt : _values[7], orderId : 0, baseToken : _addresses[7] }); //generate orderId.the salt param is to ensure the orderId is unique maker.orderId = generateOrderId(maker.tokenGet, maker.amountGet, maker.tokenGive, maker.amountGive, maker.baseToken, maker.salt); taker.orderId = generateOrderId(taker.tokenGet, taker.amountGet, taker.tokenGive, taker.amountGive, taker.baseToken, taker.salt); //make sure order is not canceled require(!canceledOrders[maker.user][maker.orderId], "make order is canceled."); require(!canceledOrders[taker.user][taker.orderId], "taker order is canceled."); //maker sure order signature is correct require(validateSignature(maker.orderId, maker.user, _makerSig), "maker signature is error."); require(validateSignature(taker.orderId, taker.user, _takerSig), "taker signature is error."); // make sure maker and taker have the same trade pair require(maker.baseToken == taker.baseToken, "base token not the same."); require((maker.tokenGet == taker.tokenGive && maker.tokenGive == taker.tokenGet) && (taker.baseToken == taker.tokenGet || taker.baseToken == taker.tokenGive) , "maker and taker not the same trade pair."); //make sure token registered require(tokenRegistered[maker.baseToken][maker.tokenGet]||tokenRegistered[maker.baseToken][maker.tokenGive],"maker token not registered"); require(tokenRegistered[taker.baseToken][taker.tokenGet]||tokenRegistered[taker.baseToken][taker.tokenGive],"taker token not registered"); ///match order and do settlement matchSettle(maker, taker, _values[8]); } /** * @dev match orders and do settlement on chain * @param maker maker's order info * @param taker taker's order info * @param traded trade amount submitted by relayer **/ function matchSettle(Order maker, Order taker, uint256 traded) internal { //match maker and taker order (uint256 takerGet, uint256 takerGive) = doMatch(maker, taker, traded); //do settle doSettle(maker, taker, takerGet, takerGive); } /** * @dev match maker and taker's orders * @param maker maker's order info * @param taker taker's order info * @param traded trade amount submitted by relayer **/ function doMatch(Order maker, Order taker, uint256 traded) internal returns (uint256 takerGet, uint256 takerGive){ //make sure sell price>=buy price require(maker.amountGive.mul(taker.amountGive) >= maker.amountGet.mul(taker.amountGet), "price not match"); if (taker.baseToken == taker.tokenGet) { //taker sell uint256 makerAmount = maker.amountGet - userOrders[maker.user][maker.orderId]; uint256 takerAmount = taker.amountGive - userOrders[taker.user][taker.orderId]; require(traded > 0 && traded <= makerAmount && traded <= takerAmount, "trade amount error."); takerGive = traded; takerGet = (maker.amountGive * takerGive) / maker.amountGet; userOrders[taker.user][taker.orderId] = userOrders[taker.user][taker.orderId] + takerGive; userOrders[maker.user][maker.orderId] = userOrders[maker.user][maker.orderId] + takerGive; } else { // taker buy takerAmount = taker.amountGet - userOrders[taker.user][taker.orderId]; makerAmount = maker.amountGive - userOrders[maker.user][maker.orderId]; require(traded > 0 && traded <= makerAmount && traded <= takerAmount, "trade amount error."); takerGet = traded; takerGive = (maker.amountGet * takerGet) / maker.amountGive; userOrders[taker.user][taker.orderId] = userOrders[taker.user][taker.orderId] + takerGet; userOrders[maker.user][maker.orderId] = userOrders[maker.user][maker.orderId] + takerGet; } return (takerGet, takerGive); } /** * @dev do exact settlement on chain. * @param maker maker's order info * @param taker taker's order info * @param takerGet the amount of token that taker get * @param takerGive the amount of token that taker give **/ function doSettle(Order maker, Order taker, uint256 takerGet, uint256 takerGive) internal { //charge fees userTokens[msg.sender][maker.tokenGet] = userTokens[msg.sender][maker.tokenGet] + maker.fee; userTokens[msg.sender][taker.tokenGet] = userTokens[msg.sender][taker.tokenGet] + taker.fee; //change balance userTokens[taker.user][taker.tokenGive] = userTokens[taker.user][taker.tokenGive] - takerGive; userTokens[taker.user][taker.tokenGet] = userTokens[taker.user][taker.tokenGet] + takerGet - taker.fee; userTokens[maker.user][maker.tokenGive] = userTokens[maker.user][maker.tokenGive] - takerGet; userTokens[maker.user][maker.tokenGet] = userTokens[maker.user][maker.tokenGet] + takerGive - maker.fee; } /** * @dev cancel the order by user. * @param _tokenGet tokenGet address * @param _amountGet amountGet * @param _tokenGive tokenGive address * @param _amountGive amountGive * @param _base the base token address * @param _salt the salt number of the order **/ function cancelOrder(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, address _base, uint256 _salt) public returns (bool){ bytes32 orderId = generateOrderId(_tokenGet, _amountGet, _tokenGive, _amountGive, _base, _salt); canceledOrders[msg.sender][orderId] = true; emit OrderCancel(msg.sender, orderId); return true; } }
match orders and do settlement on chain maker maker's order info taker taker's order info traded trade amount submitted by relayer/match maker and taker orderdo settle
function matchSettle(Order maker, Order taker, uint256 traded) internal { (uint256 takerGet, uint256 takerGive) = doMatch(maker, taker, traded); doSettle(maker, taker, takerGet, takerGive); }
5,409,232
pragma solidity 0.5.17; /* import "./iElasticTokenInterface.sol"; */ import "./iTokenGovernance.sol"; import "../lib/SafeERC20.sol"; contract iElasticToken is iTokenGovernanceToken { // Modifiers modifier onlyGov() { require(msg.sender == gov); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } modifier onlyBanker() { require(msg.sender == banker); _; } modifier onlyMinter() { require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov || msg.sender == banker, "not minter"); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(itokensScalingFactor == 0, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Computes the current max scaling factor */ function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * itokensScalingFactor // this is used to check if itokensScalingFactor will be too high to compute balances when rebasing. return uint256(- 1) / initSupply; } /** * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance. * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter returns (bool) { _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { // increase totalSupply totalSupply = totalSupply.add(amount); // get underlying value uint256 itokenValue = _fragmentToiToken(amount); // increase initSupply initSupply = initSupply.add(itokenValue); // make sure the mint didnt push maxScalingFactor too low require(itokensScalingFactor <= _maxScalingFactor(), "max scaling factor too low"); // add balance _itokenBalances[to] = _itokenBalances[to].add(itokenValue); // add delegates to the minter _moveDelegates(address(0), _delegates[to], itokenValue); emit Mint(to, amount); emit Transfer(address(0), to, amount); } function burn(uint256 amount) external returns (bool) { _burn(msg.sender, amount); return true; } /// @notice Burns `_amount` token in `account`. Must only be called by the IFABank. function burnFrom(address account, uint256 amount) external onlyBanker returns (bool) { // decreased Allowance uint256 allowance = _allowedFragments[account][msg.sender]; uint256 decreasedAllowance = allowance.sub(amount); // approve _allowedFragments[account][msg.sender] = decreasedAllowance; emit Approval(account, msg.sender, decreasedAllowance); // burn _burn(account, amount); return true; } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); // get underlying value uint256 itokenValue = _fragmentToiToken(amount); // sub balance _itokenBalances[account] = _itokenBalances[account].sub(itokenValue); // decrease initSupply initSupply = initSupply.sub(itokenValue); // decrease totalSupply totalSupply = totalSupply.sub(amount); //remove delegates from the account _moveDelegates(_delegates[account], address(0), itokenValue); emit Burn(account, amount); emit Transfer(account, address(0), amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { // underlying balance is stored in itokens, so divide by current scaling factor // note, this means as scaling factor grows, dust will be untransferrable. // minimum transfer value == itokensScalingFactor / 1e24; // get amount in underlying uint256 itokenValue = _fragmentToiToken(value); // sub from balance of sender _itokenBalances[msg.sender] = _itokenBalances[msg.sender].sub(itokenValue); // add to balance of receiver _itokenBalances[to] = _itokenBalances[to].add(itokenValue); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], itokenValue); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) returns (bool) { // decrease allowance _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); // get value in itokens uint256 itokenValue = _fragmentToiToken(value); // sub from from _itokenBalances[from] = _itokenBalances[from].sub(itokenValue); _itokenBalances[to] = _itokenBalances[to].add(itokenValue); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], itokenValue); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _itokenToFragment(_itokenBalances[who]); } /** @notice Currently returns the internal storage amount * @param who The address to query. * @return The underlying balance of the specified address. */ function balanceOfUnderlying(address who) external view returns (uint256) { return _itokenBalances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } // --- Approve by signature --- function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(now <= deadline, "iToken/permit-expired"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); require(owner != address(0), "iToken/invalid-address-0"); require(owner == ecrecover(digest, v, r, s), "iToken/invalid-permit"); _allowedFragments[owner][spender] = value; emit Approval(owner, spender, value); } /* - Governance Functions - */ /** @notice sets the rebaser * @param rebaser_ The address of the rebaser contract to use for authentication. */ function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; rebaser = rebaser_; emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the incentivizer * @param incentivizer_ The address of the rebaser contract to use for authentication. */ function _setIncentivizer(address incentivizer_) external onlyGov { address oldIncentivizer = incentivizer; incentivizer = incentivizer_; emit NewIncentivizer(oldIncentivizer, incentivizer_); } /** @notice sets the banker * @param banker_ The address of the IFABank contract to use for authentication. */ function _setBanker(address banker_) external onlyGov { address oldBanker = banker; banker = banker_; emit NewBanker(oldBanker, banker_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /* - Extras - */ /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external onlyRebaser returns (uint256) { // no change if (indexDelta == 0) { emit Rebase(epoch, itokensScalingFactor, itokensScalingFactor); return totalSupply; } // for events uint256 previTokensScalingFactor = itokensScalingFactor; if (!positive) { // negative rebase, decrease scaling factor itokensScalingFactor = itokensScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); } else { // positive reabse, increase scaling factor uint256 newScalingFactor = itokensScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { itokensScalingFactor = newScalingFactor; } else { itokensScalingFactor = _maxScalingFactor(); } } // update total supply, correctly totalSupply = _itokenToFragment(initSupply); emit Rebase(epoch, previTokensScalingFactor, itokensScalingFactor); return totalSupply; } function itokenToFragment(uint256 itoken) external view returns (uint256) { return _itokenToFragment(itoken); } function fragmentToiToken(uint256 value) external view returns (uint256) { return _fragmentToiToken(value); } function _itokenToFragment(uint256 itoken) internal view returns (uint256) { return itoken.mul(itokensScalingFactor).div(internalDecimals); } function _fragmentToiToken(uint256 value) internal view returns (uint256) { return value.mul(internalDecimals).div(itokensScalingFactor); } // Rescue tokens function rescueTokens( address token, address to, uint256 amount ) external onlyGov returns (bool) { // transfer to SafeERC20.safeTransfer(IERC20(token), to, amount); return true; } } contract iToken is iElasticToken { /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initTotalSupply_ ) public { super.initialize(name_, symbol_, decimals_); itokensScalingFactor = BASE; initSupply = _fragmentToiToken(initTotalSupply_); totalSupply = initTotalSupply_; _itokenBalances[initial_owner] = initSupply; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); } }
get underlying value sub balance decrease initSupply decrease totalSupplyremove delegates from the account
function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); uint256 itokenValue = _fragmentToiToken(amount); _itokenBalances[account] = _itokenBalances[account].sub(itokenValue); initSupply = initSupply.sub(itokenValue); totalSupply = totalSupply.sub(amount); _moveDelegates(_delegates[account], address(0), itokenValue); emit Burn(account, amount); emit Transfer(account, address(0), amount); }
6,403,351
/** *Submitted for verification at Etherscan.io on 2021-11-10 */ pragma solidity 0.6.7; abstract contract StructLike { function val(uint256 _id) virtual public view returns (uint256); } /** * @title LinkedList (Structured Link List) * @author Vittorio Minacori (https://github.com/vittominacori) * @dev A utility library for using sorted linked list data structures in your Solidity project. */ library LinkedList { uint256 private constant NULL = 0; uint256 private constant HEAD = 0; bool private constant PREV = false; bool private constant NEXT = true; struct List { mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function isList(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function isNode(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function range(List storage self) internal view returns (uint256) { uint256 i; uint256 num; (, i) = adj(self, HEAD, NEXT); while (i != HEAD) { (, i) = adj(self, i, NEXT); num++; } return num; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function node(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!isNode(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][PREV], self.list[_node][NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function adj(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!isNode(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function next(List storage self, uint256 _node) internal view returns (bool, uint256) { return adj(self, _node, NEXT); } /** * @dev Returns the link of a node `_node` in direction `PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function prev(List storage self, uint256 _node) internal view returns (bool, uint256) { return adj(self, _node, PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `back` or `face` basing on your list order. * @dev If you want to order basing on other than `structure.val()` override this function * @param self stored linked list from contract * @param _struct the structure instance * @param _val value to seek * @return uint256 next node with a value less than StructLike(_struct).val(next_) */ function sort(List storage self, address _struct, uint256 _val) internal view returns (uint256) { if (range(self) == 0) { return 0; } bool exists; uint256 next_; (exists, next_) = adj(self, HEAD, NEXT); while ((next_ != 0) && ((_val < StructLike(_struct).val(next_)) != NEXT)) { next_ = self.list[next_][NEXT]; } return next_; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node first node for linking * @param _link node to link to in the _direction */ function form(List storage self, uint256 _node, uint256 _link, bool _dir) internal { self.list[_link][!_dir] = _node; self.list[_node][_dir] = _link; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function insert(List storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if (!isNode(self, _new) && isNode(self, _node)) { uint256 c = self.list[_node][_direction]; form(self, _node, _new, _direction); form(self, _new, c, _direction); return true; } else { return false; } } /** * @dev Insert node `_new` beside existing node `_node` in direction `NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function face(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return insert(self, _node, _new, NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function back(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return insert(self, _node, _new, PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function del(List storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!isNode(self, _node))) { return 0; } form(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; return _node; } /** * @dev Pushes an entry to the head or tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (NEXT) or tail (PREV) * @return bool true if success, false otherwise */ function push(List storage self, uint256 _node, bool _direction) internal returns (bool) { return insert(self, HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (NEXT) or the tail (PREV) * @return uint256 the removed node */ function pop(List storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj_; (exists, adj_) = adj(self, HEAD, _direction); return del(self, adj_); } } abstract contract RewardAdjusterLike { function recomputeRewards(address, bytes4) external virtual; } contract RewardAdjusterBundler { using LinkedList for LinkedList.List; // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "RewardAdjusterBundler/account-not-authorized"); _; } // --- Variables --- // Number of funded functions ever added uint256 public fundedFunctionNonce; // Max number of functions that can be in the list uint256 public maxFunctions; // Latest funded function index in the list uint256 public latestFundedFunction; // Mapping with functions that were already added mapping(address => mapping(bytes4 => uint256)) public addedFunction; // Data about each funded function mapping(uint256 => FundedFunction) public fundedFunctions; // Linked list with functions offering rewards to be called LinkedList.List internal fundedFunctionsList; // The fixed reward adjuster RewardAdjusterLike public fixedRewardAdjuster; // The min + max reward adjuster RewardAdjusterLike public minMaxRewardAdjuster; // --- Structs --- struct FundedFunction { uint256 adjusterType; bytes4 functionName; address receiverContract; } // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event FailedRecomputeReward(uint256 adjusterType, address receiverContract, bytes4 functionName); event AddFundedFunction( uint256 latestFundedFunction, uint256 adjusterType, bytes4 functionName, address receiverContract ); event RemoveFundedFunction(uint256 functionPosition); event ModifyParameters(bytes32 parameter, address val); event ModifyParameters(bytes32 actionType, uint256 functionPosition, uint256 adjusterType, bytes4 functionName, address receiverContract); constructor(address _fixedRewardAdjuster, address _minMaxRewardAdjuster, uint256 _maxFunctions) public { require(_maxFunctions > 0, "RewardAdjusterBundler/null-max-functions"); require(_fixedRewardAdjuster != address(0), "RewardAdjusterBundler/null-fixed-reward-adjuster"); require(_minMaxRewardAdjuster != address(0), "RewardAdjusterBundler/null-minmax-reward-adjuster"); authorizedAccounts[msg.sender] = 1; maxFunctions = _maxFunctions; fixedRewardAdjuster = RewardAdjusterLike(_fixedRewardAdjuster); minMaxRewardAdjuster = RewardAdjusterLike(_minMaxRewardAdjuster); emit AddAuthorization(msg.sender); } // --- Boolean Logic --- function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- Math --- function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; require(z >= x, "RewardAdjusterBundler/add-uint-uint-overflow"); } function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "RewardAdjusterBundler/sub-uint-uint-underflow"); } // --- Administration --- /* * @notice Modify address params * @param parameter The name of the parameter to update * @param val The new address for the parameter */ function modifyParameters(bytes32 parameter, address val) external isAuthorized { require(val != address(0), "RewardAdjusterBundler/null-val"); if (parameter == "fixedRewardAdjuster") { fixedRewardAdjuster = RewardAdjusterLike(val); } else if (parameter == "minMaxRewardAdjuster") { minMaxRewardAdjuster = RewardAdjusterLike(val); } else revert("RewardAdjusterBundler/modify-unrecognized-param"); emit ModifyParameters(parameter, val); } /* * @notice Add or remove a funded function * @param actionType The type of action to execute * @param functionPosition The position of the funded function in fundedFunctions * @param adjusterType The adjuster contract to include for the funded function * @param functionName The signature of the function that gets funded * @param receiverContract The contract hosting the funded function */ function modifyParameters(bytes32 actionType, uint256 functionPosition, uint256 adjusterType, bytes4 functionName, address receiverContract) external isAuthorized { if (actionType == "addFunction") { addFundedFunction(adjusterType, functionName, receiverContract); } else if (actionType == "removeFunction") { removeFundedFunction(functionPosition); } else revert("RewardAdjusterBundler/modify-unrecognized-param"); emit ModifyParameters(actionType, functionPosition, adjusterType, functionName, receiverContract); } // --- Internal Logic --- /* * @notice Add a funded function * @param adjusterType The type of adjuster that recomputes the rewards offered by this function * @param functionName The name of the function offering rewards * @param receiverContract Contract that has the funded function */ function addFundedFunction(uint256 adjusterType, bytes4 functionName, address receiverContract) internal { require(receiverContract != address(0), "RewardAdjusterBundler/null-receiver-contract"); require(adjusterType <= 1, "RewardAdjusterBundler/invalid-adjuster-type"); require(addedFunction[receiverContract][functionName] == 0, "RewardAdjusterBundler/function-already-added"); require(fundedFunctionsAmount() < maxFunctions, "RewardAdjusterBundler/function-limit-reached"); addedFunction[receiverContract][functionName] = 1; fundedFunctionNonce = addition(fundedFunctionNonce, 1); latestFundedFunction = fundedFunctionNonce; fundedFunctions[fundedFunctionNonce] = FundedFunction(adjusterType, functionName, receiverContract); fundedFunctionsList.push(latestFundedFunction, false); emit AddFundedFunction( latestFundedFunction, adjusterType, functionName, receiverContract ); } /* * @notice Remove a funded function * @param functionPosition The position of the funded function in fundedFunctions */ function removeFundedFunction(uint256 functionPosition) internal { require(both(functionPosition <= latestFundedFunction, functionPosition > 0), "RewardAdjusterBundler/invalid-position"); FundedFunction memory fundedFunction = fundedFunctions[functionPosition]; require(addedFunction[fundedFunction.receiverContract][fundedFunction.functionName] == 1, "RewardAdjusterBundler/function-not-added"); delete(addedFunction[fundedFunction.receiverContract][fundedFunction.functionName]); if (functionPosition == latestFundedFunction) { (, uint256 prevReceiver) = fundedFunctionsList.prev(latestFundedFunction); latestFundedFunction = prevReceiver; } fundedFunctionsList.del(functionPosition); delete(fundedFunctions[functionPosition]); emit RemoveFundedFunction(functionPosition); } // --- Core Logic --- /* * @param Recopute all system coin rewards for all funded functions included in this contract */ function recomputeAllRewards() external { // Start looping from the latest funded function uint256 currentFundedFunction = latestFundedFunction; FundedFunction memory fundedFunction; // While we still haven't gone through the entire list while (currentFundedFunction > 0) { fundedFunction = fundedFunctions[currentFundedFunction]; if (fundedFunction.adjusterType == 0) { try fixedRewardAdjuster.recomputeRewards(fundedFunction.receiverContract, fundedFunction.functionName) {} catch(bytes memory /* revertReason */) { emit FailedRecomputeReward(fundedFunction.adjusterType, fundedFunction.receiverContract, fundedFunction.functionName); } } else { try minMaxRewardAdjuster.recomputeRewards(fundedFunction.receiverContract, fundedFunction.functionName) {} catch(bytes memory /* revertReason */) { emit FailedRecomputeReward(fundedFunction.adjusterType, fundedFunction.receiverContract, fundedFunction.functionName); } } // Continue looping (, currentFundedFunction) = fundedFunctionsList.prev(currentFundedFunction); } } // --- Getters --- /** * @notice Get the secondary tax receiver list length */ function fundedFunctionsAmount() public view returns (uint256) { return fundedFunctionsList.range(); } /** * @notice Check if a funded function index is in the list */ function isFundedFunction(uint256 _fundedFunction) public view returns (bool) { if (_fundedFunction == 0) return false; return fundedFunctionsList.isNode(_fundedFunction); } }
--- Getters --- Get the secondary tax receiver list length/
function fundedFunctionsAmount() public view returns (uint256) { return fundedFunctionsList.range(); }
6,800,035
./full_match/5/0x1cD3522515BA87e190fDa01A636e7F6D59601fFF/sources/contracts/ETH/PresaleV1.sol
To remove users from whitelist which restricts users from claiming if claimWhitelistStatus is true _userToRemoveFromWhitelist addresses of the users/
function removeFromWhitelist( address[] calldata _userToRemoveFromWhitelist ) external onlyOwner { for (uint256 i = 0; i < _userToRemoveFromWhitelist.length; i++) { isWhitelisted[_userToRemoveFromWhitelist[i]] = false; } }
1,932,323
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/utils/SafeERC20.sol"; import "./OwnableInitializable.sol"; import "./MathUtils.sol"; import "./ITokenLock.sol"; // this contract is based on GraphTokenLock // see https://github.com/graphprotocol/token-distribution/blob/main/contracts/GraphTokenLock.sol /** * @title HatTokenLock * @notice Contract that manages an unlocking schedule of tokens. * @dev The contract lock manage a number of tokens deposited into the contract to ensure that * they can only be released under certain time conditions. * * This contract implements a release scheduled based on periods and tokens are released in steps * after each period ends. It can be configured with one period in which case it is like a plain TimeLock. * It also supports revocation to be used for vesting schedules. * * The contract supports receiving extra funds than the managed tokens ones that can be * withdrawn by the beneficiary at any time. * * A releaseStartTime parameter is included to override the default release schedule and * perform the first release on the configured time. After that it will continue with the * default schedule. */ // solhint-disable-next-line indent abstract contract TokenLock is OwnableInitializable, ITokenLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant MIN_PERIOD = 1; // -- State -- IERC20 public token; address public beneficiary; // Configuration // Amount of tokens managed by the contract schedule uint256 public managedAmount; uint256 public startTime; // Start datetime (in unixtimestamp) uint256 public endTime; // Datetime after all funds are fully vested/unlocked (in unixtimestamp) uint256 public periods; // Number of vesting/release periods // First release date for tokens (in unixtimestamp) // If set, no tokens will be released before releaseStartTime ignoring // the amount to release each period uint256 public releaseStartTime; // A cliff set a date to which a beneficiary needs to get to vest // all preceding periods uint256 public vestingCliffTime; Revocability public revocable; // Whether to use vesting for locked funds // State bool public isRevoked; bool public isInitialized; bool public isAccepted; uint256 public releasedAmount; // -- Events -- event TokensReleased(address indexed beneficiary, uint256 amount); event TokensWithdrawn(address indexed beneficiary, uint256 amount); event TokensRevoked(address indexed beneficiary, uint256 amount); event BeneficiaryChanged(address newBeneficiary); event LockAccepted(); event LockCanceled(); /** * @dev Only allow calls from the beneficiary of the contract */ modifier onlyBeneficiary() { require(msg.sender == beneficiary, "!auth"); _; } /** * @notice Initializes the contract * @param _tokenLockOwner Address of the contract owner * @param _beneficiary Address of the beneficiary of locked tokens * @param _managedAmount Amount of tokens to be managed by the lock contract * @param _startTime Start time of the release schedule * @param _endTime End time of the release schedule * @param _periods Number of periods between start time and end time * @param _releaseStartTime Override time for when the releases start * @param _vestingCliffTime Override time for when the vesting start * @param _revocable Whether the contract is revocable */ function _initialize( address _tokenLockOwner, address _beneficiary, address _token, uint256 _managedAmount, uint256 _startTime, uint256 _endTime, uint256 _periods, uint256 _releaseStartTime, uint256 _vestingCliffTime, Revocability _revocable ) internal { require(!isInitialized, "Already initialized"); require(_tokenLockOwner != address(0), "Owner cannot be zero"); require(_beneficiary != address(0), "Beneficiary cannot be zero"); require(_token != address(0), "Token cannot be zero"); require(_managedAmount > 0, "Managed tokens cannot be zero"); require(_startTime != 0, "Start time must be set"); require(_startTime < _endTime, "Start time > end time"); require(_periods >= MIN_PERIOD, "Periods cannot be below minimum"); require(_revocable != Revocability.NotSet, "Must set a revocability option"); require(_releaseStartTime < _endTime, "Release start time must be before end time"); require(_vestingCliffTime < _endTime, "Cliff time must be before end time"); isInitialized = true; OwnableInitializable.initialize(_tokenLockOwner); beneficiary = _beneficiary; token = IERC20(_token); managedAmount = _managedAmount; startTime = _startTime; endTime = _endTime; periods = _periods; // Optionals releaseStartTime = _releaseStartTime; vestingCliffTime = _vestingCliffTime; revocable = _revocable; } /** * @notice Change the beneficiary of funds managed by the contract * @dev Can only be called by the beneficiary * @param _newBeneficiary Address of the new beneficiary address */ function changeBeneficiary(address _newBeneficiary) external onlyBeneficiary { require(_newBeneficiary != address(0), "Empty beneficiary"); beneficiary = _newBeneficiary; emit BeneficiaryChanged(_newBeneficiary); } /** * @notice Beneficiary accepts the lock, the owner cannot retrieve back the tokens * @dev Can only be called by the beneficiary */ function acceptLock() external onlyBeneficiary { isAccepted = true; emit LockAccepted(); } /** * @notice Owner cancel the lock and return the balance in the contract * @dev Can only be called by the owner */ function cancelLock() external onlyOwner { require(isAccepted == false, "Cannot cancel accepted contract"); token.safeTransfer(owner(), currentBalance()); emit LockCanceled(); } // -- Balances -- /** * @notice Returns the amount of tokens currently held by the contract * @return Tokens held in the contract */ function currentBalance() public override view returns (uint256) { return token.balanceOf(address(this)); } // -- Time & Periods -- /** * @notice Returns the current block timestamp * @return Current block timestamp */ function currentTime() public override view returns (uint256) { // solhint-disable-next-line not-rely-on-time return block.timestamp; } /** * @notice Gets duration of contract from start to end in seconds * @return Amount of seconds from contract startTime to endTime */ function duration() public override view returns (uint256) { return endTime.sub(startTime); } /** * @notice Gets time elapsed since the start of the contract * @dev Returns zero if called before conctract starTime * @return Seconds elapsed from contract startTime */ function sinceStartTime() public override view returns (uint256) { uint256 current = currentTime(); if (current <= startTime) { return 0; } return current.sub(startTime); } /** * @notice Returns amount available to be released after each period according to schedule * @return Amount of tokens available after each period */ function amountPerPeriod() public override view returns (uint256) { return managedAmount.div(periods); } /** * @notice Returns the duration of each period in seconds * @return Duration of each period in seconds */ function periodDuration() public override view returns (uint256) { return duration().div(periods); } /** * @notice Gets the current period based on the schedule * @return A number that represents the current period */ function currentPeriod() public override view returns (uint256) { return sinceStartTime().div(periodDuration()).add(MIN_PERIOD); } /** * @notice Gets the number of periods that passed since the first period * @return A number of periods that passed since the schedule started */ function passedPeriods() public override view returns (uint256) { return currentPeriod().sub(MIN_PERIOD); } // -- Locking & Release Schedule -- /** * @notice Gets the currently available token according to the schedule * @dev Implements the step-by-step schedule based on periods for available tokens * @return Amount of tokens available according to the schedule */ function availableAmount() public override view returns (uint256) { uint256 current = currentTime(); // Before contract start no funds are available if (current < startTime) { return 0; } // After contract ended all funds are available if (current > endTime) { return managedAmount; } // Get available amount based on period return passedPeriods().mul(amountPerPeriod()); } /** * @notice Gets the amount of currently vested tokens * @dev Similar to available amount, but is fully vested when contract is non-revocable * @return Amount of tokens already vested */ function vestedAmount() public override view returns (uint256) { // If non-revocable it is fully vested if (revocable == Revocability.Disabled) { return managedAmount; } // Vesting cliff is activated and it has not passed means nothing is vested yet if (vestingCliffTime > 0 && currentTime() < vestingCliffTime) { return 0; } return availableAmount(); } /** * @notice Gets tokens currently available for release * @dev Considers the schedule and takes into account already released tokens * @return Amount of tokens ready to be released */ function releasableAmount() public override view returns (uint256) { // If a release start time is set no tokens are available for release before this date // If not set it follows the default schedule and tokens are available on // the first period passed if (releaseStartTime > 0 && currentTime() < releaseStartTime) { return 0; } // Vesting cliff is activated and it has not passed means nothing is vested yet // so funds cannot be released if (revocable == Revocability.Enabled && vestingCliffTime > 0 && currentTime() < vestingCliffTime) { return 0; } // A beneficiary can never have more releasable tokens than the contract balance uint256 releasable = availableAmount().sub(releasedAmount); return MathUtils.min(currentBalance(), releasable); } /** * @notice Gets the outstanding amount yet to be released based on the whole contract lifetime * @dev Does not consider schedule but just global amounts tracked * @return Amount of outstanding tokens for the lifetime of the contract */ function totalOutstandingAmount() public override view returns (uint256) { return managedAmount.sub(releasedAmount); } /** * @notice Gets surplus amount in the contract based on outstanding amount to release * @dev All funds over outstanding amount is considered surplus that can be withdrawn by beneficiary * @return Amount of tokens considered as surplus */ function surplusAmount() public override view returns (uint256) { uint256 balance = currentBalance(); uint256 outstandingAmount = totalOutstandingAmount(); if (balance > outstandingAmount) { return balance.sub(outstandingAmount); } return 0; } // -- Value Transfer -- /** * @notice Releases tokens based on the configured schedule * @dev All available releasable tokens are transferred to beneficiary */ function release() external override onlyBeneficiary { uint256 amountToRelease = releasableAmount(); require(amountToRelease > 0, "No available releasable amount"); releasedAmount = releasedAmount.add(amountToRelease); token.safeTransfer(beneficiary, amountToRelease); emit TokensReleased(beneficiary, amountToRelease); } /** * @notice Withdraws surplus, unmanaged tokens from the contract * @dev Tokens in the contract over outstanding amount are considered as surplus * @param _amount Amount of tokens to withdraw */ function withdrawSurplus(uint256 _amount) external override onlyBeneficiary { require(_amount > 0, "Amount cannot be zero"); require(surplusAmount() >= _amount, "Amount requested > surplus available"); token.safeTransfer(beneficiary, _amount); emit TokensWithdrawn(beneficiary, _amount); } /** * @notice Revokes a vesting schedule and return the unvested tokens to the owner * @dev Vesting schedule is always calculated based on managed tokens */ function revoke() external override onlyOwner { require(revocable == Revocability.Enabled, "Contract is non-revocable"); require(isRevoked == false, "Already revoked"); uint256 unvestedAmount = managedAmount.sub(vestedAmount()); require(unvestedAmount > 0, "No available unvested amount"); isRevoked = true; token.safeTransfer(owner(), unvestedAmount); emit TokensRevoked(beneficiary, unvestedAmount); } }
Change the beneficiary of funds managed by the contract Can only be called by the beneficiary _newBeneficiary Address of the new beneficiary address/
function changeBeneficiary(address _newBeneficiary) external onlyBeneficiary { require(_newBeneficiary != address(0), "Empty beneficiary"); beneficiary = _newBeneficiary; emit BeneficiaryChanged(_newBeneficiary); }
1,768,268
./full_match/1/0xa108DCCae3399973c2b129aE3927832CBbA6570B/sources/browser/STYK1.sol
To Claim Monthly Rewards
function claimMonthlyRewards() external { address _customerAddress = msg.sender; require(_calculateMonthlyRewards(_customerAddress) > 0 ,"ERR_YOU_DONT_QUALIFY"); uint256 daysPayout = safeSub(getDaysInMonth(getMonth(now), getYear(now)),1); require( (getDay(now) == daysPayout || getDay(now) == getDaysInMonth(getMonth(now), getYear(now))), "ERR_CANNOT_CLAIM_BEFORE_PAYOUT" ); require(!monthlyRewardsClaimed[_customerAddress][getYear(now)][getMonth(now)],"ERR_REWARD_ALREADY_CLAIMED"); if (_calculateTokenPercentage(_customerAddress) != 0) { totalMonthRewards[_customerAddress] = safeAdd( totalMonthRewards[_customerAddress], _calculateMonthlyRewards(_customerAddress) ); monthlyRewardsClaimed[_customerAddress][getYear(now)][getMonth(now)] = true; } }
8,360,385
pragma solidity ^0.4.25; /** * * World War Goo - Competitive Idle Game * * https://ethergoo.io * */ contract Units { GooToken constant goo = GooToken(0xdf0960778c6e6597f197ed9a25f12f5d971da86c); Army army = Army(0x0); Clans clans = Clans(0x0); Factories constant factories = Factories(0xc81068cd335889736fc485592e4d73a82403d44b); mapping(address => mapping(uint256 => UnitsOwned)) public unitsOwned; mapping(address => mapping(uint256 => UnitExperience)) public unitExp; mapping(address => mapping(uint256 => uint256)) private unitMaxCap; mapping(address => mapping(uint256 => UnitUpgrades)) private unitUpgrades; mapping(address => mapping(uint256 => UpgradesOwned)) public upgradesOwned; // For each unitId, which upgrades owned (3 columns of uint64) mapping(uint256 => Unit) public unitList; mapping(uint256 => Upgrade) public upgradeList; mapping(address => bool) operator; address owner; constructor() public { owner = msg.sender; } struct UnitsOwned { uint80 units; uint8 factoryBuiltFlag; // Incase user sells units, we still want to keep factory } struct UnitExperience { uint224 experience; uint32 level; } struct UnitUpgrades { uint32 prodIncrease; uint32 prodMultiplier; uint32 attackIncrease; uint32 attackMultiplier; uint32 defenseIncrease; uint32 defenseMultiplier; uint32 lootingIncrease; uint32 lootingMultiplier; } struct UpgradesOwned { uint64 column0; uint64 column1; uint64 column2; } // Unit & Upgrade data: struct Unit { uint256 unitId; uint224 gooCost; uint256 baseProduction; uint80 attack; uint80 defense; uint80 looting; } struct Upgrade { uint256 upgradeId; uint224 gooCost; uint256 unitId; uint256 column; // Columns of upgrades (1st & 2nd are unit specific, then 3rd is capacity) uint256 prerequisiteUpgrade; uint256 unitMaxCapacityGain; uint32 prodIncrease; uint32 prodMultiplier; uint32 attackIncrease; uint32 attackMultiplier; uint32 defenseIncrease; uint32 defenseMultiplier; uint32 lootingIncrease; uint32 lootingMultiplier; } function setArmy(address armyContract) external { require(msg.sender == owner); army = Army(armyContract); } function setClans(address clansContract) external { require(msg.sender == owner); clans = Clans(clansContract); } function setOperator(address gameContract, bool isOperator) external { require(msg.sender == owner); operator[gameContract] = isOperator; } function mintUnitExternal(uint256 unit, uint80 amount, address player, uint8 chosenPosition) external { require(operator[msg.sender]); mintUnit(unit, amount, player, chosenPosition); } function mintUnit(uint256 unit, uint80 amount, address player, uint8 chosenPosition) internal { UnitsOwned storage existingUnits = unitsOwned[player][unit]; if (existingUnits.factoryBuiltFlag == 0) { // Edge case to create factory for player (on empty tile) where it is their first unit uint256[] memory existingFactories = factories.getFactories(player); uint256 length = existingFactories.length; // Provided position is not valid so find valid factory position if (chosenPosition >= factories.MAX_SIZE() || (chosenPosition < length && existingFactories[chosenPosition] > 0)) { chosenPosition = 0; while (chosenPosition < length && existingFactories[chosenPosition] > 0) { chosenPosition++; } } factories.addFactory(player, chosenPosition, unit); unitsOwned[player][unit] = UnitsOwned(amount, 1); // 1 = Flag to say factory exists } else { existingUnits.units += amount; } (uint80 attackStats, uint80 defenseStats, uint80 lootingStats) = getUnitsCurrentBattleStats(player, unit); if (attackStats > 0 || defenseStats > 0 || lootingStats > 0) { army.increasePlayersArmyPowerTrio(player, attackStats * amount, defenseStats * amount, lootingStats * amount); } else { uint256 prodIncrease = getUnitsCurrentProduction(player, unit) * amount; goo.increasePlayersGooProduction(player, prodIncrease / 100); } } function deleteUnitExternal(uint80 amount, uint256 unit, address player) external { require(operator[msg.sender]); deleteUnit(amount, unit, player); } function deleteUnit(uint80 amount, uint256 unit, address player) internal { (uint80 attackStats, uint80 defenseStats, uint80 lootingStats) = getUnitsCurrentBattleStats(player, unit); if (attackStats > 0 || defenseStats > 0 || lootingStats > 0) { army.decreasePlayersArmyPowerTrio(player, attackStats * amount, defenseStats * amount, lootingStats * amount); } else { uint256 prodDecrease = getUnitsCurrentProduction(player, unit) * amount; goo.decreasePlayersGooProduction(player, prodDecrease / 100); } unitsOwned[player][unit].units -= amount; } function getUnitsCurrentBattleStats(address player, uint256 unitId) internal view returns (uint80 attack, uint80 defense, uint80 looting) { Unit memory unit = unitList[unitId]; UnitUpgrades memory existingUpgrades = unitUpgrades[player][unitId]; attack = (unit.attack + existingUpgrades.attackIncrease) * (100 + existingUpgrades.attackMultiplier); defense = (unit.defense + existingUpgrades.defenseIncrease) * (100 + existingUpgrades.defenseMultiplier); looting = (unit.looting + existingUpgrades.lootingIncrease) * (100 + existingUpgrades.lootingMultiplier); } function getUnitsCurrentProduction(address player, uint256 unitId) public view returns (uint256) { UnitUpgrades memory existingUpgrades = unitUpgrades[player][unitId]; return (unitList[unitId].baseProduction + existingUpgrades.prodIncrease) * (100 + existingUpgrades.prodMultiplier); } function buyUnit(uint256 unitId, uint80 amount, uint8 position) external { uint224 gooCost = SafeMath224.mul(unitList[unitId].gooCost, amount); require(gooCost > 0); // Valid unit uint80 newTotal = unitsOwned[msg.sender][unitId].units + amount; if (newTotal > 99) { require(newTotal < 99 + unitMaxCap[msg.sender][unitId]); } // Clan discount uint224 unitDiscount = clans.getPlayersClanUpgrade(msg.sender, 1); // class 1 = unit discount uint224 reducedGooCost = gooCost - ((gooCost * unitDiscount) / 100); uint224 seventyFivePercentRefund = (gooCost * 3) / 4; // Update players goo goo.updatePlayersGooFromPurchase(msg.sender, reducedGooCost); goo.mintGoo(seventyFivePercentRefund, this); // 75% refund is stored (in this contract) for when player sells unit army.depositSpentGoo(reducedGooCost - seventyFivePercentRefund); // Upto 25% Goo spent goes to divs (Remaining is discount + 75% player gets back when selling unit) mintUnit(unitId, amount, msg.sender, position); } function sellUnit(uint256 unitId, uint80 amount) external { require(unitsOwned[msg.sender][unitId].units >= amount && amount > 0); uint224 gooCost = unitList[unitId].gooCost; require(gooCost > 0); goo.updatePlayersGoo(msg.sender); deleteUnit(amount, unitId, msg.sender); goo.transfer(msg.sender, (gooCost * amount * 3) / 4); // Refund 75% } function grantArmyExp(address player, uint256 unitId, uint224 amount) external returns(bool) { require(operator[msg.sender]); UnitExperience memory existingExp = unitExp[player][unitId]; uint224 expRequirement = (existingExp.level + 1) * 80; // Lvl 1: 80; Lvl 2: 160, Lvl 3: 240 (480 in total) etc. if (existingExp.experience + amount >= expRequirement) { existingExp.experience = (existingExp.experience + amount) - expRequirement; existingExp.level++; unitExp[player][unitId] = existingExp; // Grant buff to unit (5% additive multiplier) UnitUpgrades memory existingUpgrades = unitUpgrades[player][unitId]; existingUpgrades.attackMultiplier += 5; existingUpgrades.defenseMultiplier += 5; existingUpgrades.lootingMultiplier += 5; unitUpgrades[player][unitId] = existingUpgrades; // Increase player's army power uint80 multiplierGain = unitsOwned[player][unitId].units * 5; Unit memory unit = unitList[unitId]; uint80 attackGain = multiplierGain * (unit.attack + existingUpgrades.attackIncrease); uint80 defenseGain = multiplierGain * (unit.defense + existingUpgrades.defenseIncrease); uint80 lootingGain = multiplierGain * (unit.looting + existingUpgrades.lootingIncrease); army.increasePlayersArmyPowerTrio(player, attackGain, defenseGain, lootingGain); return true; } else { unitExp[player][unitId].experience += amount; return false; } } function increaseUnitCapacity(address player, uint256 upgradeGain, uint256 unitId) external { require(operator[msg.sender]); unitMaxCap[player][unitId] += upgradeGain; } function decreaseUnitCapacity(address player, uint256 upgradeGain, uint256 unitId) external { require(operator[msg.sender]); unitMaxCap[player][unitId] -= upgradeGain; } function increaseUpgradesExternal(address player, uint256 unitId, uint32 prodIncrease, uint32 prodMultiplier, uint32 attackIncrease, uint32 attackMultiplier, uint32 defenseIncrease, uint32 defenseMultiplier, uint32 lootingIncrease, uint32 lootingMultiplier) external { require(operator[msg.sender]); Upgrade memory upgrade = Upgrade(0,0,0,0,0,0, prodIncrease, prodMultiplier, attackIncrease, attackMultiplier, defenseIncrease, defenseMultiplier, lootingIncrease, lootingMultiplier); increaseUpgrades(player, upgrade, unitId); } function increaseUpgrades(address player, Upgrade upgrade, uint256 unitId) internal { uint80 units = unitsOwned[player][unitId].units; UnitUpgrades memory existingUpgrades = unitUpgrades[player][unitId]; Unit memory unit = unitList[unitId]; if (unit.baseProduction > 0) { // Increase goo production uint256 prodGain = units * upgrade.prodMultiplier * (unit.baseProduction + existingUpgrades.prodIncrease); // Multiplier gains prodGain += units * upgrade.prodIncrease * (100 + existingUpgrades.prodMultiplier); // Base prod gains goo.updatePlayersGoo(player); goo.increasePlayersGooProduction(player, prodGain / 100); } else { // Increase army power uint80 attackGain = units * upgrade.attackMultiplier * (unit.attack + existingUpgrades.attackIncrease); // Multiplier gains uint80 defenseGain = units * upgrade.defenseMultiplier * (unit.defense + existingUpgrades.defenseIncrease); // Multiplier gains uint80 lootingGain = units * upgrade.lootingMultiplier * (unit.looting + existingUpgrades.lootingIncrease); // Multiplier gains attackGain += units * upgrade.attackIncrease * (100 + existingUpgrades.attackMultiplier); // + Base gains defenseGain += units * upgrade.defenseIncrease * (100 + existingUpgrades.defenseMultiplier); // + Base gains lootingGain += units * upgrade.lootingIncrease * (100 + existingUpgrades.lootingMultiplier); // + Base gains army.increasePlayersArmyPowerTrio(player, attackGain, defenseGain, lootingGain); } existingUpgrades.prodIncrease += upgrade.prodIncrease; existingUpgrades.prodMultiplier += upgrade.prodMultiplier; existingUpgrades.attackIncrease += upgrade.attackIncrease; existingUpgrades.attackMultiplier += upgrade.attackMultiplier; existingUpgrades.defenseIncrease += upgrade.defenseIncrease; existingUpgrades.defenseMultiplier += upgrade.defenseMultiplier; existingUpgrades.lootingIncrease += upgrade.lootingIncrease; existingUpgrades.lootingMultiplier += upgrade.lootingMultiplier; unitUpgrades[player][unitId] = existingUpgrades; } function decreaseUpgradesExternal(address player, uint256 unitId, uint32 prodIncrease, uint32 prodMultiplier, uint32 attackIncrease, uint32 attackMultiplier, uint32 defenseIncrease, uint32 defenseMultiplier, uint32 lootingIncrease, uint32 lootingMultiplier) external { require(operator[msg.sender]); Upgrade memory upgrade = Upgrade(0,0,0,0,0,0, prodIncrease, prodMultiplier, attackIncrease, attackMultiplier, defenseIncrease, defenseMultiplier, lootingIncrease, lootingMultiplier); decreaseUpgrades(player, upgrade, unitId); } function decreaseUpgrades(address player, Upgrade upgrade, uint256 unitId) internal { uint80 units = unitsOwned[player][unitId].units; UnitUpgrades memory existingUpgrades = unitUpgrades[player][unitId]; Unit memory unit = unitList[unitId]; if (unit.baseProduction > 0) { // Decrease goo production uint256 prodLoss = units * upgrade.prodMultiplier * (unit.baseProduction + existingUpgrades.prodIncrease); // Multiplier losses prodLoss += units * upgrade.prodIncrease * (100 + existingUpgrades.prodMultiplier); // Base prod losses goo.updatePlayersGoo(player); goo.decreasePlayersGooProduction(player, prodLoss / 100); } else { // Decrease army power uint80 attackLoss = units * upgrade.attackMultiplier * (unit.attack + existingUpgrades.attackIncrease); // Multiplier losses uint80 defenseLoss = units * upgrade.defenseMultiplier * (unit.defense + existingUpgrades.defenseIncrease); // Multiplier losses uint80 lootingLoss = units * upgrade.lootingMultiplier * (unit.looting + existingUpgrades.lootingIncrease); // Multiplier losses attackLoss += units * upgrade.attackIncrease * (100 + existingUpgrades.attackMultiplier); // + Base losses defenseLoss += units * upgrade.defenseIncrease * (100 + existingUpgrades.defenseMultiplier); // + Base losses lootingLoss += units * upgrade.lootingIncrease * (100 + existingUpgrades.lootingMultiplier); // + Base losses army.decreasePlayersArmyPowerTrio(player, attackLoss, defenseLoss, lootingLoss); } existingUpgrades.prodIncrease -= upgrade.prodIncrease; existingUpgrades.prodMultiplier -= upgrade.prodMultiplier; existingUpgrades.attackIncrease -= upgrade.attackIncrease; existingUpgrades.attackMultiplier -= upgrade.attackMultiplier; existingUpgrades.defenseIncrease -= upgrade.defenseIncrease; existingUpgrades.defenseMultiplier -= upgrade.defenseMultiplier; existingUpgrades.lootingIncrease -= upgrade.lootingIncrease; existingUpgrades.lootingMultiplier -= upgrade.lootingMultiplier; unitUpgrades[player][unitId] = existingUpgrades; } function swapUpgradesExternal(address player, uint256 unitId, uint32[8] upgradeGains, uint32[8] upgradeLosses) external { require(operator[msg.sender]); UnitUpgrades memory existingUpgrades = unitUpgrades[player][unitId]; Unit memory unit = unitList[unitId]; if (unit.baseProduction > 0) { // Change goo production gooProductionChange(player, unitId, existingUpgrades, unit.baseProduction, upgradeGains, upgradeLosses); } else { // Change army power armyPowerChange(player, existingUpgrades, unit, upgradeGains, upgradeLosses); } } function armyPowerChange(address player, UnitUpgrades existingUpgrades, Unit unit, uint32[8] upgradeGains, uint32[8] upgradeLosses) internal { int256 existingAttack = int256((unit.attack + existingUpgrades.attackIncrease) * (100 + existingUpgrades.attackMultiplier)); int256 existingDefense = int256((unit.defense + existingUpgrades.defenseIncrease) * (100 + existingUpgrades.defenseMultiplier)); int256 existingLooting = int256((unit.looting + existingUpgrades.lootingIncrease) * (100 + existingUpgrades.lootingMultiplier)); existingUpgrades.attackIncrease = uint32(int(existingUpgrades.attackIncrease) + (int32(upgradeGains[2]) - int32(upgradeLosses[2]))); existingUpgrades.attackMultiplier = uint32(int(existingUpgrades.attackMultiplier) + (int32(upgradeGains[3]) - int32(upgradeLosses[3]))); existingUpgrades.defenseIncrease = uint32(int(existingUpgrades.defenseIncrease) + (int32(upgradeGains[4]) - int32(upgradeLosses[4]))); existingUpgrades.defenseMultiplier = uint32(int(existingUpgrades.defenseMultiplier) + (int32(upgradeGains[5]) - int32(upgradeLosses[5]))); existingUpgrades.lootingIncrease = uint32(int(existingUpgrades.lootingIncrease) + (int32(upgradeGains[6]) - int32(upgradeLosses[6]))); existingUpgrades.lootingMultiplier = uint32(int(existingUpgrades.lootingMultiplier) + (int32(upgradeGains[7]) - int32(upgradeLosses[7]))); int256 attackChange = ((int256(unit.attack) + existingUpgrades.attackIncrease) * (100 + existingUpgrades.attackMultiplier)) - existingAttack; int256 defenseChange = ((int256(unit.defense) + existingUpgrades.defenseIncrease) * (100 + existingUpgrades.defenseMultiplier)) - existingDefense; int256 lootingChange = ((int256(unit.looting) + existingUpgrades.lootingIncrease) * (100 + existingUpgrades.lootingMultiplier)) - existingLooting; uint256 unitId = unit.unitId; int256 units = int256(unitsOwned[player][unitId].units); army.changePlayersArmyPowerTrio(player, units * attackChange, units * defenseChange, units * lootingChange); unitUpgrades[player][unitId] = existingUpgrades; } function gooProductionChange(address player, uint256 unitId, UnitUpgrades existingUpgrades, uint256 baseProduction, uint32[8] upgradeGains, uint32[8] upgradeLosses) internal { goo.updatePlayersGoo(player); int256 existingProd = int256((baseProduction + existingUpgrades.prodIncrease) * (100 + existingUpgrades.prodMultiplier)); existingUpgrades.prodIncrease = uint32(int(existingUpgrades.prodIncrease) + (int32(upgradeGains[0]) - int32(upgradeLosses[0]))); existingUpgrades.prodMultiplier = uint32(int(existingUpgrades.prodMultiplier) + (int32(upgradeGains[1]) - int32(upgradeLosses[1]))); int256 prodChange = ((int256(baseProduction) + existingUpgrades.prodIncrease) * (100 + existingUpgrades.prodMultiplier)) - existingProd; if (prodChange > 0) { goo.increasePlayersGooProduction(player, (unitsOwned[player][unitId].units * uint256(prodChange)) / 100); } else { goo.decreasePlayersGooProduction(player, (unitsOwned[player][unitId].units * uint256(-prodChange)) / 100); } unitUpgrades[player][unitId] = existingUpgrades; } function addUnit(uint256 id, uint224 baseGooCost, uint256 baseGooProduction, uint80 baseAttack, uint80 baseDefense, uint80 baseLooting) external { require(operator[msg.sender]); unitList[id] = Unit(id, baseGooCost, baseGooProduction, baseAttack, baseDefense, baseLooting); } function addUpgrade(uint256 id, uint224 gooCost, uint256 unit, uint256 column, uint256 prereq, uint256 unitMaxCapacityGain, uint32[8] upgradeGains) external { require(operator[msg.sender]); upgradeList[id] = Upgrade(id, gooCost, unit, column, prereq, unitMaxCapacityGain, upgradeGains[0], upgradeGains[1], upgradeGains[2], upgradeGains[3], upgradeGains[4], upgradeGains[5], upgradeGains[6], upgradeGains[7]); } function buyUpgrade(uint64 upgradeId) external { Upgrade memory upgrade = upgradeList[upgradeId]; uint256 unitId = upgrade.unitId; UpgradesOwned memory ownedUpgrades = upgradesOwned[msg.sender][unitId]; uint64 latestUpgradeOwnedForColumn; if (upgrade.column == 0) { latestUpgradeOwnedForColumn = ownedUpgrades.column0; ownedUpgrades.column0 = upgradeId; // Update upgradesOwned } else if (upgrade.column == 1) { latestUpgradeOwnedForColumn = ownedUpgrades.column1; ownedUpgrades.column1 = upgradeId; // Update upgradesOwned } else if (upgrade.column == 2) { latestUpgradeOwnedForColumn = ownedUpgrades.column2; ownedUpgrades.column2 = upgradeId; // Update upgradesOwned } upgradesOwned[msg.sender][unitId] = ownedUpgrades; require(unitId > 0); // Valid upgrade require(latestUpgradeOwnedForColumn < upgradeId); // Haven't already purchased require(latestUpgradeOwnedForColumn >= upgrade.prerequisiteUpgrade); // Own prequisite // Clan discount uint224 upgradeDiscount = clans.getPlayersClanUpgrade(msg.sender, 0); // class 0 = upgrade discount uint224 reducedUpgradeCost = upgrade.gooCost - ((upgrade.gooCost * upgradeDiscount) / 100); // Update players goo goo.updatePlayersGooFromPurchase(msg.sender, reducedUpgradeCost); army.depositSpentGoo(reducedUpgradeCost); // Transfer to goo bankroll // Update stats for upgrade if (upgrade.column == 2) { unitMaxCap[msg.sender][unitId] += upgrade.unitMaxCapacityGain; } else if (upgrade.column == 1) { increaseUpgrades(msg.sender, upgrade, unitId); } else if (upgrade.column == 0) { increaseUpgrades(msg.sender, upgrade, unitId); } } } contract GooToken { function transfer(address to, uint256 tokens) external returns (bool); function increasePlayersGooProduction(address player, uint256 increase) external; function decreasePlayersGooProduction(address player, uint256 decrease) external; function updatePlayersGooFromPurchase(address player, uint224 purchaseCost) external; function updatePlayersGoo(address player) external; function mintGoo(uint224 amount, address player) external; } contract Army { function depositSpentGoo(uint224 gooSpent) external; function increasePlayersArmyPowerTrio(address player, uint80 attackGain, uint80 defenseGain, uint80 lootingGain) public; function decreasePlayersArmyPowerTrio(address player, uint80 attackLoss, uint80 defenseLoss, uint80 lootingLoss) public; function changePlayersArmyPowerTrio(address player, int attackChange, int defenseChange, int lootingChange) public; } contract Clans { mapping(uint256 => uint256) public clanTotalArmyPower; function totalSupply() external view returns (uint256); function depositGoo(uint256 amount, uint256 clanId) external; function getPlayerFees(address player) external view returns (uint224 clansFee, uint224 leadersFee, address leader, uint224 referalsFee, address referer); function getPlayersClanUpgrade(address player, uint256 upgradeClass) external view returns (uint224 upgradeGain); function mintGoo(address player, uint256 amount) external; function increaseClanPower(address player, uint256 amount) external; function decreaseClanPower(address player, uint256 amount) external; } contract Factories { uint256 public constant MAX_SIZE = 40; function getFactories(address player) external returns (uint256[]); function addFactory(address player, uint8 position, uint256 unitId) external; } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint224 a, uint224 b) internal pure returns (uint224) { if (a == 0) { return 0; } uint224 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } library SafeMath224 { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint224 a, uint224 b) internal pure returns (uint224) { if (a == 0) { return 0; } uint224 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint224 a, uint224 b) internal pure returns (uint224) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint224 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint224 a, uint224 b) internal pure returns (uint224) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint224 a, uint224 b) internal pure returns (uint224) { uint224 c = a + b; assert(c >= a); return c; } }
Grant buff to unit (5% additive multiplier) Increase player's army power
function grantArmyExp(address player, uint256 unitId, uint224 amount) external returns(bool) { require(operator[msg.sender]); UnitExperience memory existingExp = unitExp[player][unitId]; if (existingExp.experience + amount >= expRequirement) { existingExp.experience = (existingExp.experience + amount) - expRequirement; existingExp.level++; unitExp[player][unitId] = existingExp; UnitUpgrades memory existingUpgrades = unitUpgrades[player][unitId]; existingUpgrades.attackMultiplier += 5; existingUpgrades.defenseMultiplier += 5; existingUpgrades.lootingMultiplier += 5; unitUpgrades[player][unitId] = existingUpgrades; uint80 multiplierGain = unitsOwned[player][unitId].units * 5; Unit memory unit = unitList[unitId]; uint80 attackGain = multiplierGain * (unit.attack + existingUpgrades.attackIncrease); uint80 defenseGain = multiplierGain * (unit.defense + existingUpgrades.defenseIncrease); uint80 lootingGain = multiplierGain * (unit.looting + existingUpgrades.lootingIncrease); army.increasePlayersArmyPowerTrio(player, attackGain, defenseGain, lootingGain); return true; unitExp[player][unitId].experience += amount; return false; } }
12,972,375
/* Copyright 2020 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { I_ExchangeWrapper } from "../../../external/I_ExchangeWrapper.sol"; import { I_PerpetualV1 } from "../intf/I_PerpetualV1.sol"; /** * @title P1CurrencyConverterProxy * @author dYdX * * @notice Proxy contract which executes a trade via an ExchangeWrapper before making a deposit * or after making a withdrawal. */ contract P1CurrencyConverterProxy { using SafeERC20 for IERC20; // ============ Events ============ event LogConvertedDeposit( address indexed account, address source, address perpetual, address exchangeWrapper, address tokenFrom, address tokenTo, uint256 tokenFromAmount, uint256 tokenToAmount ); event LogConvertedWithdrawal( address indexed account, address destination, address perpetual, address exchangeWrapper, address tokenFrom, address tokenTo, uint256 tokenFromAmount, uint256 tokenToAmount ); // ============ State-Changing Functions ============ /** * @notice Sets the maximum allowance on the Perpetual contract. Must be called at least once * on a given Perpetual before deposits can be made. * @dev Cannot be run in the constructor due to technical restrictions in Solidity. */ function approveMaximumOnPerpetual( address perpetual ) external { IERC20 tokenContract = IERC20(I_PerpetualV1(perpetual).getTokenContract()); // safeApprove requires unsetting the allowance first. tokenContract.safeApprove(perpetual, 0); // Set the allowance to the highest possible value. tokenContract.safeApprove(perpetual, uint256(-1)); } /** * @notice Make a margin deposit to a Perpetual, after converting funds to the margin currency. * Funds will be withdrawn from the sender and deposited into the specified account. * @dev Emits LogConvertedDeposit event. * * @param account The account for which to credit the deposit. * @param perpetual The PerpetualV1 contract to deposit to. * @param exchangeWrapper The ExchangeWrapper contract to trade with. * @param tokenFrom The token to convert from. * @param tokenFromAmount The amount of `tokenFrom` tokens to deposit. * @param data Trade parameters for the ExchangeWrapper. */ function deposit( address account, address perpetual, address exchangeWrapper, address tokenFrom, uint256 tokenFromAmount, bytes calldata data ) external returns (uint256) { I_PerpetualV1 perpetualContract = I_PerpetualV1(perpetual); address tokenTo = perpetualContract.getTokenContract(); address self = address(this); // Send fromToken to the ExchangeWrapper. // // TODO: Take possible ERC20 fee into account. IERC20(tokenFrom).safeTransferFrom( msg.sender, exchangeWrapper, tokenFromAmount ); // Convert fromToken to toToken on the ExchangeWrapper. I_ExchangeWrapper exchangeWrapperContract = I_ExchangeWrapper(exchangeWrapper); uint256 tokenToAmount = exchangeWrapperContract.exchange( msg.sender, self, tokenTo, tokenFrom, tokenFromAmount, data ); // Receive toToken from the ExchangeWrapper. IERC20(tokenTo).safeTransferFrom( exchangeWrapper, self, tokenToAmount ); // Deposit toToken to the Perpetual. perpetualContract.deposit( account, tokenToAmount ); // Log the result. emit LogConvertedDeposit( account, msg.sender, perpetual, exchangeWrapper, tokenFrom, tokenTo, tokenFromAmount, tokenToAmount ); return tokenToAmount; } /** * @notice Withdraw margin from a Perpetual, then convert the funds to another currency. Funds * will be withdrawn from the specified account and transfered to the specified destination. * @dev Emits LogConvertedWithdrawal event. * * @param account The account to withdraw from. * @param destination The address to send the withdrawn funds to. * @param perpetual The PerpetualV1 contract to withdraw from to. * @param exchangeWrapper The ExchangeWrapper contract to trade with. * @param tokenTo The token to convert to. * @param tokenFromAmount The amount of `tokenFrom` tokens to withdraw. * @param data Trade parameters for the ExchangeWrapper. */ function withdraw( address account, address destination, address perpetual, address exchangeWrapper, address tokenTo, uint256 tokenFromAmount, bytes calldata data ) external returns (uint256) { I_PerpetualV1 perpetualContract = I_PerpetualV1(perpetual); address tokenFrom = perpetualContract.getTokenContract(); address self = address(this); // Verify that the sender has permission to withdraw from the account. require( account == msg.sender || perpetualContract.hasAccountPermissions(account, msg.sender), "msg.sender cannot operate the account" ); // Withdraw fromToken from the Perpetual. perpetualContract.withdraw( account, exchangeWrapper, tokenFromAmount ); // Convert fromToken to toToken on the ExchangeWrapper. I_ExchangeWrapper exchangeWrapperContract = I_ExchangeWrapper(exchangeWrapper); uint256 tokenToAmount = exchangeWrapperContract.exchange( msg.sender, self, tokenTo, tokenFrom, tokenFromAmount, data ); // Transfer toToken from the ExchangeWrapper to the destination address. IERC20(tokenTo).safeTransferFrom( exchangeWrapper, destination, tokenToAmount ); // Log the result. emit LogConvertedWithdrawal( account, destination, perpetual, exchangeWrapper, tokenFrom, tokenTo, tokenFromAmount, tokenToAmount ); return tokenToAmount; } }
Withdraw margin from a Perpetual, then convert the funds to another currency. Funds will be withdrawn from the specified account and transfered to the specified destination. Emits LogConvertedWithdrawal event. account The account to withdraw from. destination The address to send the withdrawn funds to. perpetual The PerpetualV1 contract to withdraw from to. exchangeWrapper The ExchangeWrapper contract to trade with. tokenTo The token to convert to. tokenFromAmount The amount of `tokenFrom` tokens to withdraw. data Trade parameters for the ExchangeWrapper./ Verify that the sender has permission to withdraw from the account. Withdraw fromToken from the Perpetual. Convert fromToken to toToken on the ExchangeWrapper. Transfer toToken from the ExchangeWrapper to the destination address. Log the result.
function withdraw( address account, address destination, address perpetual, address exchangeWrapper, address tokenTo, uint256 tokenFromAmount, bytes calldata data ) external returns (uint256) { I_PerpetualV1 perpetualContract = I_PerpetualV1(perpetual); address tokenFrom = perpetualContract.getTokenContract(); address self = address(this); require( account == msg.sender || perpetualContract.hasAccountPermissions(account, msg.sender), "msg.sender cannot operate the account" ); perpetualContract.withdraw( account, exchangeWrapper, tokenFromAmount ); I_ExchangeWrapper exchangeWrapperContract = I_ExchangeWrapper(exchangeWrapper); uint256 tokenToAmount = exchangeWrapperContract.exchange( msg.sender, self, tokenTo, tokenFrom, tokenFromAmount, data ); IERC20(tokenTo).safeTransferFrom( exchangeWrapper, destination, tokenToAmount ); emit LogConvertedWithdrawal( account, destination, perpetual, exchangeWrapper, tokenFrom, tokenTo, tokenFromAmount, tokenToAmount ); return tokenToAmount; }
5,428,264
contract FivePercent { struct Participant { address etherAddress; uint amount; } Participant[] private participants; uint private payoutIdx = 0; uint private balance = 0; uint private factor =105; //105% payout //Fallback function function() { init(); } //init function run on fallback function init() private { //Ensures only tx with value between min. 10 finney (0.01 ether) and max. 10 ether are processed if (msg.value < 10 finney) { msg.sender.send(msg.value); return; } uint amount; if (msg.value > 10 ether) { msg.sender.send(msg.value - 10 ether); amount = 10 ether; } else { amount = msg.value; } // add a new participant to array uint idx = participants.length; participants.length += 1; participants[idx].etherAddress = msg.sender; participants[idx].amount = amount ; // update contract balance balance += amount ; // while there are enough ether on the balance we can pay out to an earlier participant while (balance > factor*participants[payoutIdx].amount / 100 ) { uint transactionAmount = factor* participants[payoutIdx].amount / 100; participants[payoutIdx].etherAddress.send(transactionAmount); balance -= transactionAmount; payoutIdx += 1; } } function Infos() constant returns (uint BalanceInFinney, uint Participants, uint PayOutIndex,uint NextPayout, string info) { BalanceInFinney = balance / 1 finney; PayOutIndex=payoutIdx; Participants=participants.length; NextPayout =factor*participants[payoutIdx].amount / 1 finney; NextPayout=NextPayout /100; info = &#39;All amounts in Finney (1 Ether = 1000 Finney)&#39;; } function participantDetails(uint nr) constant returns (address Address, uint PayinInFinney, uint PayoutInFinney, string PaidOut) { PaidOut=&#39;N.A.&#39;; Address=0; PayinInFinney=0; PayoutInFinney=0; if (nr < participants.length) { Address = participants[nr].etherAddress; PayinInFinney = participants[nr].amount / 1 finney; PayoutInFinney= factor*PayinInFinney/100; PaidOut=&#39;no&#39;; if (nr<payoutIdx){PaidOut=&#39;yes&#39;;} } } }
init function run on fallbackEnsures only tx with value between min. 10 finney (0.01 ether) and max. 10 ether are processed
function init() private { if (msg.value < 10 finney) { msg.sender.send(msg.value); return; } uint amount; if (msg.value > 10 ether) { msg.sender.send(msg.value - 10 ether); amount = 10 ether; } else { amount = msg.value; } participants.length += 1; participants[idx].etherAddress = msg.sender; participants[idx].amount = amount ; { uint transactionAmount = factor* participants[payoutIdx].amount / 100; participants[payoutIdx].etherAddress.send(transactionAmount); balance -= transactionAmount; payoutIdx += 1; } }
12,856,664
pragma solidity ^0.5.15; interface IERC20 { function TOTALSUPPLY265() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF676(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER585(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE478(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE401(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM799(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER297(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL288(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER981() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA870() internal view 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 Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED51(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER981(); emit OWNERSHIPTRANSFERRED51(address(0), _owner); } function OWNER52() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER947() { //inject NONSTANDARD NAMING require(ISOWNER855(), "Ownable: caller is not the owner"); _; } function ISOWNER855() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER981() == _owner; } function RENOUNCEOWNERSHIP936() public ONLYOWNER947 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED51(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP177(address newOwner) public ONLYOWNER947 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP636(newOwner); } function _TRANSFEROWNERSHIP636(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED51(_owner, newOwner); _owner = newOwner; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY265() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF676(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER585(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER399(_MSGSENDER981(), recipient, amount); return true; } function ALLOWANCE478(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE401(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE768(_MSGSENDER981(), spender, amount); return true; } function TRANSFERFROM799(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER399(sender, recipient, amount); _APPROVE768(sender, _MSGSENDER981(), _allowances[sender][_MSGSENDER981()].SUB171(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE254(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].ADD125(addedValue)); return true; } function DECREASEALLOWANCE775(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].SUB171(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER399(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB171(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD125(amount); emit TRANSFER297(sender, recipient, amount); } function _MINT552(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD125(amount); _balances[account] = _balances[account].ADD125(amount); emit TRANSFER297(address(0), account, amount); } function _BURN908(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB171(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB171(amount); emit TRANSFER297(account, address(0), amount); } function _APPROVE768(address owner, address spender, uint256 amount) internal { //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 APPROVAL288(owner, spender, amount); } function _BURNFROM359(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN908(account, amount); _APPROVE768(account, _MSGSENDER981(), _allowances[account][_MSGSENDER981()].SUB171(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME677() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL955() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS596() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD125(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB171(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB171(a, b, "SafeMath: subtraction overflow"); } function SUB171(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 MUL207(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV619(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV619(a, b, "SafeMath: division by zero"); } function DIV619(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD550(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD550(a, b, "SafeMath: modulo by zero"); } function MOD550(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT651(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE339(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE156(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER644(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFER585.selector, to, value)); } function SAFETRANSFERFROM18(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFERFROM799.selector, from, to, value)); } function SAFEAPPROVE229(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE478(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, value)); } function SAFEINCREASEALLOWANCE497(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE478(address(this), spender).ADD125(value); CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE975(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE478(address(this), spender).SUB171(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance)); } function CALLOPTIONALRETURN428(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT651(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface Controller { function WITHDRAW158(address, uint) external; //inject NONSTANDARD NAMING function BALANCEOF676(address) external view returns (uint); //inject NONSTANDARD NAMING function EARN532(address, uint) external; //inject NONSTANDARD NAMING function REWARDS630() external view returns (address); //inject NONSTANDARD NAMING } // vault1111 111111111111 // abi1111: https://github.com/ystar-foundation/YstarFarming/blob/master/Vault/abi/vault.json contract Vault { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; IERC20 public YFToken; // YF1111 uint public min = 9500; uint public constant max986 = 10000; //inject NONSTANDARD NAMING uint public earnLowerlimit; //1111111111111earn address public governance; address public controller; struct Player { uint256 stake; // 1111 uint256 payout; // 11 uint256 total_out; // 1111111 } mapping(address => Player) public player_; // (player => data) player data struct Global { uint256 total_stake; // 11111 uint256 total_out; // 11111 uint256 earnings_per_share; // 1111 } mapping(uint256 => Global) public global_; // (global => data) global data mapping (address => uint256) public deposittime; uint256 constant internal magnitude720 = 10**40; // 1014011 //inject NONSTANDARD NAMING address constant public yf82 = address(0x96F9632b25f874769969ff91219fCCb6ceDf26D2); //inject NONSTANDARD NAMING string public getName; constructor (address _token, uint256 _earnLowerlimit) public { token = IERC20(_token); getName = string(abi.encodePacked("yf:Vault:", ERC20Detailed(_token).NAME677())); earnLowerlimit = _earnLowerlimit*1e18; YFToken = IERC20(yf82); governance = tx.origin; controller = 0xcC8d36211374a08fC61d74ed2E48e22b922C9D7C; } function BALANCE265() public view returns (uint) { //inject NONSTANDARD NAMING return token.BALANCEOF676(address(this)) .ADD125(Controller(controller).BALANCEOF676(address(token))); } function SETMIN245(uint _min) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); min = _min; } // 11111111111111111111 function SETGOVERNANCE992(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } // 1111token function SETTOKEN102(address _token) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); token = IERC20(_token); } // 1111111111111111111 function SETCONTROLLER604(address _controller) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } function SETEARNLOWERLIMIT476(uint256 _earnLowerlimit) public{ //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); earnLowerlimit = _earnLowerlimit; } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap // 11111111111 // 111111111111111111111 function AVAILABLE23() public view returns (uint) { //inject NONSTANDARD NAMING return token.BALANCEOF676(address(this)).MUL207(min).DIV619(max986); // balance*min/max 1111111111111111111 } // 11111Strategy1111111111111 vault->controller->strategy function EARN532() public { //inject NONSTANDARD NAMING uint _bal = AVAILABLE23(); // 1111111111111111111111 token.SAFETRANSFER644(controller, _bal); // 1111111 Controller(controller).EARN532(address(token), _bal); // 11111Strategy111111 } // 11 111111 function DEPOSIT245(uint amount) external { //inject NONSTANDARD NAMING // 111111111111111111appove1111111111111 token.SAFETRANSFERFROM18(msg.sender, address(this), amount); // 1111111111 player_[msg.sender].stake = player_[msg.sender].stake.ADD125(amount); // 11111110 if (global_[0].earnings_per_share != 0) { player_[msg.sender].payout = player_[msg.sender].payout.ADD125( global_[0].earnings_per_share.MUL207(amount).SUB171(1).DIV619(magnitude720).ADD125(1) // (((earnings_per_share*amount)-1)/magnitude)+1 ); } // 1111111111 global_[0].total_stake = global_[0].total_stake.ADD125(amount); // 111111111111111111111111111111111111111111111 if (token.BALANCEOF676(address(this)) > earnLowerlimit){ EARN532(); } // 11111111 deposittime[msg.sender] = now; } // No rebalance implementation for lower fees and faster swaps // 11 function WITHDRAW158(uint amount) external { //inject NONSTANDARD NAMING CLAIM365(); // 111111111111 require(amount <= player_[msg.sender].stake, "!balance"); uint r = amount; // Check balance uint b = token.BALANCEOF676(address(this)); if (b < r) { // 11vault111111111111111111111Strategy11111111111 uint _withdraw = r.SUB171(b); Controller(controller).WITHDRAW158(address(token), _withdraw); // 11 uint _after = token.BALANCEOF676(address(this)); uint _diff = _after.SUB171(b); if (_diff < _withdraw) { // 111111111111111111111vault111111 r = b.ADD125(_diff); } } // 111111111111111111111 player_[msg.sender].payout = player_[msg.sender].payout.SUB171( global_[0].earnings_per_share.MUL207(amount).DIV619(magnitude720) ); // 1111111111111 player_[msg.sender].stake = player_[msg.sender].stake.SUB171(amount); global_[0].total_stake = global_[0].total_stake.SUB171(amount); // 1111111111 token.SAFETRANSFER644(msg.sender, r); } // Strategy.harvest 111111 function MAKE_PROFIT788(uint256 amount) public { //inject NONSTANDARD NAMING require(amount > 0, "not 0"); YFToken.SAFETRANSFERFROM18(msg.sender, address(this), amount); // 1111111111111110%1111190%1111111 global_[0].earnings_per_share = global_[0].earnings_per_share.ADD125( amount.MUL207(magnitude720).DIV619(global_[0].total_stake) ); global_[0].total_out = global_[0].total_out.ADD125(amount); } // 11111111 function CAL_OUT246(address user) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _cal = global_[0].earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720); if (_cal < player_[user].payout) { return 0; } else { return _cal.SUB171(player_[user].payout); } } // 11111111111111111111111111.11111111111harvest1111111111 function CAL_OUT_PENDING918(uint256 _pendingBalance,address user) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _earnings_per_share = global_[0].earnings_per_share.ADD125( _pendingBalance.MUL207(magnitude720).DIV619(global_[0].total_stake) ); uint256 _cal = _earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720); _cal = _cal.SUB171(CAL_OUT246(user)); if (_cal < player_[user].payout) { return 0; } else { return _cal.SUB171(player_[user].payout); } } // 111111 function CLAIM365() public { //inject NONSTANDARD NAMING uint256 out = CAL_OUT246(msg.sender); player_[msg.sender].payout = global_[0].earnings_per_share.MUL207(player_[msg.sender].stake).DIV619(magnitude720); player_[msg.sender].total_out = player_[msg.sender].total_out.ADD125(out); if (out > 0) { uint256 _depositTime = now - deposittime[msg.sender]; if (_depositTime < 1 days){ // deposit in 24h uint256 actually_out = _depositTime.MUL207(out).MUL207(1e18).DIV619(1 days).DIV619(1e18); uint256 to_team = out.SUB171(actually_out); YFToken.SAFETRANSFER644(Controller(controller).REWARDS630(), to_team); out = actually_out; } YFToken.SAFETRANSFER644(msg.sender, out); } } }
inject NONSTANDARD NAMING
function CLAIM365() public {
12,634,708
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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 "./FeeManagerStorage.sol"; /// @title FeeManager /// @author Angle Core Team /// @dev This contract interacts with fee parameters for a given stablecoin/collateral pair /// @dev `FeeManager` contains all the functions that keepers can call to update parameters /// in the `StableMaster` and `PerpetualManager` contracts /// @dev These parameters need to be updated by keepers because they depend on variables, like /// the collateral ratio, that are too expensive to compute each time transactions that would need /// it occur contract FeeManager is FeeManagerStorage, IFeeManagerFunctions, AccessControl, Initializable { /// @notice Role for `PoolManager` only bytes32 public constant POOLMANAGER_ROLE = keccak256("POOLMANAGER_ROLE"); /// @notice Role for guardians and governors bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); /// @notice Deploys the `FeeManager` contract for a pair stablecoin/collateral /// @param _poolManager `PoolManager` contract handling the collateral /// @dev The `_poolManager` address is used to grant the correct role. It does not need to be stored by the /// contract /// @dev There is no need to do a zero address check on the `_poolManager` as if the zero address is passed /// the function will revert when trying to fetch the `StableMaster` constructor(IPoolManager _poolManager) { stableMaster = IStableMaster(_poolManager.stableMaster()); // Once a `FeeManager` contract has been initialized with a `PoolManager` contract, this // reference cannot be modified _setupRole(POOLMANAGER_ROLE, address(_poolManager)); _setRoleAdmin(POOLMANAGER_ROLE, POOLMANAGER_ROLE); _setRoleAdmin(GUARDIAN_ROLE, POOLMANAGER_ROLE); } /// @notice Initializes the governor and guardian roles of the contract as well as the reference to /// the `perpetualManager` contract /// @param governorList List of the governor addresses of the protocol /// @param guardian Guardian address of the protocol /// @param _perpetualManager `PerpetualManager` contract handling the perpetuals of the pool /// @dev `GUARDIAN_ROLE` can then directly be granted or revoked by the corresponding `PoolManager` /// As `POOLMANAGER_ROLE` is admin of `GUARDIAN_ROLE`, it corresponds to the intended behaviour of roles function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external override onlyRole(POOLMANAGER_ROLE) initializer { for (uint256 i = 0; i < governorList.length; i++) { _grantRole(GUARDIAN_ROLE, governorList[i]); } _grantRole(GUARDIAN_ROLE, guardian); perpetualManager = IPerpetualManager(_perpetualManager); } // ============================ `StableMaster` ================================= /// @notice Updates the SLP and Users fees associated to the pair stablecoin/collateral in /// the `StableMaster` contract /// @dev This function updates: /// - `bonusMalusMint`: part of the fee induced by a user minting depending on the collateral ratio /// In normal times, no fees are taken for that, and so this fee should be equal to `BASE_PARAMS` /// - `bonusMalusBurn`: part of the fee induced by a user burning depending on the collateral ratio /// - Slippage: what's given to SLPs compared with their claim when they exit /// - SlippageFee: that is the portion of fees that is put aside because the protocol /// is not well collateralized /// @dev `bonusMalusMint` and `bonusMalusBurn` allow governance to add penalties or bonuses for users minting /// and burning in some situations of collateral ratio. These parameters are multiplied to the fee amount depending /// on the hedge ratio by Hedging Agents to get the exact fee induced to the users function updateUsersSLP() external override { // Computing the collateral ratio, expressed in `BASE_PARAMS` uint256 collatRatio = stableMaster.getCollateralRatio(); // Computing the fees based on this collateral ratio uint64 bonusMalusMint = _piecewiseLinearCollatRatio(collatRatio, xBonusMalusMint, yBonusMalusMint); uint64 bonusMalusBurn = _piecewiseLinearCollatRatio(collatRatio, xBonusMalusBurn, yBonusMalusBurn); uint64 slippage = _piecewiseLinearCollatRatio(collatRatio, xSlippage, ySlippage); uint64 slippageFee = _piecewiseLinearCollatRatio(collatRatio, xSlippageFee, ySlippageFee); emit UserAndSLPFeesUpdated(collatRatio, bonusMalusMint, bonusMalusBurn, slippage, slippageFee); stableMaster.setFeeKeeper(bonusMalusMint, bonusMalusBurn, slippage, slippageFee); } // ============================= PerpetualManager ============================== /// @notice Updates HA fees associated to the pair stablecoin/collateral in the `PerpetualManager` contract /// @dev This function updates: /// - The part of the fee taken from HAs when they open a perpetual or add collateral in it. This allows /// governance to add penalties or bonuses in some occasions to HAs opening their perpetuals /// - The part of the fee taken from the HA when they withdraw collateral from a perpetual. This allows /// governance to add penalty or bonuses in some occasions to HAs closing their perpetuals /// @dev Penalties or bonuses for HAs should almost never be used /// @dev In the `PerpetualManager` contract, these parameters are multiplied to the fee amount depending on the HA /// hedge ratio to get the exact fee amount for HAs /// @dev For the moment, these parameters do not depend on the collateral ratio, and they are just an extra /// element that governance can play on to correct fees taken for HAs function updateHA() external override { emit HaFeesUpdated(haFeeDeposit, haFeeWithdraw); perpetualManager.setFeeKeeper(haFeeDeposit, haFeeWithdraw); } // ============================= Governance ==================================== /// @notice Sets the x (i.e. thresholds of collateral ratio) array / y (i.e. value of fees at threshold)-array /// for users minting, burning, for SLPs withdrawal slippage or for the slippage fee when updating /// the exchange rate between sanTokens and collateral /// @param xArray New collateral ratio thresholds (in ascending order) /// @param yArray New fees or values for the parameters at thresholds /// @param typeChange Type of parameter to change /// @dev For `typeChange = 1`, `bonusMalusMint` fees are updated /// @dev For `typeChange = 2`, `bonusMalusBurn` fees are updated /// @dev For `typeChange = 3`, `slippage` values are updated /// @dev For other values of `typeChange`, `slippageFee` values are updated function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external override onlyRole(GUARDIAN_ROLE) { require(xArray.length == yArray.length && yArray.length > 0, "5"); for (uint256 i = 0; i <= yArray.length - 1; i++) { if (i > 0) { require(xArray[i] > xArray[i - 1], "7"); } } if (typeChange == 1) { xBonusMalusMint = xArray; yBonusMalusMint = yArray; emit FeeMintUpdated(xBonusMalusMint, yBonusMalusMint); } else if (typeChange == 2) { xBonusMalusBurn = xArray; yBonusMalusBurn = yArray; emit FeeBurnUpdated(xBonusMalusBurn, yBonusMalusBurn); } else if (typeChange == 3) { xSlippage = xArray; ySlippage = yArray; _checkSlippageCompatibility(); emit SlippageUpdated(xSlippage, ySlippage); } else { xSlippageFee = xArray; ySlippageFee = yArray; _checkSlippageCompatibility(); emit SlippageFeeUpdated(xSlippageFee, ySlippageFee); } } /// @notice Sets the extra fees that can be used when HAs deposit or withdraw collateral from the /// protocol /// @param _haFeeDeposit New parameter to modify deposit fee for HAs /// @param _haFeeWithdraw New parameter to modify withdraw fee for HAs function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external override onlyRole(GUARDIAN_ROLE) { haFeeDeposit = _haFeeDeposit; haFeeWithdraw = _haFeeWithdraw; } /// @notice Helps to make sure that the `slippageFee` and the `slippage` will in most situations be compatible /// with one another /// @dev Whenever the `slippageFee` is not null, the `slippage` should be non null, as otherwise, there would be /// an opportunity cost to increase the collateral ratio to make the `slippage` non null and collect the fees /// that have been left aside /// @dev This function does not perform an exhaustive check around the fact that whenever the `slippageFee` /// is not null the `slippage` is not null neither. It simply checks that each positive value in the `ySlippageFee` array /// corresponds to a positive value of the `slippage` /// @dev The protocol still relies on governance to make sure that this condition is always verified, this function /// is just here to eliminate potentially extreme errors function _checkSlippageCompatibility() internal view { // We need this `if` condition because when this function is first called after contract deployment, the length // of the two arrays is zero if (xSlippage.length >= 1 && xSlippageFee.length >= 1) { for (uint256 i = 0; i <= ySlippageFee.length - 1; i++) { if (ySlippageFee[i] > 0) { require(ySlippageFee[i] <= BASE_PARAMS_CASTED, "37"); require(_piecewiseLinearCollatRatio(xSlippageFee[i], xSlippage, ySlippage) > 0, "38"); } } } } /// @notice Computes the value of a linear by part function at a given point /// @param x Point of the function we want to compute /// @param xArray List of breaking points (in ascending order) that define the linear by part function /// @param yArray List of values at breaking points (not necessarily in ascending order) /// @dev The evolution of the linear by part function between two breaking points is linear /// @dev Before the first breaking point and after the last one, the function is constant with a value /// equal to the first or last value of the `yArray` /// @dev The reason for having a function that is different from what's in the `FunctionUtils` contract is that /// here the values in `xArray` can be greater than `BASE_PARAMS` meaning that there is a non negligeable risk that /// the product between `yArray` and `xArray` values overflows function _piecewiseLinearCollatRatio( uint256 x, uint256[] storage xArray, uint64[] storage yArray ) internal view returns (uint64 y) { if (x >= xArray[xArray.length - 1]) { return yArray[xArray.length - 1]; } else if (x <= xArray[0]) { return yArray[0]; } else { uint256 lower; uint256 upper = xArray.length - 1; uint256 mid; while (upper - lower > 1) { mid = lower + (upper - lower) / 2; if (xArray[mid] <= x) { lower = mid; } else { upper = mid; } } uint256 yCasted; if (yArray[upper] > yArray[lower]) { yCasted = yArray[lower] + ((yArray[upper] - yArray[lower]) * (x - xArray[lower])) / (xArray[upper] - xArray[lower]); } else { yCasted = yArray[lower] - ((yArray[lower] - yArray[upper]) * (x - xArray[lower])) / (xArray[upper] - xArray[lower]); } // There is no problem with this cast as `y` was initially a `uint64` and we divided a `uint256` with a `uint256` // that is greater y = uint64(yCasted); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../external/AccessControl.sol"; import "../interfaces/IFeeManager.sol"; import "../interfaces/IPoolManager.sol"; import "../interfaces/IStableMaster.sol"; import "../interfaces/IPerpetualManager.sol"; /// @title FeeManagerEvents /// @author Angle Core Team /// @dev This file contains all the events that are triggered by the `FeeManager` contract contract FeeManagerEvents { event UserAndSLPFeesUpdated( uint256 _collatRatio, uint64 _bonusMalusMint, uint64 _bonusMalusBurn, uint64 _slippage, uint64 _slippageFee ); event FeeMintUpdated(uint256[] _xBonusMalusMint, uint64[] _yBonusMalusMint); event FeeBurnUpdated(uint256[] _xBonusMalusBurn, uint64[] _yBonusMalusBurn); event SlippageUpdated(uint256[] _xSlippage, uint64[] _ySlippage); event SlippageFeeUpdated(uint256[] _xSlippageFee, uint64[] _ySlippageFee); event HaFeesUpdated(uint64 _haFeeDeposit, uint64 _haFeeWithdraw); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./FeeManagerEvents.sol"; /// @title FeeManagerStorage /// @author Angle Core Team /// @dev `FeeManagerStorage` contains all the parameters (most often fee parameters) to add corrections /// to fees in the `StableMaster` and `PerpetualManager` contracts contract FeeManagerStorage is FeeManagerEvents { uint64 public constant BASE_PARAMS_CASTED = 10**9; // ==================== References to other contracts ========================== /// @notice Address of the `StableMaster` contract corresponding to this contract /// This reference cannot be modified IStableMaster public stableMaster; /// @notice Address of the `PerpetualManager` corresponding to this contract /// This reference cannot be modified IPerpetualManager public perpetualManager; // ================= Parameters that can be set by governance ================== /// @notice Bonus - Malus Fee, means that if the `fee > BASE_PARAMS` then agents incur a malus and will /// have larger fees, while `fee < BASE_PARAMS` they incur a smaller fee than what they would have if fees /// just consisted in what was obtained using the hedge ratio /// @notice Values of the collateral ratio where mint transaction fees will change for users /// It should be ranked in ascending order uint256[] public xBonusMalusMint; /// @notice Values of the bonus/malus on the mint fees at the points of collateral ratio in the array above /// The evolution of the fees when collateral ratio is between two threshold values is linear uint64[] public yBonusMalusMint; /// @notice Values of the collateral ratio where burn transaction fees will change uint256[] public xBonusMalusBurn; /// @notice Values of the bonus/malus on the burn fees at the points of collateral ratio in the array above uint64[] public yBonusMalusBurn; /// @notice Values of the collateral ratio where the slippage factor for SLPs exiting will evolve uint256[] public xSlippage; /// @notice Slippage factor at the values of collateral ratio above uint64[] public ySlippage; /// @notice Values of the collateral ratio where the slippage fee, that is the portion of the fees /// that does not come to SLPs although changes uint256[] public xSlippageFee; /// @notice Slippage fee value at the values of collateral ratio above uint64[] public ySlippageFee; /// @notice Bonus - Malus HA deposit Fee, means that if the `fee > BASE_PARAMS` then HAs incur a malus and /// will have larger fees, while `fee < BASE_PARAMS` they incur a smaller fee than what they would have if /// fees just consisted in what was obtained using hedge ratio uint64 public haFeeDeposit; /// @notice Bonus - Malus HA withdraw Fee uint64 public haFeeWithdraw; } // 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; /// @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 "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /// @title ISanToken /// @author Angle Core Team /// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs /// contributing to a collateral for a given stablecoin interface ISanToken is IERC20Upgradeable { // ================================== StableMaster ============================= function mint(address account, uint256 amount) external; function burnFrom( uint256 amount, address burner, address sender ) external; function burnSelf(uint256 amount, address burner) external; function stableMaster() external view returns (address); function poolManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Normally just importing `IPoolManager` should be sufficient, but for clarity here // we prefer to import all concerned interfaces import "./IPoolManager.sol"; import "./IOracle.sol"; import "./IPerpetualManager.sol"; import "./ISanToken.sol"; // Struct to handle all the parameters to manage the fees // related to a given collateral pool (associated to the stablecoin) struct MintBurnData { // Values of the thresholds to compute the minting fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeMint; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeMint; // Values of the thresholds to compute the burning fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeBurn; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeBurn; // Max proportion of collateral from users that can be covered by HAs // It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated // the other changes accordingly uint64 targetHAHedge; // Minting fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusMint; // Burning fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusBurn; // Parameter used to limit the number of stablecoins that can be issued using the concerned collateral uint256 capOnStableMinted; } // Struct to handle all the variables and parameters to handle SLPs in the protocol // including the fraction of interests they receive or the fees to be distributed to // them struct SLPData { // Last timestamp at which the `sanRate` has been updated for SLPs uint256 lastBlockUpdated; // Fees accumulated from previous blocks and to be distributed to SLPs uint256 lockedInterests; // Max interests used to update the `sanRate` in a single block // Should be in collateral token base uint256 maxInterestsDistributed; // Amount of fees left aside for SLPs and that will be distributed // when the protocol is collateralized back again uint256 feesAside; // Part of the fees normally going to SLPs that is left aside // before the protocol is collateralized back again (depends on collateral ratio) // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippageFee; // Portion of the fees from users minting and burning // that goes to SLPs (the rest goes to surplus) uint64 feesForSLPs; // Slippage factor that's applied to SLPs exiting (depends on collateral ratio) // If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippage; // Portion of the interests from lending // that goes to SLPs (the rest goes to surplus) uint64 interestsForSLPs; } /// @title IStableMasterFunctions /// @author Angle Core Team /// @notice Interface for the `StableMaster` contract interface IStableMasterFunctions { function deploy( address[] memory _governorList, address _guardian, address _agToken ) external; // ============================== Lending ====================================== function accumulateInterest(uint256 gain) external; function signalLoss(uint256 loss) external; // ============================== HAs ========================================== function getStocksUsers() external view returns (uint256 maxCAmountInStable); function convertToSLP(uint256 amount, address user) external; // ============================== Keepers ====================================== function getCollateralRatio() external returns (uint256); function setFeeKeeper( uint64 feeMint, uint64 feeBurn, uint64 _slippage, uint64 _slippageFee ) external; // ============================== AgToken ====================================== function updateStocksUsers(uint256 amount, address poolManager) external; // ============================= Governance ==================================== function setCore(address newCore) external; function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address newGuardian, address oldGuardian) external; function revokeGuardian(address oldGuardian) external; function setCapOnStableAndMaxInterests( uint256 _capOnStableMinted, uint256 _maxInterestsDistributed, IPoolManager poolManager ) external; function setIncentivesForSLPs( uint64 _feesForSLPs, uint64 _interestsForSLPs, IPoolManager poolManager ) external; function setUserFees( IPoolManager poolManager, uint64[] memory _xFee, uint64[] memory _yFee, uint8 _mint ) external; function setTargetHAHedge(uint64 _targetHAHedge) external; function pause(bytes32 agent, IPoolManager poolManager) external; function unpause(bytes32 agent, IPoolManager poolManager) external; } /// @title IStableMaster /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings interface IStableMaster is IStableMasterFunctions { function agToken() external view returns (address); function collateralMap(IPoolManager poolManager) external view returns ( IERC20 token, ISanToken sanToken, IPerpetualManager perpetualManager, IOracle oracle, uint256 stocksUsers, uint256 sanRate, uint256 collatBase, SLPData memory slpData, MintBurnData memory feeData ); }
Initializes the governor and guardian roles of the contract as well as the reference to the `perpetualManager` contract governorList List of the governor addresses of the protocol guardian Guardian address of the protocol _perpetualManager `PerpetualManager` contract handling the perpetuals of the pool `GUARDIAN_ROLE` can then directly be granted or revoked by the corresponding `PoolManager` As `POOLMANAGER_ROLE` is admin of `GUARDIAN_ROLE`, it corresponds to the intended behaviour of roles
function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external override onlyRole(POOLMANAGER_ROLE) initializer { for (uint256 i = 0; i < governorList.length; i++) { _grantRole(GUARDIAN_ROLE, governorList[i]); } _grantRole(GUARDIAN_ROLE, guardian); perpetualManager = IPerpetualManager(_perpetualManager); }
10,172,740
./full_match/1/0xDB2DcB4a1dB8C0dc8080042eE5e88002efe5E540/sources/localhost/exchange/SaverExchangeCore.sol
Calls wraper contract for exchage to preform an on-chain swap exData Exchange data struct _wrapper Address of exchange wrapper _type Type of action SELL|BUY return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory exData, address _wrapper, ActionType _type) internal returns (uint swapedTokens) { uint ethValue = 0; if (exData.srcAddr == KYBER_ETH_ADDRESS) { ethValue = exData.srcAmount; ERC20(exData.srcAddr).transfer(_wrapper, ERC20(exData.srcAddr).balanceOf(address(this))); } if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_wrapper). swapedTokens = ExchangeInterfaceV2(_wrapper). } }
2,917,924
./partial_match/42/0xb8D7BF978a166E5D731f381d1E529816Aa9E0879/sources/Treasury.sol
take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); }
3,353,762
/** *Submitted for verification at Etherscan.io on 2021-08-05 */ // Sources flattened with hardhat v2.3.0 https://hardhat.org // File @openzeppelin/contracts/introspection/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/introspection/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File @openzeppelin/contracts/math/[email protected] // 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; } } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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/utils/CountedMap.sol pragma solidity =0.6.2; // Reference counted mapping[address => uint]. library CountedMap { uint256 constant COUNTER_MASK = (1 << 128) - 1; struct Map { // Maps addresses to pair (index, counter) represented as single uint256. mapping(address => uint256) dict; address[] data; } function add(Map storage _map, address _who) internal { uint256 value = _map.dict[_who]; if (value == 0) { _map.data.push(_who); _map.dict[_who] = _map.data.length << 128; } else { _map.dict[_who] = value + 1; } } function remove(Map storage _map, address _who) internal { uint256 value = _map.dict[_who]; if ((value & COUNTER_MASK) == 0) { uint256 index = (value >> 128) - 1; uint256 last = _map.data.length - 1; address moved = _map.data[index] = _map.data[last]; _map.dict[moved] = (_map.dict[moved] & COUNTER_MASK) | ((index + 1) << 128); _map.data.pop(); delete _map.dict[_who]; } else { _map.dict[_who] = value - 1; } } function length(Map storage _map) internal view returns(uint256) { return _map.data.length; } function at(Map storage _map, uint256 index) internal view returns(address) { return _map.data[index]; } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/GravisCollectionMintable.sol pragma solidity =0.6.2; contract GravisCollectionMintable is Context, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "GravisCollectible: must have admin role"); _; } } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/Whitelist.sol pragma solidity =0.6.2; /** * @title Whitelist * @author Alberto Cuesta Canada * @dev Implements a simple whitelist of addresses. */ contract Whitelist is Ownable { event MemberAdded(address member); event MemberRemoved(address member); mapping(address => bool) private members; uint256 public whitelisted; /** * @dev A method to verify whether an address is a member of the whitelist * @param _member The address to verify. * @return Whether the address is a member of the whitelist. */ function isMember(address _member) public view returns (bool) { return members[_member]; } /** * @dev A method to add a member to the whitelist * @param _member The member to add as a member. */ function addMember(address _member) public onlyOwner { address[] memory mem = new address[](1); mem[0] = _member; _addMembers(mem); } /** * @dev A method to add a member to the whitelist * @param _members The members to add as a member. */ function addMembers(address[] memory _members) public onlyOwner { _addMembers(_members); } /** * @dev A method to remove a member from the whitelist * @param _member The member to remove as a member. */ function removeMember(address _member) public onlyOwner { require(isMember(_member), "Whitelist: Not member of whitelist"); delete members[_member]; --whitelisted; emit MemberRemoved(_member); } function _addMembers(address[] memory _members) internal { uint256 l = _members.length; for (uint256 i = 0; i < l; i++) { require(!isMember(_members[i]), "Whitelist: Address is member already"); members[_members[i]] = true; emit MemberAdded(_members[i]); } whitelisted += _members.length; } /** * @dev Access modifier for whitelisted members. */ modifier canParticipate() { require(whitelisted == 0 || isMember(msg.sender), "Seller: not from private list"); _; } } // File contracts/GravisCollectible.sol pragma solidity =0.6.2; /** * @title GravisCollectible - Collectible token implementation, * from Gravis project, based on OpenZeppelin eip-721 implementation. * * @author Darth Andeddu <[email protected]> */ contract GravisCollectible is GravisCollectionMintable, Whitelist, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using CountedMap for CountedMap.Map; // Bitmask size in slots (256 bit words) to fit all NFTs in the round uint256 internal constant VAULT_SIZE_SLOTS = 79; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; struct TokenVault { uint256[VAULT_SIZE_SLOTS] data; } struct TypeData { address minterOnly; string info; uint256 nominalPrice; uint256 totalSupply; uint256 maxSupply; TokenVault vault; string uri; } TypeData[] private typeData; mapping(address => TokenVault) private tokens; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 public last = 0; string public baseURI; CountedMap.Map owners; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract. */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Returns the token collection name. */ function name() external view override returns (string memory) { return "Gravis Finance Captains Collection"; } /** * @dev Returns the token collection symbol. */ function symbol() external view override returns (string memory) { return "GRVSCAPS"; } /** * @dev Returns the number of decimals used to get its user representation. */ function decimals() public pure virtual returns (uint8) { return 0; } /** * @dev Default transfer from ERC20 is not possible so disabled. */ function transfer(address, uint256) public pure virtual returns (bool) { require(false, "This type of token cannot be transferred from this type of wallet"); } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 _tokenId) external view override returns (string memory) { uint256 typ = getTokenType(_tokenId); require(typ != uint256(-1), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI, typeData[typ].uri)); } /** * @dev Returns the balance for the `_who` address. */ function balanceOf(address _who) public view override returns (uint256 res) { TokenVault storage cur = tokens[_who]; for (uint256 index = 0; index < VAULT_SIZE_SLOTS; ++index) { uint256 val = cur.data[index]; while (val != 0) { val &= val - 1; ++res; } } } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address _who, uint256 _index) public view virtual override returns (uint256) { TokenVault storage vault = tokens[_who]; uint256 index = 0; uint256 bit = 0; uint256 cnt = 0; while (true) { uint256 val = vault.data[index]; if (val != 0) { while (bit < 256 && (val & (1 << bit) == 0)) ++bit; } if (val == 0 || bit == 256) { bit = 0; ++index; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: not enough tokens"); continue; } if (cnt == _index) break; ++cnt; ++bit; } return index * 256 + bit; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return last; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { return index; } /** * @dev Returns data about token collection by type id `_typeId`. */ function getTypeInfo(uint256 _typeId) public view returns ( uint256 nominalPrice, uint256 capSupply, uint256 maxSupply, string memory info, address minterOnly, string memory uri ) { TypeData memory t = typeData[_typeId]; return (t.nominalPrice, t.totalSupply, t.maxSupply, t.info, t.minterOnly, t.uri); } /** * @dev Returns token type by token id `_tokenId`. */ function getTokenType(uint256 _tokenId) public view returns (uint256) { if (_tokenId < last) { (uint256 index, uint256 mask) = _position(_tokenId); for (uint256 i = 0; i < typeData.length; ++i) { if (typeData[i].vault.data[index] & mask != 0) return i; } } return uint256(-1); } /** * @dev See {IERC721-approve}. */ function approve(address _to, uint256 _tokenId) public virtual override { require(_to != _msgSender(), "ERC721: approval to current owner"); require(isOwner(_msgSender(), _tokenId), "ERC721: approve caller is not owner"); _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 { 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 See {ERC71-_exists}. */ function exists(uint256 _tokenId) public view returns (bool) { return getTokenType(_tokenId) != uint256(-1); } /** * @dev See {ERC71-_setBaseURI}. */ function setBaseURI(string memory _baseURI) public onlyAdmin { baseURI = _baseURI; } /** * @dev Create new token collection, with uniq id. * * Permission: onlyAdmin * * @param _nominalPrice - nominal price per item, should be set in USD, * with decimal zero * @param _maxTotal - maximum total amount items in collection * @param _info - general information about collection * @param _uri - JSON metadata address based on `baseURI` */ function createNewTokenType( uint256 _nominalPrice, uint256 _maxTotal, string memory _info, string memory _uri ) public onlyAdmin { require(_nominalPrice != 0, "GravisCollectible: nominal price is zero"); TypeData memory t; t.nominalPrice = _nominalPrice; t.maxSupply = _maxTotal; t.info = _info; t.uri = _uri; typeData.push(t); } /** * @dev Setter for lock minter rights by `_minter` and `_type`. * * Permission: onlyAdmin */ function setMinterOnly(address _minter, uint256 _type) external onlyAdmin { require(typeData[_type].minterOnly == address(0), "GravisCollectible: minter locked already"); typeData[_type].minterOnly = _minter; } /** * @dev Add new user with MINTER_ROLE permission. * * Permission: onlyAdmin */ function addMinter(address _newMinter) public onlyAdmin { _setupRole(MINTER_ROLE, _newMinter); } /** * @dev Mint one NFT token to specific address `_to` with specific type id `_type`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function mint( address _to, uint256 _type, uint256 _amount ) public returns (uint256) { require(hasRole(MINTER_ROLE, _msgSender()), "GravisCollectible: must have minter role to mint"); require(_type < typeData.length, "GravisCollectible: type not exist"); TypeData storage currentType = typeData[_type]; if (currentType.minterOnly != address(0)) { require(typeData[_type].minterOnly == _msgSender(), "GravisCollectible: minting locked by another account"); } return _mint(_to, _type, _amount); } function mintFor(address[] calldata _to, uint256[] calldata _amount, uint256 _type) external { require(hasRole(MINTER_ROLE, _msgSender()), "GravisCollectible: must have minter role to mint"); require(_to.length == _amount.length, "GravisCollectible: input arrays don't match"); require(_type < typeData.length, "GravisCollectible: type not exist"); TypeData storage currentType = typeData[_type]; if (currentType.minterOnly != address(0)) { require(typeData[_type].minterOnly == _msgSender(), "GravisCollectible: minting locked by another account"); } for (uint256 i = 0; i < _to.length; ++i) { _mint(_to[i], _type, _amount[i]); } } function _mint( address _to, uint256 _type, uint256 _amount ) internal returns (uint256) { require(_to != address(0), "GravisCollectible: mint to the zero address"); TokenVault storage vaultUser = tokens[_to]; TokenVault storage vaultType = typeData[_type].vault; uint256 tokenId = last; (uint256 index, uint256 mask) = _position(tokenId); uint256 userBuf = vaultUser.data[index]; uint256 typeBuf = vaultType.data[index]; while (tokenId < last.add(_amount)) { userBuf |= mask; typeBuf |= mask; mask <<= 1; if (mask == 0) { mask = 1; vaultUser.data[index] = userBuf; vaultType.data[index] = typeBuf; ++index; userBuf = vaultUser.data[index]; typeBuf = vaultType.data[index]; } emit Transfer(address(0), _to, tokenId); ++tokenId; } last = tokenId; vaultUser.data[index] = userBuf; vaultType.data[index] = typeBuf; typeData[_type].totalSupply = typeData[_type].totalSupply.add(_amount); owners.add(_to); require(typeData[_type].totalSupply <= typeData[_type].maxSupply, "GravisCollectible: max supply reached"); return last; } /** * @dev Moves one NFT token to specific address `_to` with specific token id `_tokenId`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFromContract(address _to, uint256 _tokenId) public onlyAdmin returns (bool) { _transfer(address(this), _to, _tokenId); return true; } /** * @dev Returns address of the caller if the token `_tokenId` belongs to her, 0 otherwise. */ function ownerOf(uint256 _tokenId) public view override returns (address) { (uint256 index, uint256 mask) = _position(_tokenId); if (tokens[_msgSender()].data[index] & mask != 0) return _msgSender(); for (uint256 i = 0; i < owners.length(); ++i) { address candidate = owners.at(i); if (tokens[candidate].data[index] & mask != 0) return candidate; } return address(0); } /** * @dev Returns true if `_who` owns token `_tokenId`. */ function isOwner(address _who, uint256 _tokenId) public view returns (bool) { (uint256 index, uint256 mask) = _position(_tokenId); return tokens[_who].data[index] & mask != 0; } function ownersLength() public view returns (uint256) { return owners.length(); } function ownerAt(uint256 _index) public view returns (address) { return owners.at(_index); } /** * @dev See {ERC71-_burn}. */ function burn(uint256 _tokenId) public { _burnFor(_msgSender(), _tokenId); } /** * @dev Burn `_amount` tokens ot type `_type` for account `_who`. */ function burnFor( address _who, uint256 _type, uint256 _amount ) public { require(_who == _msgSender() || isApprovedForAll(_who, _msgSender()), "GravisCollectible: must have approval"); require(_type < typeData.length, "GravisCollectible: type not exist"); TokenVault storage vaultUser = tokens[_who]; TokenVault storage vaultType = typeData[_type].vault; uint256 index = 0; uint256 burned = 0; uint256 userBuf; uint256 typeBuf; while (burned < _amount) { while (index < VAULT_SIZE_SLOTS && vaultUser.data[index] == 0) ++index; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: not enough tokens"); userBuf = vaultUser.data[index]; typeBuf = vaultType.data[index]; uint256 bit = 0; while (burned < _amount) { while (bit < 256) { uint256 mask = 1 << bit; if (userBuf & mask != 0 && typeBuf & mask != 0) break; ++bit; } if (bit == 256) { vaultUser.data[index] = userBuf; vaultType.data[index] = typeBuf; ++index; break; } uint256 tokenId = index * 256 + bit; _approve(address(0), tokenId); uint256 mask = ~(1 << bit); userBuf &= mask; typeBuf &= mask; emit Transfer(_who, address(0), tokenId); ++burned; } } vaultUser.data[index] = userBuf; vaultType.data[index] = typeBuf; owners.remove(_who); } /** * @dev Transfer `_amount` tokens ot type `_type` between accounts `_from` and `_to`. */ function transferFor( address _from, address _to, uint256 _type, uint256 _amount ) public { require(_from == _msgSender() || isApprovedForAll(_from, _msgSender()), "GravisCollectible: must have approval"); require(_type < typeData.length, "GravisCollectible: type not exist"); TokenVault storage vaultFrom = tokens[_from]; TokenVault storage vaultTo = tokens[_to]; TokenVault storage vaultType = typeData[_type].vault; uint256 index = 0; uint256 transfered = 0; uint256 fromBuf; uint256 toBuf; while (transfered < _amount) { while (index < VAULT_SIZE_SLOTS && vaultFrom.data[index] == 0) ++index; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: not enough tokens"); fromBuf = vaultFrom.data[index]; toBuf = vaultTo.data[index]; uint256 bit = 0; while (transfered < _amount) { while (bit < 256) { uint256 mask = 1 << bit; if (fromBuf & mask != 0 && vaultType.data[index] & mask != 0) break; ++bit; } if (bit == 256) { vaultFrom.data[index] = fromBuf; vaultTo.data[index] = toBuf; ++index; break; } uint256 tokenId = index * 256 + bit; _approve(address(0), tokenId); uint256 mask = 1 << bit; toBuf |= mask; fromBuf &= ~mask; emit Transfer(_from, _to, tokenId); ++transfered; } } vaultFrom.data[index] = fromBuf; vaultTo.data[index] = toBuf; owners.add(_to); owners.remove(_from); } /** * @dev Approve `_to` to operate on `_tokenId` * * Emits an {Approval} event. */ function _approve(address _to, uint256 _tokenId) internal virtual { if (_tokenApprovals[_tokenId] != _to) { _tokenApprovals[_tokenId] = _to; emit Approval(_msgSender(), _to, _tokenId); // internal owner } } /** * @dev Burn a single token `_tokenId` for address `_who`. */ function _burnFor(address _who, uint256 _tokenId) internal virtual { (uint256 index, uint256 mask) = _position(_tokenId); require(tokens[_who].data[index] & mask != 0, "not owner"); _approve(address(0), _tokenId); mask = ~mask; tokens[_who].data[index] &= mask; for (uint256 i = 0; i < typeData.length; ++i) { typeData[i].vault.data[index] &= mask; } owners.remove(_who); emit Transfer(_who, address(0), _tokenId); } /** * @dev Transfers `_tokenId` from `_from` to `_to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Emits a {Transfer} event. */ function _transfer( address _from, address _to, uint256 _tokenId ) internal virtual { require(isOwner(_from, _tokenId), "ERC721: transfer of token that is not own"); // internal owner require(_to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), _tokenId); (uint256 index, uint256 mask) = _position(_tokenId); tokens[_from].data[index] &= ~mask; tokens[_to].data[index] |= mask; owners.add(_to); owners.remove(_from); emit Transfer(_from, _to, _tokenId); } /** * @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`. * * 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 Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address _from, address _to, uint256 _tokenId, bytes memory _data ) private returns (bool) { if (!_to.isContract()) { return true; } bytes memory returndata = _to.functionCall( abi.encodeWithSelector( IERC721Receiver(_to).onERC721Received.selector, _msgSender(), _from, _tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Returns whether `_spender` is allowed to manage `_tokenId`. */ function _isApprovedOrOwner(address _spender, uint256 _tokenId) internal view virtual returns (bool) { if (isOwner(_spender, _tokenId)) return true; return (getApproved(_tokenId) == _spender || isApprovedForAll(ownerOf(_tokenId), _spender)); } function _position(uint256 _tokenId) internal pure returns (uint256 index, uint256 mask) { index = _tokenId / 256; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: OOB"); mask = uint256(1 << (_tokenId % 256)); } }
See {IERC721-safeTransferFrom}./
function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public virtual override { safeTransferFrom(_from, _to, _tokenId, ""); }
10,668,568
pragma solidity 0.4.24; pragma experimental "v0.5.0"; import "../Math/SafeMath.sol"; import "../Interfaces/RTCoinInterface.sol"; /// @title Merged Miner Validator allows people who mine mainnet Ethereum blocks to also mint RTC /// @author Postables, RTrade Technologies Ltd /// @notice Version 1, future versions will require a non-interactive block submissinon method /// @dev We able V5 for safety features, see https://solidity.readthedocs.io/en/v0.4.24/security-considerations.html#take-warnings-seriously contract MergedMinerValidator { using SafeMath for uint256; // 0.5 uint256 constant public SUBMISSIONREWARD = 500000000000000000; // 0.3 uint256 constant public BLOCKREWARD = 300000000000000000; address public tokenAddress; address public admin; uint256 public lastBlockSet; RTCoinInterface public rtI; enum BlockStateEnum { nil, submitted, claimed } struct Blocks { uint256 number; address coinbase; BlockStateEnum state; } mapping (uint256 => Blocks) public blocks; mapping (uint256 => bytes) public hashedBlocks; event BlockInformationSubmitted(address indexed _coinbase, uint256 indexed _blockNumber, address _submitter); event MergedMinedRewardClaimed(address indexed _claimer, uint256[] indexed _blockNumbers, uint256 _totalReward); modifier submittedBlock(uint256 _blockNum) { require(blocks[_blockNum].state == BlockStateEnum.submitted); _; } modifier nonSubmittedBlock(uint256 _blockNum) { require(blocks[_blockNum].state == BlockStateEnum.nil); _; } modifier isCoinbase(uint256 _blockNumber) { require(msg.sender == blocks[_blockNumber].coinbase); _; } modifier unclaimed(uint256 _blockNumber) { require(blocks[_blockNumber].state == BlockStateEnum.submitted); _; } modifier canMint() { require(rtI.mergedMinerValidatorAddress() == address(this)); _; } modifier notCurrentSetBlock(uint256 _blockNumber) { require(_blockNumber > lastBlockSet, "unable to submit information for already submitted block"); _; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier tokenAddressNotSet() { require(tokenAddress == address(0), "token address must not be set"); _; } constructor() public { admin = msg.sender; Blocks memory b = Blocks({ number: block.number, coinbase: block.coinbase, state: BlockStateEnum.submitted }); lastBlockSet = block.number; blocks[block.number] = b; // we use address(0) and don't mint any tokens, since "we are submitting the information" emit BlockInformationSubmitted(block.coinbase, block.number, address(0)); } /** @notice Used to submit block hash, and block miner information for the current block * @dev Future iterations will avoid this process entirely, and use RLP encoded block headers to parse the data. */ function submitBlock() public nonSubmittedBlock(block.number) notCurrentSetBlock(block.number) returns (bool) { Blocks memory b = Blocks({ number: block.number, coinbase: block.coinbase, state: BlockStateEnum.submitted }); lastBlockSet = block.number; blocks[block.number] = b; // lets not do a storage lookup so we can avoid SSLOAD gas usage emit BlockInformationSubmitted(block.coinbase, block.number, msg.sender); require(rtI.mint(msg.sender, SUBMISSIONREWARD), "failed to transfer reward to block submitter"); return true; } /** @notice Used by a miner to claim their merged mined RTC * @param _blockNumber The block number of the block that the person mined */ function claimReward(uint256 _blockNumber) internal isCoinbase(_blockNumber) unclaimed(_blockNumber) submittedBlock(_blockNumber) returns (uint256) { // mark the reward as claimed blocks[_blockNumber].state = BlockStateEnum.claimed; return BLOCKREWARD; } /** @notice Used by a miner to bulk claim their merged mined RTC * @dev To prevent expensive looping, we throttle to 20 withdrawals at once * @param _blockNumbers Contains the block numbers for which they want to claim */ function bulkClaimReward(uint256[] _blockNumbers) external canMint returns (bool) { require(_blockNumbers.length <= 20, "can only claim up to 20 rewards at once"); uint256 totalMint; for (uint256 i = 0; i < _blockNumbers.length; i++) { // update their total amount minted totalMint = totalMint.add(claimReward(_blockNumbers[i])); // make sure the block was marked as claimed require(blocks[_blockNumbers[i]].state == BlockStateEnum.claimed, "block state is not claimed"); } emit MergedMinedRewardClaimed(msg.sender, _blockNumbers, totalMint); // make sure more than 0 is being claimed require(totalMint > 0, "total coins to mint must be greater than 0"); require(rtI.mint(msg.sender, totalMint), "unable to mint tokens"); return true; } /** @notice Used to set the RTC token address and interface * @param _tokenAddress This is the address of the RTC token contract */ function setRTI(address _tokenAddress) public onlyAdmin tokenAddressNotSet returns (bool) { tokenAddress = _tokenAddress; rtI = RTCoinInterface(_tokenAddress); return true; } /** @notice Used to destroy the contract */ function goodNightSweetPrince() public onlyAdmin returns (bool) { selfdestruct(msg.sender); return true; } }
Used to submit block hash, and block miner information for the current block Future iterations will avoid this process entirely, and use RLP encoded block headers to parse the data./
function submitBlock() public nonSubmittedBlock(block.number) notCurrentSetBlock(block.number) returns (bool) { Blocks memory b = Blocks({ number: block.number, coinbase: block.coinbase, state: BlockStateEnum.submitted }); lastBlockSet = block.number; blocks[block.number] = b; require(rtI.mint(msg.sender, SUBMISSIONREWARD), "failed to transfer reward to block submitter"); return true; }
6,484,929
./full_match/40/0x4b7CfCB288D811cF68d32d1abcE3c621ed69Dce0/sources/src/Libraries/LibFees.sol
solhint-disable-next-line no-inline-assembly
function feesStorage() internal pure returns (FeesStorage storage fs) { bytes32 position = FFES_STORAGE_POSITION; assembly { fs.slot := position } }
9,541,978
pragma solidity ^0.4.2; import "./helper_contracts/strings.sol"; import "./helper_contracts/MediaLib.sol"; contract MediaStore { using MediaLib for *; using strings for *; mapping (address => MediaLib.User) private userList; mapping (string => MediaLib.Media) private mediaList; mapping (string => MediaLib.Tag) private tagList; mapping (address => mapping(string => MediaLib.Playlist)) private userPlayList; MediaLib.Tag tagObj; MediaLib.Media mediaObj; MediaLib.User userObj; MediaLib.Playlist playListObj; string [] tagIdsList; modifier checkUserExists(){ //check if user exist or not, if not create user. if(!userList[msg.sender].exists) createUser(); _; } modifier checkIfValue(){ //check if some ether is passed or not require(msg.value >0); _; } //user function createUser() public { userObj = MediaLib.User({ exists : true, mediaCount : 0, playlistIds : new string[](0) }); userObj.playlistIds.push("Default"); //if playlist is not specified, then "Default" userList[msg.sender] = userObj; } //Check if user exisits or not function getUser(address userAddress) public view returns (bool isUserExists) { return userList[userAddress].exists; } //Createing playlist function createPlaylist(string playListId) public{ require(!userPlayList[msg.sender][playListId].exists); playListObj = MediaLib.Playlist({ id : playListId, mediaIds : new string[](0), mediaCount : 0, exists : true }); userPlayList[msg.sender][playListId] = playListObj; //updating user's playlistids array object with playList userList[msg.sender].playlistIds.push(playListId); } //get all playlists of a userObj function getUserPlaylist(address userAddr) public view returns(uint256 count,string allPlaylistIds) { require(userList[userAddr].exists); count = userList[userAddr].playlistIds.length; allPlaylistIds = convertArrayToString(userList[userAddr].playlistIds); } //adding a new MediaLib //tagsString format : t1|t2|t3 function addMedia(string playlistId, string mediaHash,string tagString)public checkUserExists checkIfValue{ bytes memory mediaHashTemp = bytes(mediaHash); bytes memory tagStringTemp = bytes(tagString); //passed parameters are blank, check if new media require(mediaHashTemp.length > 0 && tagStringTemp.length > 0); string memory playListTemp = getConvertedPlayListId(playlistId); //if playlist does not exists then create if(!userPlayList[msg.sender][playListTemp].exists){ //Call to Create playListTemp createPlaylist(playListTemp); } if(!mediaList[mediaHash].exists){ //spliting tagSring, iterating over and preparing tag array //TODO : can be optimised later var tagSlice = tagString.toSlice(); string [] tempTagArr; uint256 tagSliceCount = tagSlice.count("|".toSlice()) + 1; for (uint i = 0; i < tagSliceCount; i++) { var t = tagSlice.split("|".toSlice()); tempTagArr.push(t.toString()); //Get tag object from tagList if(tagList[t.toString()].exists){ //if tag is already present, update mediaHash to the array present in the existing tag object tagList[t.toString()].mediaIds.push(mediaHash); tagList[t.toString()].mediaCount = tagList[t.toString()].mediaCount+1; }else{ //if tag not present, create new tag object and store into taglist tagObj = MediaLib.Tag({ id : t.toString(), exists : true, mediaIds : new string[](0), mediaCount: 1 }); tagObj.mediaIds.push(mediaHash); tagList[t.toString()] = tagObj; tagIdsList.push(t.toString()); } } //Creating media object mediaObj = MediaLib.Media({ creatorAddress : msg.sender, tags : tempTagArr, claps : 0, id: mediaHash, exists : true }); //storing new media into mapping mediaList[mediaHash] = mediaObj; }else{ string [] playListMedias = userPlayList[msg.sender][playListTemp].mediaIds; for(uint32 j = 0;j< playListMedias.length ; j++){ if(keccak256(playListMedias[j]) == keccak256(mediaHash)) { revert(); }else{ continue; } } } //fetch playlist for this user and update the mediahash array userPlayList[msg.sender][playListTemp].mediaIds.push(mediaHash); userPlayList[msg.sender][playListTemp].mediaCount += userPlayList[msg.sender][playListTemp].mediaCount; } function getMediaListByUser(string playListId) public view returns(uint256 count, string allMediaIds){ string memory playListTemp = getConvertedPlayListId(playListId); require(userPlayList[msg.sender][playListTemp].exists); count = userPlayList[msg.sender][playListTemp].mediaIds.length; allMediaIds = convertArrayToString(userPlayList[msg.sender][playListTemp].mediaIds); } function getConvertedPlayListId(string playlistId) private returns(string) { string memory playListTemp = "Default"; bytes memory playlistIdTemp = bytes(playlistId); //Playlist if(playlistIdTemp.length >0){ playListTemp = playlistId; } return playListTemp; } //Get media details by hash function getMediaDetByHash(string mediaHash) public view returns(address creatorAddress, string allTags, uint32 claps){ //check if media exisit or not require(mediaList[mediaHash].exists); creatorAddress = mediaList[mediaHash].creatorAddress; string [] storage tagArr = mediaList[mediaHash].tags; allTags = convertArrayToString(tagArr); claps = mediaList[mediaHash].claps; } //Get all tags present function getTags() public view returns (uint256 count, string allTags) { allTags = convertArrayToString(tagIdsList); count = tagIdsList.length; } //Get mediaHashs of a tag function getMediaHashesByTag(string tag)public view returns(uint256 count,string allHashes){ require(tagList[tag].exists); count = tagList[tag].mediaCount; allHashes = convertArrayToString(tagList[tag].mediaIds); } function clap(address creatorAddress, string mediaHash, uint32 clapCount) public payable checkIfValue{ //check if media exisit or not require(mediaList[mediaHash].exists); //check creator is present in the userlist require(userList[creatorAddress].exists); //increase the claps count and transfer the ether to creator mediaList[mediaHash].claps = mediaList[mediaHash].claps + clapCount; creatorAddress.transfer(msg.value); } //helper method to convert all values of an array in pipe separated function convertArrayToString(string []arr) internal pure returns(string arrConvertedToStr){ var parts = new strings.slice[](arr.length); for (uint32 i = 0; i < arr.length; i++) { parts[i] =arr[i].toSlice(); } arrConvertedToStr = "|".toSlice().join(parts); } }
Get all tags present
function getTags() public view returns (uint256 count, string allTags) { allTags = convertArrayToString(tagIdsList); count = tagIdsList.length; }
12,876,342
./full_match/80001/0x163ea9e95d73cF029cD968Bd0a2Be9F1a82f6376/sources/contracts/MedicalHealthContract.sol
Return a default value for review (0) since it is not stored in the struct
function getDoctorReview(string memory doctorName) external view returns (uint256) { Doctor storage selectedDoctor = doctors[doctorName]; require(bytes(selectedDoctor.name).length > 0, "Doctor not found."); return 0; }
837,238
//Address: 0xB4e4a785de5A9cAEfAD3912A1344fEbF04c7d2aC //Contract name: ArtSale //Balance: 0 Ether //Verification Date: 7/19/2017 //Transacion Count: 23 // CODE STARTS HERE pragma solidity ^0.4.11; /** * Controller */ contract Controller { /// @notice Called when `_owner` sends ether to the 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); } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /** * @title Contracts that should not own Tokens * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is Ownable { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ Uint the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint value_, bytes data_) external { throw; } /** * @dev Reclaim all ERC20Basic compatible tokens * @param tokenAddr address The address of the token contract */ function reclaimToken(address tokenAddr) external onlyOwner { ERC20Basic tokenInst = ERC20Basic(tokenAddr); uint256 balance = tokenInst.balanceOf(this); tokenInst.transfer(owner, balance); } } // @dev Contract to hold ETH raised during a token sale. // Prevents attack in which the Multisig sends raised ether to the // sale contract to mint tokens to itself, and getting the // funds back immediately. contract AbstractSale { function saleFinalized() constant returns (bool); } contract Escrow is HasNoTokens { address public beneficiary; uint public finalBlock; AbstractSale public tokenSale; // @dev Constructor initializes public variables // @param _beneficiary The address of the multisig that will receive the funds // @param _finalBlock Block after which the beneficiary can request the funds function Escrow(address _beneficiary, uint _finalBlock, address _tokenSale) { beneficiary = _beneficiary; finalBlock = _finalBlock; tokenSale = AbstractSale(_tokenSale); } // @dev Receive all sent funds without any further logic function() public payable {} // @dev Withdraw function sends all the funds to the wallet if conditions are correct function withdraw() public { if (msg.sender != beneficiary) throw; if (block.number > finalBlock) return doWithdraw(); if (tokenSale.saleFinalized()) return doWithdraw(); } function doWithdraw() internal { if (!beneficiary.send(this.balance)) throw; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping (address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint 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) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart 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 BasicToken, ERC20 { mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * Controlled */ contract Controlled { address public controller; function Controlled() { controller = msg.sender; } function changeController(address _controller) onlyController { controller = _controller; } modifier onlyController { if (msg.sender != controller) throw; _; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation */ contract MintableToken is StandardToken, Controlled { event Mint(address indexed to, uint value); event MintFinished(); bool public mintingFinished = false; uint public totalSupply = 0; /** * @dev Function to mint tokens * @param _to The address that will recieve 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, uint _amount) onlyController canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyController returns (bool) { mintingFinished = true; MintFinished(); return true; } modifier canMint() { if (mintingFinished) throw; _; } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint _value) { if (_value > transferableTokens(_sender, uint64(now))) throw; _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint _value) canTransfer(msg.sender, _value) { super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) { super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { return balanceOf(holder); } } /** * @title Vested token * @dev Tokens that can be vested for a group of addresses. */ contract VestedToken is StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. * @param _revokable bool If the grant is revokable. * @param _burnsOnRevoke bool When true, the tokens are burned if revoked. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior if (_cliff < _start || _vesting < _cliff) { throw; } if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) throw; // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, count - 1); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint _grantId) public { TokenGrant grant = grants[_holder][_grantId]; if (!grant.revokable) { // Check if grant was revokable throw; } if (grant.granter != msg.sender) { // Only granter can revoke it throw; } address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint representing a holder's total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = nonVested.add(nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = balanceOf(holder).sub(nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint representing the total amount of grants. */ function tokenGrantsCount(address _holder) constant returns (uint index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . |(grants[_holder] == address(0)) return 0; * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) constant returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = tokens.mul(time.sub(start)).div(vesting.sub(start)); return vestedTokens; } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = SafeMath.max64(grants[holder][i].vesting, date); } } } /// @title Artcoin (ART) - democratizing culture. contract Artcoin is MintableToken, VestedToken { string public constant name = 'Artcoin'; string public constant symbol = 'ART'; uint public constant decimals = 18; function() public payable { if (isContract(controller)) { if (!Controller(controller).proxyPayment.value(msg.value)(msg.sender)) throw; } else { throw; } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size > 0; } } /// @title Artcoin Placeholder - democratizing culture. contract ArtcoinPlaceholder is Controller { Artcoin public token; address public tokenSale; function ArtcoinPlaceholder(address _token, address _tokenSale) { token = Artcoin(_token); tokenSale = _tokenSale; } function changeController(address consortium) public { if (msg.sender != tokenSale) throw; token.changeController(consortium); suicide(consortium); } function proxyPayment(address _owner) payable public returns (bool) { throw; return false; } function onTransfer(address _from, address _to, uint _amount) public returns (bool) { return true; } function onApprove(address _owner, address _spender, uint _amount) public returns (bool) { return true; } } /// @title ART Sale - democratizing culture. contract ArtSale is Controller { using SafeMath for uint; address public manager; address public operations; ArtcoinPlaceholder public consortiumPlaceholder; Artcoin public token; Escrow public escrow; uint public initialBlock; // block number in which the sale starts, inclusive. sale will be opened at initial block. uint public finalBlock; // block number in which the sale ends, exclusive, sale will be closed at ends block. uint public initialPrice; // number of wei-Artcoin tokens for 1 wei, at the start of the sale (18 decimals) uint public finalPrice; // number of wei-Artcoin tokens for 1 wei, at the end of the sale uint public priceStages; // number of different price stages for interpolating between initialPrice and finalPrice uint public maximumSubscription; // maximum subscriptions, in wei uint public totalSubscription = 0; // total subscriptions, in wei mapping (address => bool) public activations; // confirmations to activate the sale mapping (address => uint) public subscriptions; // subscriptions uint constant public dust = 1 finney; // minimum investment bool public saleStopped = false; bool public saleFinalized = false; event NewPresaleAllocation(address indexed holder, uint amount); event NewSubscription(address indexed holder, uint amount, uint etherAmount); function ArtSale(address _manager, address _operations, uint _initialBlock, uint _finalBlock, uint256 _initialPrice, uint256 _finalPrice, uint8 _priceStages, uint _maximumSubscription) nonZeroAddress(_operations) { if (_initialBlock < getBlockNumber()) throw; if (_initialBlock >= _finalBlock) throw; if (_initialPrice <= _finalPrice) throw; if (_priceStages < 2) throw; if (_priceStages > _initialPrice - _finalPrice) throw; manager = _manager; operations = _operations; maximumSubscription = _maximumSubscription; initialBlock = _initialBlock; finalBlock = _finalBlock; initialPrice = _initialPrice; finalPrice = _finalPrice; priceStages = _priceStages; } // @notice Set Artcoin token and escrow address. // @param _token: Address of an instance of the Artcoin token // @param _consortiumPlaceholder: Address of the consortium placeholder // @param _escrow: Address of the wallet receiving the funds of the sale function setArtcoin(address _token, address _consortiumPlaceholder, address _escrow) nonZeroAddress(_token) nonZeroAddress(_consortiumPlaceholder) nonZeroAddress(_escrow) public { if (activations[this]) throw; token = Artcoin(_token); consortiumPlaceholder = ArtcoinPlaceholder(_consortiumPlaceholder); escrow = Escrow(_escrow); if (token.controller() != address(this)) throw; // sale is token controller if (token.totalSupply() > 0) throw; // token is empty if (consortiumPlaceholder.tokenSale() != address(this)) throw; // placeholder has reference to sale if (consortiumPlaceholder.token() != address(token)) throw; // placeholder has reference to ART if (escrow.finalBlock() != finalBlock) throw; // final blocks must match if (escrow.beneficiary() != operations) throw; // receiving wallet must match if (escrow.tokenSale() != address(this)) throw; // watched token sale must be self doActivateSale(this); } // @notice Certain addresses need to call the activate function prior to the sale opening block. // This proves that they have checked the sale contract is legit, as well as proving // the capability for those addresses to interact with the contract. function activateSale() public { doActivateSale(msg.sender); } function doActivateSale(address _entity) nonZeroAddress(token) onlyBeforeSale private { activations[_entity] = true; } // @notice Whether the needed accounts have activated the sale. // @return Is sale activated function isActivated() constant public returns (bool) { return activations[this] && activations[operations]; } // @notice Get the price for a Artcoin token at any given block number // @param _blockNumber the block for which the price is requested // @return Number of wei-Artcoin for 1 wei // If sale isn't ongoing for that block, returns 0. function getPrice(uint _blockNumber) constant public returns (uint) { if (_blockNumber < initialBlock || _blockNumber >= finalBlock) return 0; return priceForStage(stageForBlock(_blockNumber)); } // @notice Get what the stage is for a given blockNumber // @param _blockNumber: Block number // @return The sale stage for that block. Stage is between 0 and (priceStages - 1) function stageForBlock(uint _blockNumber) constant internal returns (uint) { uint blockN = _blockNumber.sub(initialBlock); uint totalBlocks = finalBlock.sub(initialBlock); return priceStages.mul(blockN).div(totalBlocks); } // @notice Get what the price is for a given stage // @param _stage: Stage number // @return Price in wei for that stage. // If sale stage doesn't exist, returns 0. function priceForStage(uint _stage) constant internal returns (uint) { if (_stage >= priceStages) return 0; uint priceDifference = initialPrice.sub(finalPrice); uint stageDelta = priceDifference.div(uint(priceStages - 1)); return initialPrice.sub(uint(_stage).mul(stageDelta)); } // @notice Artcoin needs to make initial token allocations for presale partners // This allocation has to be made before the sale is activated. Activating the // sale means no more arbitrary allocations are possible and expresses conformity. // @param _recipient: The receiver of the tokens // @param _amount: Amount of tokens allocated for receiver. function allocatePresaleTokens(address _recipient, uint _amount, uint64 cliffDate, uint64 vestingDate, bool revokable, bool burnOnRevocation) onlyBeforeSaleActivation onlyBeforeSale nonZeroAddress(_recipient) only(operations) public { token.grantVestedTokens(_recipient, _amount, uint64(now), cliffDate, vestingDate, revokable, burnOnRevocation); NewPresaleAllocation(_recipient, _amount); } /// @dev The fallback function is called when ether is sent to the contract, it /// simply calls `doPayment()` with the address that sent the ether as the /// `_subscriber`. Payable is a required solidity modifier for functions to receive /// ether, without this modifier functions will throw if ether is sent to them function() public payable { return doPayment(msg.sender); } /// @dev `doPayment()` is an internal function that sends the ether that this /// contract receives to escrow and creates tokens in the address of the /// @param _subscriber The address that will hold the newly created tokens function doPayment(address _subscriber) onlyDuringSalePeriod onlySaleNotStopped onlySaleActivated nonZeroAddress(_subscriber) minimumValue(dust) internal { if (totalSubscription + msg.value > maximumSubscription) throw; // throw if maximum subscription exceeded uint purchasedTokens = msg.value.mul(getPrice(getBlockNumber())); // number of purchased tokens if (!escrow.send(msg.value)) throw; // escrow funds if (!token.mint(_subscriber, purchasedTokens)) throw; // deliver tokens subscriptions[_subscriber] = subscriptions[_subscriber].add(msg.value); totalSubscription = totalSubscription.add(msg.value); NewSubscription(_subscriber, purchasedTokens, msg.value); } // @notice Function to stop sale before the sale period ends // @dev Only operations is authorized to call this method function stopSale() onlySaleActivated onlySaleNotStopped only(operations) public { saleStopped = true; } // @notice Function to restart stopped sale // @dev Only operations is authorized to call this method function restartSale() onlyDuringSalePeriod onlySaleStopped only(operations) public { saleStopped = false; } // @notice Finalizes sale and distributes Artcoin to purchasers and releases payments // @dev Transfers the token controller power to the consortium. function finalizeSale() onlyAfterSale only(operations) public { doFinalizeSale(); } function doFinalizeSale() internal { uint purchasedTokens = token.totalSupply(); uint advisorTokens = purchasedTokens * 5 / 100; // mint 5% of purchased for advisors if (!token.mint(operations, advisorTokens)) throw; uint managerTokens = purchasedTokens * 25 / 100; // mint 25% of purchased for manager if (!token.mint(manager, managerTokens)) throw; token.changeController(consortiumPlaceholder); saleFinalized = true; saleStopped = true; } // @notice Deploy Artcoin Consortium contract // @param consortium: The address the consortium was deployed at. function deployConsortium(address consortium) onlyFinalizedSale nonZeroAddress(consortium) only(operations) public { consortiumPlaceholder.changeController(consortium); } function setOperations(address _operations) nonZeroAddress(_operations) only(operations) public { operations = _operations; } function getBlockNumber() constant internal returns (uint) { return block.number; } function saleFinalized() constant returns (bool) { return saleFinalized; } function proxyPayment(address _owner) payable public returns (bool) { doPayment(_owner); return true; } /// @notice Notifies the controller about a transfer /// @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) public returns (bool) { // Until the sale is finalized, only allows transfers originated by the sale contract. // When finalizeSale is called, this function will stop being called and will always be true. return _from == address(this); } /// @notice Notifies the controller about an approval /// @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) public returns (bool) { return false; } modifier only(address x) { if (msg.sender != x) throw; _; } modifier onlyBeforeSale { if (getBlockNumber() >= initialBlock) throw; _; } modifier onlyDuringSalePeriod { if (getBlockNumber() < initialBlock) throw; if (getBlockNumber() >= finalBlock) throw; _; } modifier onlyAfterSale { if (getBlockNumber() < finalBlock) throw; _; } modifier onlySaleStopped { if (!saleStopped) throw; _; } modifier onlySaleNotStopped { if (saleStopped) throw; _; } modifier onlyBeforeSaleActivation { if (isActivated()) throw; _; } modifier onlySaleActivated { if (!isActivated()) throw; _; } modifier onlyFinalizedSale { if (getBlockNumber() < finalBlock) throw; if (!saleFinalized) throw; _; } modifier nonZeroAddress(address x) { if (x == 0) throw; _; } modifier minimumValue(uint256 x) { if (msg.value < x) throw; _; } }
Finalizes sale and distributes Artcoin to purchasers and releases payments Transfers the token controller power to the consortium.
function finalizeSale() onlyAfterSale only(operations) public { doFinalizeSale(); }
6,463,515
./partial_match/3/0xBB9dAB0ecb218ad758453E3e4d7c06BDF72754DC/sources/Users/erinshaben/Work/box-project/contracts/ArrayContract.sol
if the new size is smaller, removed array elements will be cleared
function changeFlagArraySize(uint256 newSize) public { m_pairsOfFlags.length = newSize; }
5,272,668
//Address: 0xdea2bc436d38d4f8ee6f9e63b63b72a399c24e2c //Contract name: VLBCrowdsale //Balance: 0 Ether //Verification Date: 12/16/2017 //Transacion Count: 822 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { 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 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; if (a != 0 && c / a != b) revert(); 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) { if (b > a) revert(); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; if (c < a) revert(); return c; } } contract VLBBonusStore is Ownable { mapping(address => uint8) public rates; function collectRate(address investor) onlyOwner public returns (uint8) { require(investor != address(0)); uint8 rate = rates[investor]; if (rate != 0) { delete rates[investor]; } return rate; } function addRate(address investor, uint8 rate) onlyOwner public { require(investor != address(0)); rates[investor] = rate; } } contract VLBRefundVault is Ownable { using SafeMath for uint256; enum State {Active, Refunding, Closed} State public state; mapping (address => uint256) public deposited; address public wallet; event Closed(); event FundsDrained(uint256 weiAmount); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function VLBRefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function unhold() onlyOwner public { require(state == State.Active); FundsDrained(this.balance); wallet.transfer(this.balance); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); FundsDrained(this.balance); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } interface Token { function transferFrom(address from, address to, uint256 value) public returns (bool); function tokensWallet() public returns (address); } /** * @title VLBCrowdsale * @dev VLB crowdsale contract borrows Zeppelin Finalized, Capped and Refundable crowdsales implementations */ contract VLBCrowdsale is Ownable { using SafeMath for uint; /** * @dev escrow address */ address public escrow; /** * @dev token contract */ Token public token; /** * @dev refund vault used to hold funds while crowdsale is running */ VLBRefundVault public vault; /** * @dev refund vault used to hold funds while crowdsale is running */ VLBBonusStore public bonuses; /** * @dev tokensale start time: Dec 17, 2017 12:00:00 UTC (1513512000) */ uint startTime = 1513512000; /** * @dev tokensale end time: Apr 09, 2018 12:00:00 UTC (1523275200) */ uint endTime = 1523275200; /** * @dev minimum purchase amount for presale */ uint256 public constant MIN_SALE_AMOUNT = 5 * 10**17; // 0.5 ether /** * @dev minimum and maximum amount of funds to be raised in USD */ uint256 public constant USD_GOAL = 4 * 10**6; // $4M uint256 public constant USD_CAP = 12 * 10**6; // $12M /** * @dev amount of raised money in wei */ uint256 public weiRaised; /** * @dev tokensale finalization flag */ bool public isFinalized = false; /** * @dev tokensale pause flag */ bool public paused = false; /** * @dev refunding satge flag */ bool public refunding = false; /** * @dev min cap reach flag */ bool public isMinCapReached = false; /** * @dev ETH x USD exchange rate */ uint public ETHUSD; /** * @dev event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @dev event for tokensale final logging */ event Finalized(); /** * @dev event for tokensale pause logging */ event Pause(); /** * @dev event for tokensale uppause logging */ event Unpause(); /** * @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 Modifier to make a function callable only when its called by escrow. */ modifier onlyEscrow() { require(msg.sender == escrow); _; } /** * @dev Crowdsale in the constructor takes addresses of * the just deployed VLBToken and VLBRefundVault contracts * @param _tokenAddress address of the VLBToken deployed contract */ function VLBCrowdsale(address _tokenAddress, address _wallet, address _escrow, uint rate) public { require(_tokenAddress != address(0)); require(_wallet != address(0)); require(_escrow != address(0)); escrow = _escrow; // Set initial exchange rate ETHUSD = rate; // VLBTokenwas deployed separately token = Token(_tokenAddress); vault = new VLBRefundVault(_wallet); bonuses = new VLBBonusStore(); } /** * @dev fallback function can be used to buy tokens */ function() public payable { buyTokens(msg.sender); } /** * @dev main function to buy tokens * @param beneficiary target wallet for tokens can vary from the sender one */ function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != address(0)); require(validPurchase(msg.value)); uint256 weiAmount = msg.value; // buyer and beneficiary could be two different wallets address buyer = msg.sender; weiRaised = weiRaised.add(weiAmount); // calculate token amount to be created uint256 tokens = weiAmount.mul(getConversionRate()); uint8 rate = bonuses.collectRate(beneficiary); if (rate != 0) { tokens = tokens.mul(rate).div(100); } if (!token.transferFrom(token.tokensWallet(), beneficiary, tokens)) { revert(); } TokenPurchase(buyer, beneficiary, weiAmount, tokens); vault.deposit.value(weiAmount)(buyer); } /** * @dev check if the current purchase valid based on time and amount of passed ether * @param _value amount of passed ether * @return true if investors can buy at the moment */ function validPurchase(uint256 _value) internal constant returns (bool) { bool nonZeroPurchase = _value != 0; bool withinPeriod = now >= startTime && now <= endTime; bool withinCap = !capReached(weiRaised.add(_value)); // For presale we want to decline all payments less then minPresaleAmount bool withinAmount = msg.value >= MIN_SALE_AMOUNT; return nonZeroPurchase && withinPeriod && withinCap && withinAmount; } /** * @dev finish presale stage and move vault to * refund state if GOAL was not reached */ function unholdFunds() onlyOwner public { if (goalReached()) { isMinCapReached = true; vault.unhold(); } else { revert(); } } /** * @dev check if crowdsale still active based on current time and cap * @return true if crowdsale event has ended */ function hasEnded() public constant returns (bool) { bool timeIsUp = now > endTime; return timeIsUp || capReached(); } /** * @dev finalize crowdsale. this method triggers vault and token finalization */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); if (goalReached()) { vault.close(); } else { refunding = true; vault.enableRefunds(); } isFinalized = true; Finalized(); } /** * @dev add previous investor compensaton rate */ function addRate(address investor, uint8 rate) onlyOwner public { require(investor != address(0)); bonuses.addRate(investor, rate); } /** * @dev check if soft cap goal is reached in USD */ function goalReached() public view returns (bool) { return isMinCapReached || weiRaised.mul(ETHUSD).div(10**20) >= USD_GOAL; } /** * @dev check if hard cap goal is reached in USD */ function capReached() internal view returns (bool) { return weiRaised.mul(ETHUSD).div(10**20) >= USD_CAP; } /** * @dev check if hard cap goal is reached in USD */ function capReached(uint256 raised) internal view returns (bool) { return raised.mul(ETHUSD).div(10**20) >= USD_CAP; } /** * @dev if crowdsale is unsuccessful, investors can claim refunds here */ function claimRefund() public { require(isFinalized && refunding); vault.refund(msg.sender); } /** * @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(); } /** * @dev called by the escrow to update current ETH x USD exchange rate */ function updateExchangeRate(uint rate) onlyEscrow public { ETHUSD = rate; } /** * @dev returns current token price based on current presale time frame */ function getConversionRate() public constant returns (uint256) { if (now >= startTime + 106 days) { return 650; } else if (now >= startTime + 99 days) { return 676; } else if (now >= startTime + 92 days) { return 715; } else if (now >= startTime + 85 days) { return 780; } else if (now >= startTime) { return 845; } return 0; } /** * @dev killer method that can bu used by owner to * kill the contract and send funds to owner */ function kill() onlyOwner whenPaused public { selfdestruct(owner); } }
called by the escrow to update current ETH x USD exchange rate/
function updateExchangeRate(uint rate) onlyEscrow public { ETHUSD = rate; }
1,014,488
// Sources flattened with hardhat v2.1.2 https://hardhat.org // File @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // File contracts/governance/TokensFarmCongressMembersRegistry.sol pragma solidity 0.6.12; /** * TokensFarmCongressMembersRegistry contract. * @author Nikola Madjarevic * Date created: 13.9.21. * Github: madjarevicn */ contract TokensFarmCongressMembersRegistry { using SafeMath for *; // The name of this contract string public constant name = "TokensFarmCongressMembersRegistry"; // Event to fire every time someone is added or removed from members event MembershipChanged(address member, bool isMember); // _tokensFarmCongress congress pointer address public tokensFarmCongress; // The minimum number of voting members that must be in attendance uint256 minimalQuorum; // Mapping to check if the member is belonging to congress mapping (address => bool) isMemberInCongress; // Mapping address to member info mapping(address => Member) public address2Member; // Mapping to store all members addresses address[] public allMembers; // Info about member's of congress struct Member { // Name of member bytes32 name; // Member since what date uint memberSince; } // Modifiers modifier onlyTokensFarmCongress { require(msg.sender == tokensFarmCongress); _; } constructor( address[] memory initialCongressMembers, bytes32[] memory initialCongressMemberNames, address _tokensFarmCongress ) public { uint length = initialCongressMembers.length; for(uint i=0; i<length; i++) { addMemberInternal( initialCongressMembers[i], initialCongressMemberNames[i] ); } tokensFarmCongress = _tokensFarmCongress; } /** * @notice function is setting minimum quorum on new value * * @param newMinimumQuorum - new value of minimum quorum */ function changeMinimumQuorum( uint newMinimumQuorum ) external onlyTokensFarmCongress { require( newMinimumQuorum > 0, "Minimum quorum must be higher than 0" ); minimalQuorum = newMinimumQuorum; } /** * @notice function is adding new member * * @param targetMember - ethereum address to be added * @param memberName - public name for that member */ function addMember( address targetMember, bytes32 memberName ) external onlyTokensFarmCongress { require( targetMember != address(0x0), "Target member can not be 0x0 address" ); addMemberInternal(targetMember, memberName); } function addMemberInternal( address targetMember, bytes32 memberName ) internal { //Require that this member is not already a member of congress require(!isMemberInCongress[targetMember], "Member already exists"); // Update basic member information address2Member[targetMember] = Member({ memberSince: block.timestamp, name: memberName }); // Add member to list of all members allMembers.push(targetMember); // Update minimum quorum minimalQuorum = allMembers.length.sub(1); // Mark that user is member in congress isMemberInCongress[targetMember] = true; // Fire an event emit MembershipChanged(targetMember, true); } /** * @notice remove membership from `targetMember` * * @param targetMember - ethereum address to be removed */ function removeMember( address targetMember ) external onlyTokensFarmCongress { require(isMemberInCongress[targetMember], "Member does not exits"); uint length = allMembers.length; uint i=0; // Find selected member while(allMembers[i] != targetMember) { if(i == length) { revert(); } i++; } // Move the last member to this place allMembers[i] = allMembers[length-1]; // Remove the last member allMembers.pop(); //Remove him from state mapping isMemberInCongress[targetMember] = false; //Remove his state to empty member address2Member[targetMember] = Member({ memberSince: block.timestamp, name: "0x0" }); //Reduce 1 member from quorum minimalQuorum = minimalQuorum.sub(1); // Emit event that member is removed. emit MembershipChanged(targetMember, false); } /** * @notice function which will be exposed, * and congress will use it as "modifier" * * @param _address - is the address we're willing to check, * if it belongs to congress * * @return true/false depending if it is either a member or not */ function isMember( address _address ) external view returns (bool) { return isMemberInCongress[_address]; } /** * @notice getter for length for how many members are currently * * @return length of members */ function getNumberOfMembers() external view returns (uint) { return allMembers.length; } /** * @notice function to get addresses of all members in congress * * @return array of addresses */ function getAllMemberAddresses() external view returns (address[] memory) { return allMembers; } /** * @notice function to get member information * * @return address of member, members name and date when he became member */ function getMemberInfo( address _member ) external view returns (address, bytes32, uint) { Member memory member = address2Member[_member]; return ( _member, member.name, member.memberSince ); } /** * @notice function to get minimal quorum * * @return minimal quorum */ function getMinimalQuorum() external view returns (uint256) { return minimalQuorum; } }
function is setting minimum quorum on new value newMinimumQuorum - new value of minimum quorum/
function changeMinimumQuorum( uint newMinimumQuorum ) external onlyTokensFarmCongress { require( newMinimumQuorum > 0, "Minimum quorum must be higher than 0" ); minimalQuorum = newMinimumQuorum; }
14,751,737
/** *Submitted for verification at Etherscan.io on 2022-03-11 */ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @title FuseFeeDistributor * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @notice FuseFeeDistributor controls and receives protocol fees from Fuse pools and relays admin actions to Fuse pools. */ contract FuseFeeDistributor is Initializable, OwnableUpgradeable { using AddressUpgradeable for address; using SafeERC20Upgradeable for IERC20Upgradeable; /** * @dev Initializer that sets initial values of state variables. * @param _defaultInterestFeeRate The default proportion of Fuse pool interest taken as a protocol fee (scaled by 1e18). */ function initialize(uint256 _defaultInterestFeeRate) public initializer { require(_defaultInterestFeeRate <= 1e18, "Interest fee rate cannot be more than 100%."); __Ownable_init(); defaultInterestFeeRate = _defaultInterestFeeRate; maxSupplyEth = uint256(-1); maxUtilizationRate = uint256(-1); } /** * @notice The proportion of Fuse pool interest taken as a protocol fee (scaled by 1e18). */ uint256 public defaultInterestFeeRate; /** * @dev Sets the default proportion of Fuse pool interest taken as a protocol fee. * @param _defaultInterestFeeRate The default proportion of Fuse pool interest taken as a protocol fee (scaled by 1e18). */ function _setDefaultInterestFeeRate(uint256 _defaultInterestFeeRate) external onlyOwner { require(_defaultInterestFeeRate <= 1e18, "Interest fee rate cannot be more than 100%."); defaultInterestFeeRate = _defaultInterestFeeRate; } /** * @dev Withdraws accrued fees on interest. * @param erc20Contract The ERC20 token address to withdraw. Set to the zero address to withdraw ETH. */ function _withdrawAssets(address erc20Contract) external { if (erc20Contract == address(0)) { uint256 balance = address(this).balance; require(balance > 0, "No balance available to withdraw."); (bool success, ) = owner().call{value: balance}(""); require(success, "Failed to transfer ETH balance to msg.sender."); } else { IERC20Upgradeable token = IERC20Upgradeable(erc20Contract); uint256 balance = token.balanceOf(address(this)); require(balance > 0, "No token balance available to withdraw."); token.safeTransfer(owner(), balance); } } /** * @dev Minimum borrow balance (in ETH) per user per Fuse pool asset (only checked on new borrows, not redemptions). */ uint256 public minBorrowEth; /** * @dev Maximum supply balance (in ETH) per user per Fuse pool asset. * No longer used as of `Rari-Capital/compound-protocol` version `fuse-v1.1.0`. */ uint256 public maxSupplyEth; /** * @dev Maximum utilization rate (scaled by 1e18) for Fuse pool assets (only checked on new borrows, not redemptions). * No longer used as of `Rari-Capital/compound-protocol` version `fuse-v1.1.0`. */ uint256 public maxUtilizationRate; /** * @dev Sets the proportion of Fuse pool interest taken as a protocol fee. * @param _minBorrowEth Minimum borrow balance (in ETH) per user per Fuse pool asset (only checked on new borrows, not redemptions). * @param _maxSupplyEth Maximum supply balance (in ETH) per user per Fuse pool asset. * @param _maxUtilizationRate Maximum utilization rate (scaled by 1e18) for Fuse pool assets (only checked on new borrows, not redemptions). */ function _setPoolLimits(uint256 _minBorrowEth, uint256 _maxSupplyEth, uint256 _maxUtilizationRate) external onlyOwner { minBorrowEth = _minBorrowEth; maxSupplyEth = _maxSupplyEth; maxUtilizationRate = _maxUtilizationRate; } /** * @dev Receives ETH fees. */ receive() external payable { } /** * @dev Sends data to a contract. * @param targets The contracts to which `data` will be sent. * @param data The data to be sent to each of `targets`. */ function _callPool(address[] calldata targets, bytes[] calldata data) external onlyOwner { require(targets.length > 0 && targets.length == data.length, "Array lengths must be equal and greater than 0."); for (uint256 i = 0; i < targets.length; i++) targets[i].functionCall(data[i]); } /** * @dev Sends data to a contract. * @param targets The contracts to which `data` will be sent. * @param data The data to be sent to each of `targets`. */ function _callPool(address[] calldata targets, bytes calldata data) external onlyOwner { require(targets.length > 0, "No target addresses specified."); for (uint256 i = 0; i < targets.length; i++) targets[i].functionCall(data); } /** * @dev Deploys a `CEtherDelegator`. * @param constructorData `CEtherDelegator` ABI-encoded constructor data. */ function deployCEther(bytes calldata constructorData) external virtual returns (address) { // ABI decode constructor data (address comptroller, , , , address implementation, , , ) = abi.decode(constructorData, (address, address, string, string, address, bytes, uint256, uint256)); // Check implementation whitelist require(cEtherDelegateWhitelist[address(0)][implementation][false], "CEtherDelegate contract not whitelisted."); // Make sure comptroller == msg.sender require(comptroller == msg.sender, "Comptroller is not sender."); // Deploy Unitroller using msg.sender, underlying, and block.number as a salt bytes memory cEtherDelegatorCreationCode = hex"608060405234801561001057600080fd5b50604051610785380380610785833981810160405261010081101561003457600080fd5b8151602083015160408085018051915193959294830192918464010000000082111561005f57600080fd5b90830190602082018581111561007457600080fd5b825164010000000081118282018810171561008e57600080fd5b82525081516020918201929091019080838360005b838110156100bb5781810151838201526020016100a3565b50505050905090810190601f1680156100e85780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561010b57600080fd5b90830190602082018581111561012057600080fd5b825164010000000081118282018810171561013a57600080fd5b82525081516020918201929091019080838360005b8381101561016757818101518382015260200161014f565b50505050905090810190601f1680156101945780820380516001836020036101000a031916815260200191505b506040818152602083015192018051929491939192846401000000008211156101bc57600080fd5b9083019060208201858111156101d157600080fd5b82516401000000008111828201881017156101eb57600080fd5b82525081516020918201929091019080838360005b83811015610218578181015183820152602001610200565b50505050905090810190601f1680156102455780820380516001836020036101000a031916815260200191505b5060405260200180519060200190929190805190602001909291905050506103ba8489898989878760405160240180876001600160a01b03166001600160a01b03168152602001866001600160a01b03166001600160a01b031681526020018060200180602001858152602001848152602001838103835287818151815260200191508051906020019080838360005b838110156102ed5781810151838201526020016102d5565b50505050905090810190601f16801561031a5780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101561034d578181015183820152602001610335565b50505050905090810190601f16801561037a5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b03908116631e70b25560e21b1790915290995061049c16975050505050505050565b5061048e848560008660405160240180846001600160a01b03166001600160a01b031681526020018315151515815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561042557818101518382015260200161040d565b50505050905090810190601f1680156104525780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b039081166350d85b7360e01b1790915290955061049c169350505050565b50505050505050505061055e565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104dc5780518252601f1990920191602091820191016104bd565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461053c576040519150601f19603f3d011682016040523d82523d6000602084013e610541565b606091505b50915091506000821415610556573d60208201fd5b949350505050565b6102188061056d6000396000f3fe60806040526004361061001e5760003560e01c80635c60da1b146100e1575b6000546040805160048152602481019091526020810180516001600160e01b031663076de25160e21b17905261005d916001600160a01b031690610112565b50600080546040516001600160a01b0390911690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146100c1576040519150601f19603f3d011682016040523d82523d6000602084013e6100c6565b606091505b505090506040513d6000823e8180156100dd573d82f35b3d82fd5b3480156100ed57600080fd5b506100f66101d4565b604080516001600160a01b039092168252519081900360200190f35b606060006060846001600160a01b0316846040518082805190602001908083835b602083106101525780518252601f199092019160209182019101610133565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146101b2576040519150601f19603f3d011682016040523d82523d6000602084013e6101b7565b606091505b509150915060008214156101cc573d60208201fd5b949350505050565b6000546001600160a01b03168156fea265627a7a723158208e3e63485e5f7ae8cba3fa394e12885c029940469c7a173b8ff7745fabdad3b364736f6c63430005110032"; cEtherDelegatorCreationCode = abi.encodePacked(cEtherDelegatorCreationCode, constructorData); bytes32 salt = keccak256(abi.encodePacked(msg.sender, address(0), block.number)); address proxy; assembly { proxy := create2(0, add(cEtherDelegatorCreationCode, 32), mload(cEtherDelegatorCreationCode), salt) if iszero(extcodesize(proxy)) { revert(0, "Failed to deploy CEther.") } } return proxy; } /** * @dev Deploys a `CErc20Delegator`. * @param constructorData `CErc20Delegator` ABI-encoded constructor data. */ function deployCErc20(bytes calldata constructorData) external virtual returns (address) { // ABI decode constructor data (address underlying, address comptroller, , , , address implementation, , , ) = abi.decode(constructorData, (address, address, address, string, string, address, bytes, uint256, uint256)); // Check implementation whitelist require(cErc20DelegateWhitelist[address(0)][implementation][false], "CErc20Delegate contract not whitelisted."); // Make sure comptroller == msg.sender require(comptroller == msg.sender, "Comptroller is not sender."); // Deploy CErc20Delegator using msg.sender, underlying, and block.number as a salt bytes memory cErc20DelegatorCreationCode = hex"608060405234801561001057600080fd5b506040516107f53803806107f5833981810160405261012081101561003457600080fd5b81516020830151604080850151606086018051925194969395919493918201928464010000000082111561006757600080fd5b90830190602082018581111561007c57600080fd5b825164010000000081118282018810171561009657600080fd5b82525081516020918201929091019080838360005b838110156100c35781810151838201526020016100ab565b50505050905090810190601f1680156100f05780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561011357600080fd5b90830190602082018581111561012857600080fd5b825164010000000081118282018810171561014257600080fd5b82525081516020918201929091019080838360005b8381101561016f578181015183820152602001610157565b50505050905090810190601f16801561019c5780820380516001836020036101000a031916815260200191505b506040818152602083015192018051929491939192846401000000008211156101c457600080fd5b9083019060208201858111156101d957600080fd5b82516401000000008111828201881017156101f357600080fd5b82525081516020918201929091019080838360005b83811015610220578181015183820152602001610208565b50505050905090810190601f16801561024d5780820380516001836020036101000a031916815260200191505b50604081815260208381015193909101516001600160a01b03808e1660248501908152818e166044860152908c16606485015260c4840185905260e4840182905260e0608485019081528b516101048601528b519597509195506103b59489948f948f948f948f948f948d948d949260a4830192610124019189019080838360005b838110156102e75781810151838201526020016102cf565b50505050905090810190601f1680156103145780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101561034757818101518382015260200161032f565b50505050905090810190601f1680156103745780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b0390811663a0b0d28960e01b17909152909a506104981698505050505050505050565b50610489848560008660405160240180846001600160a01b03166001600160a01b031681526020018315151515815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610420578181015183820152602001610408565b50505050905090810190601f16801561044d5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b039081166350d85b7360e01b17909152909550610498169350505050565b5050505050505050505061055a565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104d85780518252601f1990920191602091820191016104b9565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610538576040519150601f19603f3d011682016040523d82523d6000602084013e61053d565b606091505b50915091506000821415610552573d60208201fd5b949350505050565b61028c806105696000396000f3fe60806040526004361061001e5760003560e01c80635c60da1b1461011e575b341561005b5760405162461bcd60e51b81526004018080602001828103825260378152602001806102216037913960400191505060405180910390fd5b6000546040805160048152602481019091526020810180516001600160e01b031663076de25160e21b17905261009a916001600160a01b03169061014f565b50600080546040516001600160a01b0390911690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146100fe576040519150601f19603f3d011682016040523d82523d6000602084013e610103565b606091505b505090506040513d6000823e81801561011a573d82f35b3d82fd5b34801561012a57600080fd5b50610133610211565b604080516001600160a01b039092168252519081900360200190f35b606060006060846001600160a01b0316846040518082805190602001908083835b6020831061018f5780518252601f199092019160209182019101610170565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146101ef576040519150601f19603f3d011682016040523d82523d6000602084013e6101f4565b606091505b50915091506000821415610209573d60208201fd5b949350505050565b6000546001600160a01b03168156fe43457263323044656c656761746f723a66616c6c6261636b3a2063616e6e6f742073656e642076616c756520746f2066616c6c6261636ba265627a7a7231582005c7822f7294a2303680b0d2b051bee472cd65b928fd92bacf345e29e5b26c9f64736f6c63430005110032"; cErc20DelegatorCreationCode = abi.encodePacked(cErc20DelegatorCreationCode, constructorData); bytes32 salt = keccak256(abi.encodePacked(msg.sender, underlying, block.number)); address proxy; assembly { proxy := create2(0, add(cErc20DelegatorCreationCode, 32), mload(cErc20DelegatorCreationCode), salt) if iszero(extcodesize(proxy)) { revert(0, "Failed to deploy CErc20.") } } return proxy; } /** * @dev Whitelisted Comptroller implementation contract addresses for each existing implementation. */ mapping(address => mapping(address => bool)) public comptrollerImplementationWhitelist; /** * @dev Adds/removes Comptroller implementations to the whitelist. * @param oldImplementations The old `Comptroller` implementation addresses to upgrade from for each `newImplementations` to upgrade to. * @param newImplementations Array of `Comptroller` implementations to be whitelisted/unwhitelisted. * @param statuses Array of whitelist statuses corresponding to `implementations`. */ function _editComptrollerImplementationWhitelist(address[] calldata oldImplementations, address[] calldata newImplementations, bool[] calldata statuses) external onlyOwner { require(newImplementations.length > 0 && newImplementations.length == oldImplementations.length && newImplementations.length == statuses.length, "No Comptroller implementations supplied or array lengths not equal."); for (uint256 i = 0; i < newImplementations.length; i++) comptrollerImplementationWhitelist[oldImplementations[i]][newImplementations[i]] = statuses[i]; } /** * @dev Whitelisted CErc20Delegate implementation contract addresses and `allowResign` values for each existing implementation. */ mapping(address => mapping(address => mapping(bool => bool))) public cErc20DelegateWhitelist; /** * @dev Adds/removes CErc20Delegate implementations to the whitelist. * @param oldImplementations The old `CErc20Delegate` implementation addresses to upgrade from for each `newImplementations` to upgrade to. * @param newImplementations Array of `CErc20Delegate` implementations to be whitelisted/unwhitelisted. * @param allowResign Array of `allowResign` values corresponding to `newImplementations` to be whitelisted/unwhitelisted. * @param statuses Array of whitelist statuses corresponding to `newImplementations`. */ function _editCErc20DelegateWhitelist(address[] calldata oldImplementations, address[] calldata newImplementations, bool[] calldata allowResign, bool[] calldata statuses) external onlyOwner { require(newImplementations.length > 0 && newImplementations.length == oldImplementations.length && newImplementations.length == allowResign.length && newImplementations.length == statuses.length, "No CErc20Delegate implementations supplied or array lengths not equal."); for (uint256 i = 0; i < newImplementations.length; i++) cErc20DelegateWhitelist[oldImplementations[i]][newImplementations[i]][allowResign[i]] = statuses[i]; } /** * @dev Whitelisted CEtherDelegate implementation contract addresses and `allowResign` values for each existing implementation. */ mapping(address => mapping(address => mapping(bool => bool))) public cEtherDelegateWhitelist; /** * @dev Adds/removes CEtherDelegate implementations to the whitelist. * @param oldImplementations The old `CEtherDelegate` implementation addresses to upgrade from for each `newImplementations` to upgrade to. * @param newImplementations Array of `CEtherDelegate` implementations to be whitelisted/unwhitelisted. * @param allowResign Array of `allowResign` values corresponding to `newImplementations` to be whitelisted/unwhitelisted. * @param statuses Array of whitelist statuses corresponding to `newImplementations`. */ function _editCEtherDelegateWhitelist(address[] calldata oldImplementations, address[] calldata newImplementations, bool[] calldata allowResign, bool[] calldata statuses) external onlyOwner { require(newImplementations.length > 0 && newImplementations.length == oldImplementations.length && newImplementations.length == allowResign.length && newImplementations.length == statuses.length, "No CEtherDelegate implementations supplied or array lengths not equal."); for (uint256 i = 0; i < newImplementations.length; i++) cEtherDelegateWhitelist[oldImplementations[i]][newImplementations[i]][allowResign[i]] = statuses[i]; } /** * @dev Latest Comptroller implementation for each existing implementation. */ mapping(address => address) internal _latestComptrollerImplementation; /** * @dev Latest Comptroller implementation for each existing implementation. */ function latestComptrollerImplementation(address oldImplementation) external view returns (address) { return _latestComptrollerImplementation[oldImplementation] != address(0) ? _latestComptrollerImplementation[oldImplementation] : oldImplementation; } /** * @dev Sets the latest `Comptroller` upgrade implementation address. * @param oldImplementation The old `Comptroller` implementation address to upgrade from. * @param newImplementation Latest `Comptroller` implementation address. */ function _setLatestComptrollerImplementation(address oldImplementation, address newImplementation) external onlyOwner { _latestComptrollerImplementation[oldImplementation] = newImplementation; } struct CDelegateUpgradeData { address implementation; bool allowResign; bytes becomeImplementationData; } /** * @dev Latest CErc20Delegate implementation for each existing implementation. */ mapping(address => CDelegateUpgradeData) public _latestCErc20Delegate; /** * @dev Latest CEtherDelegate implementation for each existing implementation. */ mapping(address => CDelegateUpgradeData) public _latestCEtherDelegate; /** * @dev Latest CErc20Delegate implementation for each existing implementation. */ function latestCErc20Delegate(address oldImplementation) external view returns (address, bool, bytes memory) { CDelegateUpgradeData memory data = _latestCErc20Delegate[oldImplementation]; bytes memory emptyBytes; return data.implementation != address(0) ? (data.implementation, data.allowResign, data.becomeImplementationData) : (oldImplementation, false, emptyBytes); } /** * @dev Latest CEtherDelegate implementation for each existing implementation. */ function latestCEtherDelegate(address oldImplementation) external view returns (address, bool, bytes memory) { CDelegateUpgradeData memory data = _latestCEtherDelegate[oldImplementation]; bytes memory emptyBytes; return data.implementation != address(0) ? (data.implementation, data.allowResign, data.becomeImplementationData) : (oldImplementation, false, emptyBytes); } /** * @dev Sets the latest `CEtherDelegate` upgrade implementation address and data. * @param oldImplementation The old `CEtherDelegate` implementation address to upgrade from. * @param newImplementation Latest `CEtherDelegate` implementation address. * @param allowResign Whether or not `resignImplementation` should be called on the old implementation before upgrade. * @param becomeImplementationData Data passed to the new implementation via `becomeImplementation` after upgrade. */ function _setLatestCEtherDelegate(address oldImplementation, address newImplementation, bool allowResign, bytes calldata becomeImplementationData) external onlyOwner { _latestCEtherDelegate[oldImplementation] = CDelegateUpgradeData(newImplementation, allowResign, becomeImplementationData); } /** * @dev Sets the latest `CErc20Delegate` upgrade implementation address and data. * @param oldImplementation The old `CErc20Delegate` implementation address to upgrade from. * @param newImplementation Latest `CErc20Delegate` implementation address. * @param allowResign Whether or not `resignImplementation` should be called on the old implementation before upgrade. * @param becomeImplementationData Data passed to the new implementation via `becomeImplementation` after upgrade. */ function _setLatestCErc20Delegate(address oldImplementation, address newImplementation, bool allowResign, bytes calldata becomeImplementationData) external onlyOwner { _latestCErc20Delegate[oldImplementation] = CDelegateUpgradeData(newImplementation, allowResign, becomeImplementationData); } /** * @notice Maps Unitroller (Comptroller proxy) addresses to the proportion of Fuse pool interest taken as a protocol fee (scaled by 1e18). * @dev A value of 0 means unset whereas a negative value means 0. */ mapping(address => int256) public customInterestFeeRates; /** * @notice Returns the proportion of Fuse pool interest taken as a protocol fee (scaled by 1e18). */ function interestFeeRate() external view returns (uint256) { (bool success, bytes memory data) = msg.sender.staticcall(abi.encodeWithSignature("comptroller()")); if (success && data.length == 32) { (address comptroller) = abi.decode(data, (address)); int256 customRate = customInterestFeeRates[comptroller]; if (customRate > 0) return uint256(customRate); if (customRate < 0) return 0; } return defaultInterestFeeRate; } /** * @dev Sets the proportion of Fuse pool interest taken as a protocol fee. * @param comptroller The Unitroller (Comptroller proxy) address. * @param rate The proportion of Fuse pool interest taken as a protocol fee (scaled by 1e18). */ function _setCustomInterestFeeRate(address comptroller, int256 rate) external onlyOwner { require(rate <= 1e18, "Interest fee rate cannot be more than 100%."); customInterestFeeRates[comptroller] = rate; } }
Sets the default proportion of Fuse pool interest taken as a protocol fee. _defaultInterestFeeRate The default proportion of Fuse pool interest taken as a protocol fee (scaled by 1e18)./
function _setDefaultInterestFeeRate(uint256 _defaultInterestFeeRate) external onlyOwner { require(_defaultInterestFeeRate <= 1e18, "Interest fee rate cannot be more than 100%."); defaultInterestFeeRate = _defaultInterestFeeRate; }
10,973,003
pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } pragma solidity ^0.6.0; import "../interfaces/GasTokenInterface.sol"; contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } pragma solidity ^0.6.0; abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } pragma solidity ^0.6.0; abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsStable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } pragma solidity ^0.6.0; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } pragma solidity ^0.6.0; import "../interfaces/ERC20.sol"; import "./Address.sol"; import "./SafeMath.sol"; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 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(ERC20 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(ERC20 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(ERC20 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"); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } pragma solidity ^0.6.0; interface ERC20 { 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); } pragma solidity ^0.6.0; 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); } } } } pragma solidity ^0.6.0; 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; } } pragma solidity ^0.6.0; import "../interfaces/DSProxyInterface.sol"; import "./SafeERC20.sol"; /// @title Pulls a specified amount of tokens from the EOA owner account to the proxy contract PullTokensProxy { using SafeERC20 for ERC20; /// @notice Pulls a token from the proxyOwner -> proxy /// @dev Proxy owner must first give approve to the proxy address /// @param _tokenAddr Address of the ERC20 token /// @param _amount Amount of tokens which will be transfered to the proxy function pullTokens(address _tokenAddr, uint _amount) public { address proxyOwner = DSProxyInterface(address(this)).owner(); ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount); } } pragma solidity ^0.6.0; abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } pragma solidity ^0.6.0; import "../auth/Auth.sol"; import "../interfaces/DSProxyInterface.sol"; // 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/>. contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } pragma solidity ^0.6.0; import "./AdminAuth.sol"; contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../interfaces/Vat.sol"; import "../interfaces/Manager.sol"; import "../interfaces/IMCDSubscriptions.sol"; import "../interfaces/ICompoundSubscriptions.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../exchangeV3/DFSExchangeData.sol"; import "./ShifterRegistry.sol"; import "../utils/GasBurner.sol"; import "../loggers/DefisaverLogger.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } // encode data bytes memory paramsData = abi.encode(_loanShift, _exchangeData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return getUnderlyingAddr(_address); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function logEvent( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } pragma solidity ^0.6.0; abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } pragma solidity ^0.6.0; abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } pragma solidity ^0.6.0; abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } pragma solidity ^0.6.0; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } pragma solidity ^0.6.0; abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } pragma solidity ^0.6.0; import "../DS/DSGuard.sol"; import "../DS/DSAuth.sol"; contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address wrapper; address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; // service fee divider address user; // user to check special fee address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } pragma solidity ^0.6.0; import "./DSAuthority.sol"; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; contract MCDCreateTaker is GasBurner { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable burnGas(20) { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/Spotter.sol"; import "../../interfaces/Jug.sol"; import "../../interfaces/DaiJoin.sol"; import "../../interfaces/Join.sol"; import "./MCDSaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for MCD CDPs contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } pragma solidity ^0.6.0; import "./PipInterface.sol"; abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } pragma solidity ^0.6.0; abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; import "./Vat.sol"; import "./Gem.sol"; abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } pragma solidity ^0.6.0; import "./Gem.sol"; abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../interfaces/Vat.sol"; /// @title Helper methods for MCDSaverProxy contract MCDSaverProxyHelper is DSMath { enum ManagerType { MCD, BPROTOCOL } /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.MCD) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } else if (_managerType == ManagerType.BPROTOCOL) { return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed; } } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/ZrxAllowlist.sol"; import "./DFSExchangeData.sol"; import "./DFSExchangeHelper.sol"; import "../exchange/SaverExchangeRegistry.sol"; import "../interfaces/OffchainWrapperInterface.sol"; contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid"; /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { return (false, 0); } if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) { return (false, 0); } // send src amount ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount); return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; abstract contract PipInterface { function read() public virtual returns (bytes32); } pragma solidity ^0.6.0; abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } pragma solidity ^0.6.0; contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } pragma solidity ^0.6.0; import "./DSAuth.sol"; import "./DSNote.sol"; abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } pragma solidity ^0.6.0; contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } pragma solidity ^0.6.0; abstract contract TokenInterface { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual 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 virtual payable; function withdraw(uint256) public virtual; } pragma solidity ^0.6.0; interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; contract DFSExchangeHelper { string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } address walletAddr = _feeRecipient.getFeeAddr(); if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _src; } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchangeV3/DFSExchangeData.sol"; abstract contract OffchainWrapperInterface is DFSExchangeData { function takeOrder( ExchangeData memory _exData, ActionType _type ) virtual public payable returns (bool success, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract IFeeRecipient { function getFeeAddr() public view virtual returns (address); function changeWalletAddr(address _newWallet) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/MCDSaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/ITokenInterface.sol"; import "../../DS/DSAuth.sol"; contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ProtocolInterface.sol"; import "../interfaces/ERC20.sol"; import "../interfaces/ITokenInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "./dydx/ISoloMargin.sol"; import "./SavingsLogger.sol"; import "./dsr/DSRSavingsProtocol.sol"; import "./compound/CompoundSavingsProtocol.sol"; contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); function borrowCaps(address) external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (public virtually) Sell, // sell an amount of some token (public virtually) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public virtual; function getIsGlobalOperator(address operator) public virtual view returns (bool); function getMarketTokenAddress(uint256 marketId) public virtual view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public virtual; function getAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public virtual view returns (address); function getMarketInterestSetter(uint256 marketId) public virtual view returns (address); function getMarketSpreadPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getNumMarkets() public virtual view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public virtual returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public virtual; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual; function getIsLocalOperator(address owner, address operator) public virtual view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public virtual; function getMarginRatio() public virtual view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public virtual view returns (bool); function getRiskParams() public virtual view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public virtual view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public virtual; function getMinBorrowedValue() public virtual view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public virtual; function getMarketPrice(uint256 marketId) public virtual view returns (address); function owner() public virtual view returns (address); function isOwner() public virtual view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public virtual returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public virtual; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getMarketWithInfo(uint256 marketId) public virtual view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual; function getLiquidationSpread() public virtual view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public virtual view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public virtual view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public virtual view returns (uint8); function getEarningsRate() public virtual view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual; function getRiskLimits() public virtual view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public virtual view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual; function ownerSetGlobalOperator(address operator, bool approved) public virtual; function transferOwnership(address newOwner) public virtual; function getAdjustedAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public virtual view returns (Interest.Rate memory); } pragma solidity ^0.6.0; contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../DS/DSMath.sol"; abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../compound/helpers/Exponential.sol"; import "../../interfaces/ERC20.sol"; contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; import "./CarefulMath.sol"; contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } } pragma solidity ^0.6.0; contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "./ISoloMargin.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, address market, uint256 rateMode, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } else { functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProviderV2 { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } pragma solidity ^0.6.0; /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external virtual view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external virtual view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; ManagerType managerType; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable burnGas(20) { mcdCloseFlashLoan.transfer(msg.value); // 0x fee address managerAddr = getManagerAddr(_closeData.managerType); if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId)); } Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILoanShifter.sol"; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../mcd/create/MCDCreateProxyActions.sol"; contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(address(manager), _cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(address(manager), _cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(address(manager), _cdpId, _joinAddr, collAmount); // draw debt drawDai(address(manager), _cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } } pragma solidity ^0.6.0; abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "./MCDCreateProxyActions.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../DS/DSProxy.sol"; import "./MCDCreateTaker.sol"; contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "./SafeERC20.sol"; interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./saver/MCDSaverProxyHelper.sol"; import "../interfaces/Spotter.sol"; contract MCDLoanInfo is MCDSaverProxyHelper { Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); struct VaultInfo { address owner; uint256 ratio; uint256 collateral; uint256 debt; bytes32 ilk; address urn; } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) { address urn = manager.urns(_cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint256 collateral, uint256 debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); vaultInfo = VaultInfo({ owner: manager.owns(_cdpId), ratio: getRatio(_cdpId, ilk), collateral: collateral, debt: debt, ilk: ilk, urn: urn }); } function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) { vaultInfos = new VaultInfo[](_cdps.length); for (uint256 i = 0; i < _cdps.length; i++) { vaultInfos[i] = getVaultInfo(_cdps[i]); } } function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) { ratios = new uint256[](_cdps.length); for (uint256 i = 0; i<_cdps.length; i++) { bytes32 ilk = manager.ilks(_cdps[i]); ratios[i] = getRatio(_cdps[i], ilk); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "./StaticV2.sol"; import "../saver/MCDSaverProxy.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../auth/AdminAuth.sol"; /// @title Handles subscriptions for automatic monitoring contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } pragma solidity ^0.6.0; /// @title Implements enum Method abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Flipper.sol"; import "../../interfaces/Gem.sol"; contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); if(Join(_joinAddr).dec() != 18) { amount = amount / (10**(18 - Join(_joinAddr).dec())); } Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } pragma solidity ^0.6.0; abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./ISubscriptionsV2.sol"; import "./StaticV2.sol"; import "./MCDMonitorProxyV2.sol"; /// @title Implements logic that allows bots to call Boost and Repay contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1000000; uint public BOOST_GAS_COST = 1000000; bytes4 public REPAY_SELECTOR = 0xf360ce20; bytes4 public BOOST_SELECTOR = 0x8ec2ae25; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./StaticV2.sol"; abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Implements logic for calling MCDSaverProxy always from same contract contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; uint public MIN_CHANGE_PERIOD = 6 * 1 hours; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../compound/helpers/Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for cream contracts contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } pragma solidity ^0.6.0; abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } pragma solidity ^0.6.0; abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CreamSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "../utils/ZrxAllowlist.sol"; import "./SaverExchangeHelper.sol"; import "./SaverExchangeRegistry.sol"; contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CompoundSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CompoundSaverFlashProxy is DFSExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee _exData.srcAmount = (borrowAmount + _flashLoanData[0]); _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "./Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for Compound contracts contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; import "../../compound/helpers/CompoundSaverHelper.sol"; contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; _exData.srcAmount = borrowAmount; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "../utils/FlashLoanReceiverBase.sol"; import "../interfaces/DSProxyInterface.sol"; import "../exchangeV3/DFSExchangeCore.sol"; import "./ShifterRegistry.sol"; import "./LoanShifterTaker.sol"; /// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth { address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant SERVICE_FEE = 400; // 0.25% Fee ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendTokenToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(paramData.proxy).owner(); if (paramData.swapType == 1) { // COLL_SWAP (, uint256 amount) = _sell(exchangeData); sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendTokenToProxy( payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)) ); } else { // NO_SWAP just send tokens to proxy sendTokenAndEthToProxy( payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr) ); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall( uint256 _amount, uint256 _fee, bytes memory _params ) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { LoanShifterTaker.LoanShiftData memory shiftData; address proxy; (shiftData, exchangeData, proxy) = abi.decode( _params, (LoanShifterTaker.LoanShiftData, ExchangeData, address) ); bytes memory proxyData1; bytes memory proxyData2; uint256 openDebtAmount = (_amount + _fee); if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER FROM proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount ); } else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND FROM if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature( "changeDebt(address,address,uint256,uint256)", shiftData.debtAddr1, shiftData.debtAddr2, _amount, exchangeData.srcAmount ); } else { proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", shiftData.addrLoan1, shiftData.debtAddr1, shiftData.collAmount, shiftData.debtAmount ); } } if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER TO proxyData2 = abi.encodeWithSignature( "open(uint256,address,uint256)", shiftData.id2, shiftData.addrLoan2, openDebtAmount ); } else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND TO if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2); } else { proxyData2 = abi.encodeWithSignature( "open(address,address,uint256)", shiftData.addrLoan2, shiftData.debtAddr2, openDebtAmount ); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: shiftData.debtAddr1, protocol1: uint8(shiftData.fromProtocol), protocol2: uint8(shiftData.toProtocol), swapType: uint8(shiftData.swapType) }); } function sendTokenAndEthToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function sendTokenToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } else { _proxy.transfer(address(this).balance); } } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../DS/DSProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../shifter/ShifterRegistry.sol"; import "./CompoundCreateTaker.sol"; /// @title Contract that receives the FL from Aave for Creating loans contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner(); _sell(exchangeData); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { CompoundCreateTaker.CreateInfo memory createData; address proxy; (createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee)); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: createData.cCollAddress, cDebtAddr: createData.cBorrowAddress }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; /// @title Opens compound positions with a leverage contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, DFSExchangeData.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/ProxyPermission.sol"; import "../utils/DydxFlashLoanBase.sol"; import "../loggers/DefisaverLogger.sol"; import "../interfaces/ERC20.sol"; /// @title Takes flash loan contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../utils/SafeMath.sol"; import "../savings/dydx/ISoloMargin.sol"; contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../AaveHelperV2.sol"; import "../../../utils/GasBurner.sol"; import "../../../auth/AdminAuth.sol"; import "../../../auth/ProxyPermission.sol"; import "../../../utils/DydxFlashLoanBase.sol"; import "../../../loggers/DefisaverLogger.sol"; import "../../../interfaces/ProxyRegistryInterface.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../interfaces/ERC20.sol"; import "../../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 { address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2; // leaving _flAmount to be the same as the older version function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; // for repay we are using regular flash loan with paying back the flash loan + premium uint256[] memory modes = new uint256[](1); modes[0] = 0; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } // leaving _flAmount to be the same as the older version function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; uint256[] memory modes = new uint256[](1); modes[0] = _rateMode; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; import "./DSProxyInterface.sol"; abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapExchangeInterface.sol"; import "../../interfaces/UniswapFactoryInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } pragma solidity ^0.6.0; abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } pragma solidity ^0.6.0; abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/SafeERC20.sol"; contract DFSPrices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers, bytes[] memory _additionalData ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "../interfaces/IFeeRecipient.sol"; import "./SaverExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { address walletAddr = _feeRecipient.getFeeAddr(); feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchange/SaverExchangeCore.sol"; contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; ManagerType managerType; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../mcd/saver/MCDSaverProxyHelper.sol"; import "./MCDCloseTaker.sol"; contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; address managerAddr = getManagerAddr(closeDataSent.managerType); closeCDP(closeData, exchangeData, user, managerAddr); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user, address _managerAddr ) internal { paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee); (, daiSwaped) = _buy(_exchangeData); } address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0); Manager(_managerAddr).flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = Manager(_managerAddr).urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == EXCHANGE_WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Imports cream position from the account to DSProxy contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Imports Compound position from the account to DSProxy contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve DSProxy to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this)); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } } pragma solidity ^0.6.0; import "../../auth/AdminAuth.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { (address cCollAddr, address cBorrowAddr, address proxy) = abi.decode(_params, (address, address, address)); address user = DSProxyInterface(proxy).owner(); uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowAddr, _amount); // repay compound debt on behalf of the user require( CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0, "Repay borrow behalf fail" ); bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance); DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData); // borrow debt now on ds proxy bytes memory borrowProxyCallData = formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData); // repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call to pull tokens to DSProxy /// @param _cTokenAddr CToken address of the collateral /// @param _amount Amount of cTokens to pull function formatDSProxyPullTokensCall( address _cTokenAddr, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "pullTokens(address,uint256)", _cTokenAddr, _amount ); } /// @notice Formats function data call borrow through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed function formatDSProxyBorrowCall( address _cCollToken, address _cBorrowToken, address _borrowToken, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount ); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = _flAmount; // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _market, _rateMode, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _market Market in which we want to import /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _market, address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_market, _collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "../compound/helpers/Exponential.sol"; contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../helpers/Exponential.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface( 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B ); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) { uint256 compBalance = 0; for (uint256 i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance = add_(comp.compAccrued(_user), compBalance); compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getClaimableAssets(address[] memory _cTokens, address _user) public view returns (bool[] memory supplyClaims, bool[] memory borrowClaims) { supplyClaims = new bool[](_cTokens.length); borrowClaims = new bool[](_cTokens.length); for (uint256 i = 0; i < _cTokens.length; ++i) { supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0; borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0; } } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint256 supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: comp.compSupplierIndex(_cToken, _supplier) }); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = supplierDelta; } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint256 borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: comp.compBorrowerIndex(_cToken, _borrower) }); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_( CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex ); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = borrowerDelta; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompBalance.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../CompoundBasicProxy.sol"; contract CompLeverage is DFSExchangeCore, CompBalance { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.user = msg.sender; exchangeData.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic compound interactions through the DSProxy contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic cream interactions through the DSProxy contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "./helpers/Exponential.sol"; contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundSafetyRatio.sol"; import "./helpers/CompoundSaverHelper.sol"; /// @title Gets data about Compound positions contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; uint borrowCap; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]), borrowCap: comp.borrowCaps(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/BotRegistry.sol"; import "../../utils/GasBurner.sol"; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../CompoundSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1500000; uint public BOOST_GAS_COST = 1000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin { compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Compound automatization contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "./DFSExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./DFSExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587); function callSell(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(dfsExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { dfsExchange = DFSExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CreamSafetyRatio.sol"; import "./helpers/CreamSaverHelper.sol"; /// @title Gets data about cream positions contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; import "../../interfaces/ERC20.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchange/SaverExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CreamSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelper is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelper.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxy is GasBurner, DFSExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } else { destAmount = _data.srcAmount; destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelperV2.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/TokenInterface.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this)); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // swap (, destAmount) = _sell(_data); } // take gas cost at the end destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); // if destAmount higher than borrow repay whole debt uint borrow; if (_rateMode == STABLE_ID) { (,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } else { (,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this))); // first return 0x fee to tx.origin as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); // borrow amount ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this)); // take gas cost at the beginning _data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } (, destAmount) = _sell(_data); } else { destAmount = _data.srcAmount; } if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../utils/SafeERC20.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../DS/DSProxy.sol"; import "../../AaveHelperV2.sol"; import "../../../auth/AdminAuth.sol"; import "../../../exchangeV3/DFSExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal { (, uint swappedAmount) = _sell(_exchangeData); address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens uint256 msgValue = 0; address token = _exchangeData.destAddr; // sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { msgValue = swappedAmount; token = ETH_ADDR; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // deposit collateral on behalf of user DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "deposit(address,address,uint256)", _market, token, swappedAmount ) ); } function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal { // we will withdraw exactly the srcAmount, as fee we keep before selling uint valueToWithdraw = _exchangeData.srcAmount; // take out the fee wee need to pay and sell the rest _exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee; (, uint swappedAmount) = _sell(_exchangeData); // set protocol fee left to eth balance of this address // but if destAddr is eth or weth, this also includes that value so we need to substract it uint protocolFeeLeft = address(this).balance; address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens uint256 msgValue = 0; if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { protocolFeeLeft -= swappedAmount; msgValue = swappedAmount; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // first payback the loan with swapped amount DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "payback(address,address,uint256,uint256)", _market, _exchangeData.destAddr, swappedAmount, _rateMode ) ); // if some tokens left after payback (full repay) we need to return it back to the proxy owner require(user != address(0)); // be sure that we fetched the user correctly if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { // keep protocol fee for tx.origin, but the rest of the balance return to the user payable(user).transfer(address(this).balance - protocolFeeLeft); } else { // in case its a token, just return whole value back to the user, as protocol fee is always in eth uint amount = ERC20(_exchangeData.destAddr).balanceOf(user); ERC20(_exchangeData.destAddr).safeTransfer(user, amount); } // pull the amount we flash loaned in collateral to be able to payback the debt DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw)); } function executeOperation( address[] calldata, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) public returns (bool) { ( bytes memory exchangeDataBytes, address market, uint256 gasCost, uint256 rateMode, bool isRepay, address proxy ) = abi.decode(params, (bytes,address,uint256,uint256,bool,address)); require(initiator == proxy, "initiator isn't proxy"); ExchangeData memory exData = unpackExchangeData(exchangeDataBytes); exData.user = DSAuth(proxy).owner(); exData.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // this is to avoid stack too deep uint fee = premiums[0]; uint totalValueToReturn = exData.srcAmount + fee; // if its repay, we are using regular flash loan and payback the premiums if (isRepay) { repay(exData, market, gasCost, proxy, rateMode, fee); address token = exData.srcAddr; if (token == ETH_ADDR || token == WETH_ADDRESS) { // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)(); token = WETH_ADDRESS; } ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn); } else { boost(exData, market, gasCost, proxy); } tx.origin.transfer(address(this).balance); return true; } /// @dev allow contract to receive eth from sell receive() external override payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImportV2 is AaveHelperV2, AdminAuth { using SafeERC20 for ERC20; address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address market, address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market); uint256 globalBorrowAmountStable = 0; uint256 globalBorrowAmountVariable = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user); if (borrowsStable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID)); globalBorrowAmountStable = borrowsStable; } if (borrowsVariable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID)); globalBorrowAmountVariable = borrowsVariable; } } if (globalBorrowAmountVariable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID); } if (globalBorrowAmountStable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID); } (address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken); // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal { // payback on behalf of user if (_token != ETH_ADDR) { ERC20(_token).safeApprove(_proxy, _amount); DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } else { DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; import "./AaveHelperV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./AaveMonitorProxyV2.sol"; import "./AaveSubscriptionsV2.sol"; import "../AaveSafetyRatioV2.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorV2"; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; AaveMonitorProxyV2 public aaveMonitorProxy; AaveSubscriptionsV2 public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxyV2(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptionsV2(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepayV2", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoostV2", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptionsV2.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptionsV2.AaveHolder memory holder; holder = subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxyV2 is AdminAuth { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorProxyV2"; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Owner is able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Owner is able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point owner is able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptionsV2 is AdminAuth { string public constant NAME = "AaveSubscriptionsV2"; struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "./AaveHelperV2.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 { using SafeERC20 for ERC20; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); if (_tokenAddr == ETH_ADDR) { require(msg.value == _amount); TokenInterface(WETH_ADDRESS).deposit{value: _amount}(); _tokenAddr = WETH_ADDRESS; } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { // if weth, pull to proxy and return ETH to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this)); // needs to use balance of in case that amount is -1 for whole debt TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); msg.sender.transfer(address(this).balance); } else { // if not eth send directly to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender); } } /// @notice User borrows tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this)); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender)); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this))); if (_tokenAddr == WETH_ADDRESS) { // Pull if we have any eth leftover TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this))); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this))); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } // stable = 1, variable = 2 function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode); } function changeToWeth(address _token) private view returns(address) { if (_token == ETH_ADDR) { return WETH_ADDRESS; } return _token; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatioV2.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; uint256 stableBorrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowStablePos = 0; uint64 borrowVariablePos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowStablePos] = reserve; data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth; borrowStablePos++; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowVariablePos] = reserve; data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth; borrowVariablePos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_market, _users[i]); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); uint256 globalBorrowAmount = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, ERC20(aCollateralToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; import "./AaveHelper.sol"; contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "./AaveMonitorProxy.sol"; import "./AaveSubscriptions.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../AaveSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatio.sol"; contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; uint256 borrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "./SaverExchangeHelper.sol"; contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./SaverExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); /// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell /// @dev safeApprove is modified to always first set approval to 0, then to exact amount if (_type == ActionType.SELL) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from Scp and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up writeUint256(_exData.offchainData.callData, 36, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CompoundSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/ICompoundSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxyV2 is ProxyPermission { string public constant NAME = "AaveSubscriptionsProxyV2"; address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; import "../../DS/DSGuard.sol"; import "../../DS/DSAuth.sol"; contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } pragma solidity ^0.6.0; import "../../interfaces/OsmMom.sol"; import "../../interfaces/Osm.sol"; import "../../auth/AdminAuth.sol"; import "../../interfaces/Manager.sol"; contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } pragma solidity ^0.6.0; abstract contract OsmMom { mapping (bytes32 => address) public osms; } pragma solidity ^0.6.0; abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } pragma solidity ^0.6.0; import "./DSProxy.sol"; abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } pragma solidity ^0.6.0; import "./ERC20.sol"; //TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); }
Called by the DSProxy contract which owns the Aave position Adds the users Aave poistion in the list of subscriptions so it can be monitored _minRatio Minimum ratio below which repay is triggered _maxRatio Maximum ratio after which boost is triggered _optimalBoost Ratio amount which boost should target _optimalRepay Ratio amount which repay should target _boostEnabled Boolean determing if boost is enabled if boost is not enabled, set max ratio to max uint
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } }
381,285
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 LICENSE pragma solidity ^0.8.0; import "./ERC20.sol"; import "./interfaces/IEON.sol"; contract EON is IEON, ERC20 { // Tracks the last block that a caller has written to state. // Disallow some access to functions if they occur while a change is being written. mapping(address => uint256) private lastWrite; // address => allowedToCallFunctions mapping(address => bool) private admins; //ower address public auth; // hardcoded max eon supply 5b uint256 public constant MAX_EON = 5000000000 ether; // amount minted uint256 public minted; constructor() ERC20("EON", "EON", 18) { auth = msg.sender; } modifier onlyOwner() { require(msg.sender == auth); _; } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disbale */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } function transferOwnership(address newOwner) external onlyOwner { auth = newOwner; } /** * mints $EON to a recipient * @param to the recipient of the $EON * @param amount the amount of $EON to mint */ function mint(address to, uint256 amount) external override { require(admins[msg.sender], "Only admins can mint"); minted += amount; _mint(to, amount); } /** * burns $EON from a holder * @param from the holder of the $EON * @param amount the amount of $EON to burn */ function burn(address from, uint256 amount) external override { require(admins[msg.sender], "Only admins"); _burn(from, amount); } /** * @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(ERC20, IEON) returns (bool) { // caught yah require( admins[msg.sender] || lastWrite[sender] < block.number, "hmmmm what are you doing?" ); // If the entity invoking this transfer is an admin (i.e. the gameContract) // allow the transfer without approval. This saves gas and a transaction. // The sender address will still need to actually have the amount being attempted to send. if (admins[msg.sender]) { // NOTE: This will omit any events from being written. This saves additional gas, // and the event emission is not a requirement by the EIP // (read this function summary / ERC20 summary for more details) emit Transfer(sender, recipient, amount); return true; } // If it's not an admin entity (Shattered EON contract, pytheas, refinery. etc) // The entity will need to be given permission to transfer these funds // For instance, someone can't just make a contract and siphon $EON from every account return super.transferFrom(sender, recipient, amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Minimalist and gas efficient standard ERC1155 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC1155.sol) abstract contract ERC1155 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 amount ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] amounts ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event URI(string value, uint256 indexed id); /*/////////////////////////////////////////////////////////////// ERC1155 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => mapping(uint256 => uint256)) public balanceOf; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// METADATA LOGIC //////////////////////////////////////////////////////////////*/ function uri(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC1155 LOGIC //////////////////////////////////////////////////////////////*/ function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isApproved(address account, address operator) public view virtual returns (bool) { return isApprovedForAll[account][operator]; } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual { require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); balanceOf[from][id] -= amount; balanceOf[to][id] += amount; emit TransferSingle(msg.sender, from, to, id, amount); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155Received( msg.sender, from, id, amount, data ) == ERC1155TokenReceiver.onERC1155Received.selector, "UNSAFE_RECIPIENT" ); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { uint256 idsLength = ids.length; // Saves MLOADs. require(idsLength == amounts.length, "LENGTH_MISMATCH"); require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); for (uint256 i = 0; i < idsLength; ) { uint256 id = ids[i]; uint256 amount = amounts[i]; balanceOf[from][id] -= amount; balanceOf[to][id] += amount; // An array can't have a total length // larger than the max uint256 value. unchecked { i++; } } emit TransferBatch(msg.sender, from, to, ids, amounts); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155BatchReceived( msg.sender, from, ids, amounts, data ) == ERC1155TokenReceiver.onERC1155BatchReceived.selector, "UNSAFE_RECIPIENT" ); } function balanceOfBatch(address[] memory owners, uint256[] memory ids) public view virtual returns (uint256[] memory balances) { uint256 ownersLength = owners.length; // Saves MLOADs. require(ownersLength == ids.length, "LENGTH_MISMATCH"); balances = new uint256[](owners.length); // Unchecked because the only math done is incrementing // the array index counter which cannot possibly overflow. unchecked { for (uint256 i = 0; i < ownersLength; i++) { balances[i] = balanceOf[owners[i]][ids[i]]; } } } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155 interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal { balanceOf[to][id] += amount; emit TransferSingle(msg.sender, address(0), to, id, amount); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155Received( msg.sender, address(0), id, amount, data ) == ERC1155TokenReceiver.onERC1155Received.selector, "UNSAFE_RECIPIENT" ); } function _batchMint( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { uint256 idsLength = ids.length; // Saves MLOADs. require(idsLength == amounts.length, "LENGTH_MISMATCH"); for (uint256 i = 0; i < idsLength; ) { balanceOf[to][ids[i]] += amounts[i]; // An array can't have a total length // larger than the max uint256 value. unchecked { i++; } } emit TransferBatch(msg.sender, address(0), to, ids, amounts); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155BatchReceived( msg.sender, address(0), ids, amounts, data ) == ERC1155TokenReceiver.onERC1155BatchReceived.selector, "UNSAFE_RECIPIENT" ); } function _batchBurn( address from, uint256[] memory ids, uint256[] memory amounts ) internal { uint256 idsLength = ids.length; // Saves MLOADs. require(idsLength == amounts.length, "LENGTH_MISMATCH"); for (uint256 i = 0; i < idsLength; ) { balanceOf[from][ids[i]] -= amounts[i]; // An array can't have a total length // larger than the max uint256 value. unchecked { i++; } } emit TransferBatch(msg.sender, from, address(0), ids, amounts); } function _burn( address from, uint256 id, uint256 amount ) internal { balanceOf[from][id] -= amount; emit TransferSingle(msg.sender, from, address(0), id, amount); } } /// @notice A generic interface for a contract which properly accepts ERC1155 tokens. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC1155.sol) interface ERC1155TokenReceiver { function onERC1155Received( address operator, address from, uint256 id, uint256 amount, bytes calldata data ) external returns (bytes4); function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER" ); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/IERC1155TokenReceiver.sol"; import "./interfaces/IImperialGuild.sol"; import "./interfaces/IEON.sol"; import "./interfaces/IRAW.sol"; import "./ERC1155.sol"; import "./EON.sol"; contract ImperialGuild is IImperialGuild, IERC1155TokenReceiver, ERC1155, Pausable { using Strings for uint256; // struct to store each trait's data for metadata and rendering struct Image { string name; string png; } struct TypeInfo { uint16 mints; uint16 burns; uint16 maxSupply; uint256 eonExAmt; uint256 secExAmt; } struct LastWrite { uint64 time; uint64 blockNum; } // hardcoded tax % to the Imperial guild, collected from shard and onosia purchases // to be used in game at a later time uint256 public constant ImperialGuildTax = 20; // multiplier for eon exchange amount uint256 public constant multiplier = 10**18; // payments for shards and onosia will collect in this contract until // an owner withdraws, at which point the tax % above will be sent to the // treasury and the remainder will be burnt *see withdraw address private ImperialGuildTreasury; address public auth; // Tracks the last block and timestamp that a caller has written to state. // Disallow some access to functions if they occur while a change is being written. mapping(address => LastWrite) private lastWrite; mapping(uint256 => TypeInfo) private typeInfo; // storage of each image data mapping(uint256 => Image) public traitData; // address => allowedToCallFunctions mapping(address => bool) private admins; IEON public eon; // reference to the raw contract for processing payments in raw eon or other // raw materials IRAW public raw; EON public eonToken; constructor() { auth = msg.sender; admins[msg.sender] = true; } modifier onlyOwner() { require(msg.sender == auth); _; } /** CRITICAL TO SETUP */ modifier requireContractsSet() { require(address(eon) != address(0), "Contracts not set"); _; } function setContracts(address _eon, address _raw) external onlyOwner { eon = IEON(_eon); raw = IRAW(_raw); eonToken = EON(_eon); } /** * Mint a token - any payment / game logic should be handled in the DenOfAlgol contract. * ATENTION- PaymentId "0" is reserved for EON only!! * All other paymentIds point to the RAW contract ID */ function mint( uint256 typeId, uint256 paymentId, uint16 qty, address recipient ) external override whenNotPaused { require(admins[msg.sender], "Only admins can call this"); require( typeInfo[typeId].mints + qty <= typeInfo[typeId].maxSupply, "All tokens minted" ); // all payments will be transferred to this contract //this allows the hardcoded ImperialGuild tax that will be used in future additions to shatteredEON to be withdrawn. At the time of withdaw the balance of this contract will be burnt - the tax amount. if (paymentId == 0) { eon.transferFrom( tx.origin, address(this), typeInfo[typeId].eonExAmt * qty ); } else { raw.safeTransferFrom( tx.origin, address(this), paymentId, typeInfo[typeId].secExAmt * qty, "" ); } typeInfo[typeId].mints += qty; _mint(recipient, typeId, qty, ""); } /** * Burn a token - any payment / game logic should be handled in the game contract. */ function burn( uint256 typeId, uint16 qty, address burnFrom ) external override whenNotPaused { require(admins[msg.sender], "Only admins can call this"); typeInfo[typeId].burns += qty; _burn(burnFrom, typeId, qty); } function handlePayment(uint256 amount) external override whenNotPaused { require(admins[msg.sender], "Only admins can call this"); eon.transferFrom(tx.origin, address(this), amount); } // used to create new erc1155 typs from the Imperial guild // ATTENTION - Type zero is reserved to not cause conflicts function setType(uint256 typeId, uint16 maxSupply) external onlyOwner { require(typeInfo[typeId].mints <= maxSupply, "max supply too low"); typeInfo[typeId].maxSupply = maxSupply; } // store exchange rates for new erc1155s for both EON and/or // any raw resource function setExchangeAmt( uint256 typeId, uint256 exchangeAmt, uint256 secExchangeAmt ) external onlyOwner { require( typeInfo[typeId].maxSupply > 0, "this type has not been set up" ); typeInfo[typeId].eonExAmt = exchangeAmt; typeInfo[typeId].secExAmt = secExchangeAmt; } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disbale */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } function setPaused(bool _paused) external onlyOwner requireContractsSet { if (_paused) _pause(); else _unpause(); } // owner call to withdraw this contracts EON balance * 20% // to the Imperial guild treasury, the remainder is then burned function withdrawEonAndBurn() external onlyOwner { uint256 guildAmt = eonToken.balanceOf(address(this)) * (ImperialGuildTax / 100); uint256 amtToBurn = eonToken.balanceOf(address(this)) - guildAmt; eonToken.transferFrom(address(this), ImperialGuildTreasury, guildAmt); eonToken.burn(address(this), amtToBurn); } // owner function to withdraw this contracts raw resource balance * 20% // to the Imperial guild treasury, the remainder is then burned function withdrawRawAndBurn(uint16 id) external onlyOwner { uint256 rawBalance = raw.getBalance(address(this), id); uint256 guildAmt = rawBalance * (ImperialGuildTax / 100); uint256 amtToBurn = rawBalance - guildAmt; raw.safeTransferFrom( address(this), ImperialGuildTreasury, id, guildAmt, "" ); raw.burn(id, amtToBurn, address(this)); } // owner function to set the Imperial guild treasury address function setTreasuries(address _treasury) external onlyOwner { ImperialGuildTreasury = _treasury; } // external function to recieve information on a given // ERC1155 from the ImperialGuild function getInfoForType(uint256 typeId) external view returns (TypeInfo memory) { require(typeInfo[typeId].maxSupply > 0, "invalid type"); return typeInfo[typeId]; } // ERC1155 token uri and renders for the on chain metadata function uri(uint256 typeId) public view override returns (string memory) { require(typeInfo[typeId].maxSupply > 0, "invalid type"); Image memory img = traitData[typeId]; string memory metadata = string( abi.encodePacked( '{"name": "', img.name, '", "description": "The Guild Lords of Pytheas are feared for their ruthless cunning and enterprising technological advancements. They alone have harnessed the power of a dying star to power a man made planet that processes EON. Rumor has it that they also dabble in the shadows as a black market dealer of hard to find artifacts and might entertain your offer for the right price, but be sure to tread lightly as they control every aspect of the economy in this star system. You would be a fool to arrive empty handed in any negotiation with them. All the metadata and images are generated and stored 100% on-chain. No IPFS. NO API. Just the Ethereum blockchain.", "image": "data:image/svg+xml;base64,', base64(bytes(drawSVG(typeId))), '", "attributes": []', "}" ) ); return string( abi.encodePacked( "data:application/json;base64,", base64(bytes(metadata)) ) ); } function uploadImage(uint256 typeId, Image calldata image) external onlyOwner { traitData[typeId] = Image(image.name, image.png); } function drawImage(Image memory image) internal pure returns (string memory) { return string( abi.encodePacked( '<image x="0" y="0" width="64" height="64" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="data:image/png;base64,', image.png, '"/>' ) ); } function drawSVG(uint256 typeId) internal view returns (string memory) { string memory svgString = string( abi.encodePacked(drawImage(traitData[typeId])) ); return string( abi.encodePacked( '<svg id="ImperialGuild" width="100%" height="100%" version="1.1" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">', svgString, "</svg>" ) ); } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override(ERC1155, IImperialGuild) { // allow admin contracts to send without approval if (!admins[msg.sender]) { require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); } balanceOf[from][id] -= amount; balanceOf[to][id] += amount; emit TransferSingle(msg.sender, from, to, id, amount); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155Received( msg.sender, from, id, amount, data ) == ERC1155TokenReceiver.onERC1155Received.selector, "UNSAFE_RECIPIENT" ); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override(ERC1155, IImperialGuild) { // allow admin contracts to send without approval uint256 idsLength = ids.length; // Saves MLOADs. require(idsLength == amounts.length, "LENGTH_MISMATCH"); // allow admin contracts to send without approval if (!admins[msg.sender]) { require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); } for (uint256 i = 0; i < idsLength; ) { uint256 id = ids[i]; uint256 amount = amounts[i]; balanceOf[from][id] -= amount; balanceOf[to][id] += amount; // An array can't have a total length // larger than the max uint256 value. unchecked { i++; } } emit TransferBatch(msg.sender, from, to, ids, amounts); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155BatchReceived( msg.sender, from, ids, amounts, data ) == ERC1155TokenReceiver.onERC1155BatchReceived.selector, "UNSAFE_RECIPIENT" ); } function getBalance(address account, uint256 id) public view returns (uint256) { return ERC1155(address(this)).balanceOf(account, id); } function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external pure override returns (bytes4) { return IERC1155TokenReceiver.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external pure override returns (bytes4) { return IERC1155TokenReceiver.onERC1155Received.selector; } function supportsInterface(bytes4 interfaceId) public pure override returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155 interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI } /** BASE 64 - Written by Brech Devos */ string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } // For OpenSeas function owner() public view virtual returns (address) { return auth; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IEON { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity >=0.8.0; interface IERC1155TokenReceiver { function onERC1155Received( address operator, address from, uint256 id, uint256 amount, bytes calldata data ) external returns (bytes4); function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IImperialGuild { function getBalance( address account, uint256 id ) external returns(uint256); function mint( uint256 typeId, uint256 paymentId, uint16 qty, address recipient ) external; function burn( uint256 typeId, uint16 qty, address burnFrom ) external; function handlePayment(uint256 amount) external; function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external; function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IRAW { function getBalance( address account, uint256 id ) external returns(uint256); function mint( uint256 typeId, uint256 qty, address recipient ) external; function burn( uint256 typeId, uint256 qty, address burnFrom ) external; function updateMintBurns( uint256 typeId, uint256 mintQty, uint256 burnQty ) external; function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external; function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; }
An array can't have a total length larger than the max uint256 value.
function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { require(idsLength == amounts.length, "LENGTH_MISMATCH"); require( msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); for (uint256 i = 0; i < idsLength; ) { uint256 id = ids[i]; uint256 amount = amounts[i]; balanceOf[from][id] -= amount; balanceOf[to][id] += amount; unchecked { i++; } } emit TransferBatch(msg.sender, from, to, ids, amounts); require( to.code.length == 0 ? to != address(0) : ERC1155TokenReceiver(to).onERC1155BatchReceived( msg.sender, from, ids, amounts, data ) == ERC1155TokenReceiver.onERC1155BatchReceived.selector, "UNSAFE_RECIPIENT" ); }
1,247,545
./full_match/5/0xc9964f5b2fDedb5C9701D947ae706A3A81D5cb7e/sources/browser/1_Storage.sol
Store proposal in variable Vote for proposal `num` with a score of `score` proposal value to store/
function vote(uint256 proposal, uint256 score) public { currentProposal = proposal; }
1,920,551
pragma solidity 0.5.3; contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED628(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED628(address(0), _owner); } function OWNER307() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER7() { //inject NONSTANDARD NAMING require(ISOWNER830()); _; } function ISOWNER830() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP84() public ONLYOWNER7 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED628(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP319(address newOwner) public ONLYOWNER7 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP813(newOwner); } function _TRANSFEROWNERSHIP813(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED628(_owner, newOwner); _owner = newOwner; } } contract OwnableSecondary is Ownable { address private _primary; event PRIMARYTRANSFERRED938( //inject NONSTANDARD NAMING address recipient ); constructor() internal { _primary = msg.sender; emit PRIMARYTRANSFERRED938(_primary); } modifier ONLYPRIMARYOROWNER634() { //inject NONSTANDARD NAMING require(msg.sender == _primary || msg.sender == OWNER307(), "not the primary user nor the owner"); _; } modifier ONLYPRIMARY294() { //inject NONSTANDARD NAMING require(msg.sender == _primary, "not the primary user"); _; } function PRIMARY930() public view returns (address) { //inject NONSTANDARD NAMING return _primary; } function TRANSFERPRIMARY55(address recipient) public ONLYOWNER7 { //inject NONSTANDARD NAMING require(recipient != address(0), "new primary address is null"); _primary = recipient; emit PRIMARYTRANSFERRED938(_primary); } } contract StatementRegisteryInterface is OwnableSecondary { function RECORDSTATEMENT412(string calldata buildingPermitId, uint[] calldata statementDataLayout, bytes calldata statementData) external returns(bytes32); //inject NONSTANDARD NAMING function STATEMENTIDSBYBUILDINGPERMIT755(string calldata id) external view returns(bytes32[] memory); //inject NONSTANDARD NAMING function STATEMENTEXISTS926(bytes32 statementId) public view returns(bool); //inject NONSTANDARD NAMING function GETSTATEMENTSTRING626(bytes32 statementId, string memory key) public view returns(string memory); //inject NONSTANDARD NAMING function GETSTATEMENTPCID716(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTACQUISITIONDATE999(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTRECIPIENT811(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTARCHITECT198(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTCITYHALL253(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTMAXIMUMHEIGHT317(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTDESTINATION15(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTSITEAREA921(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTBUILDINGAREA300(bytes32 statementId) external view returns (string memory); //inject NONSTANDARD NAMING function GETSTATEMENTNEARIMAGE527(bytes32 statementId) external view returns(string memory); //inject NONSTANDARD NAMING function GETSTATEMENTFARIMAGE348(bytes32 statementId) external view returns(string memory); //inject NONSTANDARD NAMING function GETALLSTATEMENTS348() external view returns(bytes32[] memory); //inject NONSTANDARD NAMING } contract OwnablePausable is Ownable { event PAUSED396(); //inject NONSTANDARD NAMING event UNPAUSED291(); //inject NONSTANDARD NAMING bool private _paused; constructor() internal { _paused = false; emit UNPAUSED291(); } function PAUSED193() public view returns (bool) { //inject NONSTANDARD NAMING return _paused; } modifier WHENNOTPAUSED828() { //inject NONSTANDARD NAMING require(!_paused); _; } modifier WHENPAUSED861() { //inject NONSTANDARD NAMING require(_paused); _; } function PAUSE542() public ONLYOWNER7 WHENNOTPAUSED828 { //inject NONSTANDARD NAMING _paused = true; emit PAUSED396(); } function UNPAUSE689() public ONLYOWNER7 WHENPAUSED861 { //inject NONSTANDARD NAMING _paused = false; emit UNPAUSED291(); } } contract Controller is OwnablePausable { StatementRegisteryInterface public registery; uint public price = 0; address payable private _wallet; address private _serverSide; event LOGEVENT957(string content); //inject NONSTANDARD NAMING event NEWSTATEMENTEVENT354(string indexed buildingPermitId, bytes32 statementId); //inject NONSTANDARD NAMING constructor(address registeryAddress, address payable walletAddr, address serverSideAddr) public { require(registeryAddress != address(0), "null registery address"); require(walletAddr != address(0), "null wallet address"); require(serverSideAddr != address(0), "null server side address"); registery = StatementRegisteryInterface(registeryAddress); _wallet = walletAddr; _serverSide = serverSideAddr; } function SETPRICE323(uint priceInWei) external WHENNOTPAUSED828 { //inject NONSTANDARD NAMING require(msg.sender == OWNER307() || msg.sender == _serverSide); price = priceInWei; } function SETWALLET585(address payable addr) external ONLYOWNER7 WHENNOTPAUSED828 { //inject NONSTANDARD NAMING require(addr != address(0), "null wallet address"); _wallet = addr; } function SETSERVERSIDE236(address payable addr) external ONLYOWNER7 WHENNOTPAUSED828 { //inject NONSTANDARD NAMING require(addr != address(0), "null server side address"); _serverSide = addr; } function RECORDSTATEMENT412(string calldata buildingPermitId, uint[] calldata statementDataLayout, bytes calldata statementData) external payable WHENNOTPAUSED828 returns(bytes32) { //inject NONSTANDARD NAMING if(msg.sender != OWNER307() && msg.sender != _serverSide) { require(msg.value >= price, "received insufficient value"); uint refund = msg.value - price; _wallet.transfer(price); // ETH TRANSFER if(refund > 0) { msg.sender.transfer(refund); // ETH TRANSFER } } bytes32 statementId = registery.RECORDSTATEMENT412( buildingPermitId, statementDataLayout, statementData ); emit NEWSTATEMENTEVENT354(buildingPermitId, statementId); return statementId; } function WALLET260() external view returns (address) { //inject NONSTANDARD NAMING return _wallet; } function SERVERSIDE606() external view returns (address) { //inject NONSTANDARD NAMING return _serverSide; } function STATEMENTEXISTS926(bytes32 statementId) external view returns (bool) { //inject NONSTANDARD NAMING return registery.STATEMENTEXISTS926(statementId); } function GETSTATEMENTIDSBYBUILDINGPERMIT117(string calldata buildingPermitId) external view returns(bytes32[] memory) { //inject NONSTANDARD NAMING return registery.STATEMENTIDSBYBUILDINGPERMIT755(buildingPermitId); } function GETALLSTATEMENTS348() external view returns(bytes32[] memory) { //inject NONSTANDARD NAMING return registery.GETALLSTATEMENTS348(); } function GETSTATEMENTPCID716(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTPCID716(statementId); } function GETSTATEMENTACQUISITIONDATE999(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTACQUISITIONDATE999(statementId); } function GETSTATEMENTRECIPIENT811(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTRECIPIENT811(statementId); } function GETSTATEMENTARCHITECT198(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTARCHITECT198(statementId); } function GETSTATEMENTCITYHALL253(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTCITYHALL253(statementId); } function GETSTATEMENTMAXIMUMHEIGHT317(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTMAXIMUMHEIGHT317(statementId); } function GETSTATEMENTDESTINATION15(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTDESTINATION15(statementId); } function GETSTATEMENTSITEAREA921(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTSITEAREA921(statementId); } function GETSTATEMENTBUILDINGAREA300(bytes32 statementId) external view returns (string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTBUILDINGAREA300(statementId); } function GETSTATEMENTNEARIMAGE527(bytes32 statementId) external view returns(string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTNEARIMAGE527(statementId); } function GETSTATEMENTFARIMAGE348(bytes32 statementId) external view returns(string memory) { //inject NONSTANDARD NAMING return registery.GETSTATEMENTFARIMAGE348(statementId); } }
inject NONSTANDARD NAMING
function GETSTATEMENTSITEAREA921(bytes32 statementId) external view returns (string memory);
12,859,539
pragma solidity ^0.4.24; /* ETHEREUM WORLD CUP : 14th June - 15th July 2018 [Russia] - designed and implemented by Norsefire. - thanks to Etherguy and oguzhanox for debugging and front-end respectively. Rules are as follows: * Entry to the game costs 0.2018 Ether. Use the register function when sending this. - Any larger or smaller amount of Ether, will be rejected. * 90% of the entry fee will go towards the prize fund, with 10% forming a fee. Of this fee, half goes to the developer, and half goes directly to Giveth (giveth.io/donate). The entry fee is the only Ether you will need to send for the duration of the tournament, barring the gas you spend for placing predictions. * Buying an entry allows the sender to place predictions on each game in the World Cup, barring those which have already kicked off prior to the time a participant enters. * Predictions can be made (or changed!) at any point up until the indicated kick-off time. * Selecting the correct result for any given game awards the player one point. In the first stage, a participant can also select a draw. This is not available from the RO16 onwards. * If a participant reaches a streak of three or more correct predictions in a row, they receive two points for every correct prediction from the third game until the streak is broken. * If a participant reaches a streak of *five* or more correct predictions in a row, they receive four points for every correct prediction from the fifth game until the streak is broken. * In the event of a tie, the following algorithm is used to decide rankings: - Compare the sum totals of the scores over the last 32 games. - If this produces a draw as well, compare results of the last 16 games. - This repeats until comparing the results of the final. - If it&#39;s a dead heat throughout, a coin-flip (or some equivalent method) will be used to determine the winner. Prizes: FIRST PLACE: 40% of Ether contained within the pot. SECOND PLACE: 30% of Ether contained within the pot. THIRD PLACE: 20% of Ether contained within the pot. FOURTH PLACE: 10% of Ether contained within the pot. Participant Teams and Groups: [Group D] AR - Argentina [Group C] AU - Australia [Group G] BE - Belgium [Group E] BR - Brazil [Group E] CH - Switzerland [Group H] CO - Colombia [Group E] CR - Costa Rica [Group E] CS - Serbia [Group F] DE - Germany [Group C] DK - Denmark [Group A] EG - Egypt [Group G] EN - England [Group B] ES - Spain [Group C] FR - France [Group D] HR - Croatia [Group B] IR - Iran [Group D] IS - Iceland [Group H] JP - Japan [Group F] KR - Republic of Korea [Group B] MA - Morocco [Group F] MX - Mexico [Group D] NG - Nigeria [Group G] PA - Panama [Group C] PE - Peru [Group H] PL - Poland [Group B] PT - Portugal [Group A] RU - Russia [Group A] SA - Saudi Arabia [Group F] SE - Sweden [Group H] SN - Senegal [Group G] TN - Tunisia [Group A] UY - Uruguay */ contract EtherWorldCup { using SafeMath for uint; /* CONSTANTS */ address internal constant administrator = 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae; address internal constant givethAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc; string name = "EtherWorldCup"; string symbol = "EWC"; /* VARIABLES */ mapping (string => int8) worldCupGameID; mapping (int8 => bool) gameFinished; // Is a game no longer available for predictions to be made? mapping (int8 => uint) gameLocked; // A result is either the two digit code of a country, or the word "DRAW". // Country codes are listed above. mapping (int8 => string) gameResult; int8 internal latestGameFinished; uint internal prizePool; uint internal givethPool; int registeredPlayers; mapping (address => bool) playerRegistered; mapping (address => mapping (int8 => bool)) playerMadePrediction; mapping (address => mapping (int8 => string)) playerPredictions; mapping (address => int8[64]) playerPointArray; mapping (address => int8) playerGamesScored; mapping (address => uint) playerStreak; address[] playerList; /* DEBUG EVENTS */ event Registration( address _player ); event PlayerLoggedPrediction( address _player, int _gameID, string _prediction ); event PlayerUpdatedScore( address _player, int _lastGamePlayed ); event Comparison( address _player, uint _gameID, string _myGuess, string _result, bool _correct ); event PlayerPointGain( address _player, uint _gameID, uint _streak, uint _points ); event StartAutoScoring( address _player ); event StartScoring( address _player, uint _gameID ); event DidNotPredict( address _player, uint _gameID ); event RipcordRefund( address _player ); /* CONSTRUCTOR */ constructor () public { // First stage games: these are known in advance. // Thursday 14th June, 2018 worldCupGameID["RU-SA"] = 1; // Russia vs Saudi Arabia gameLocked[1] = 1528988400; // Friday 15th June, 2018 worldCupGameID["EG-UY"] = 2; // Egypt vs Uruguay worldCupGameID["MA-IR"] = 3; // Morocco vs Iran worldCupGameID["PT-ES"] = 4; // Portugal vs Spain gameLocked[2] = 1529064000; gameLocked[3] = 1529074800; gameLocked[4] = 1529085600; // Saturday 16th June, 2018 worldCupGameID["FR-AU"] = 5; // France vs Australia worldCupGameID["AR-IS"] = 6; // Argentina vs Iceland worldCupGameID["PE-DK"] = 7; // Peru vs Denmark worldCupGameID["HR-NG"] = 8; // Croatia vs Nigeria gameLocked[5] = 1529143200; gameLocked[6] = 1529154000; gameLocked[7] = 1529164800; gameLocked[8] = 1529175600; // Sunday 17th June, 2018 worldCupGameID["CR-CS"] = 9; // Costa Rica vs Serbia worldCupGameID["DE-MX"] = 10; // Germany vs Mexico worldCupGameID["BR-CH"] = 11; // Brazil vs Switzerland gameLocked[9] = 1529236800; gameLocked[10] = 1529247600; gameLocked[11] = 1529258400; // Monday 18th June, 2018 worldCupGameID["SE-KR"] = 12; // Sweden vs Korea worldCupGameID["BE-PA"] = 13; // Belgium vs Panama worldCupGameID["TN-EN"] = 14; // Tunisia vs England gameLocked[12] = 1529323200; gameLocked[13] = 1529334000; gameLocked[14] = 1529344800; // Tuesday 19th June, 2018 worldCupGameID["CO-JP"] = 15; // Colombia vs Japan worldCupGameID["PL-SN"] = 16; // Poland vs Senegal worldCupGameID["RU-EG"] = 17; // Russia vs Egypt gameLocked[15] = 1529409600; gameLocked[16] = 1529420400; gameLocked[17] = 1529431200; // Wednesday 20th June, 2018 worldCupGameID["PT-MA"] = 18; // Portugal vs Morocco worldCupGameID["UR-SA"] = 19; // Uruguay vs Saudi Arabia worldCupGameID["IR-ES"] = 20; // Iran vs Spain gameLocked[18] = 1529496000; gameLocked[19] = 1529506800; gameLocked[20] = 1529517600; // Thursday 21st June, 2018 worldCupGameID["DK-AU"] = 21; // Denmark vs Australia worldCupGameID["FR-PE"] = 22; // France vs Peru worldCupGameID["AR-HR"] = 23; // Argentina vs Croatia gameLocked[21] = 1529582400; gameLocked[22] = 1529593200; gameLocked[23] = 1529604000; // Friday 22nd June, 2018 worldCupGameID["BR-CR"] = 24; // Brazil vs Costa Rica worldCupGameID["NG-IS"] = 25; // Nigeria vs Iceland worldCupGameID["CS-CH"] = 26; // Serbia vs Switzerland gameLocked[24] = 1529668800; gameLocked[25] = 1529679600; gameLocked[26] = 1529690400; // Saturday 23rd June, 2018 worldCupGameID["BE-TN"] = 27; // Belgium vs Tunisia worldCupGameID["KR-MX"] = 28; // Korea vs Mexico worldCupGameID["DE-SE"] = 29; // Germany vs Sweden gameLocked[27] = 1529755200; gameLocked[28] = 1529766000; gameLocked[29] = 1529776800; // Sunday 24th June, 2018 worldCupGameID["EN-PA"] = 30; // England vs Panama worldCupGameID["JP-SN"] = 31; // Japan vs Senegal worldCupGameID["PL-CO"] = 32; // Poland vs Colombia gameLocked[30] = 1529841600; gameLocked[31] = 1529852400; gameLocked[32] = 1529863200; // Monday 25th June, 2018 worldCupGameID["UR-RU"] = 33; // Uruguay vs Russia worldCupGameID["SA-EG"] = 34; // Saudi Arabia vs Egypt worldCupGameID["ES-MA"] = 35; // Spain vs Morocco worldCupGameID["IR-PT"] = 36; // Iran vs Portugal gameLocked[33] = 1529935200; gameLocked[34] = 1529935200; gameLocked[35] = 1529949600; gameLocked[36] = 1529949600; // Tuesday 26th June, 2018 worldCupGameID["AU-PE"] = 37; // Australia vs Peru worldCupGameID["DK-FR"] = 38; // Denmark vs France worldCupGameID["NG-AR"] = 39; // Nigeria vs Argentina worldCupGameID["IS-HR"] = 40; // Iceland vs Croatia gameLocked[37] = 1530021600; gameLocked[38] = 1530021600; gameLocked[39] = 1530036000; gameLocked[40] = 1530036000; // Wednesday 27th June, 2018 worldCupGameID["KR-DE"] = 41; // Korea vs Germany worldCupGameID["MX-SE"] = 42; // Mexico vs Sweden worldCupGameID["CS-BR"] = 43; // Serbia vs Brazil worldCupGameID["CH-CR"] = 44; // Switzerland vs Costa Rica gameLocked[41] = 1530108000; gameLocked[42] = 1530108000; gameLocked[43] = 1530122400; gameLocked[44] = 1530122400; // Thursday 28th June, 2018 worldCupGameID["JP-PL"] = 45; // Japan vs Poland worldCupGameID["SN-CO"] = 46; // Senegal vs Colombia worldCupGameID["PA-TN"] = 47; // Panama vs Tunisia worldCupGameID["EN-BE"] = 48; // England vs Belgium gameLocked[45] = 1530194400; gameLocked[46] = 1530194400; gameLocked[47] = 1530208800; gameLocked[48] = 1530208800; // Second stage games and onwards. The string values for these will be overwritten // as the tournament progresses. This is the order that will be followed for the // purposes of calculating winning streaks, as per the World Cup website. // Round of 16 // Saturday 30th June, 2018 worldCupGameID["1C-2D"] = 49; // 1C vs 2D worldCupGameID["1A-2B"] = 50; // 1A vs 2B gameLocked[49] = 1530367200; gameLocked[50] = 1530381600; // Sunday 1st July, 2018 worldCupGameID["1B-2A"] = 51; // 1B vs 2A worldCupGameID["1D-2C"] = 52; // 1D vs 2C gameLocked[51] = 1530453600; gameLocked[52] = 1530468000; // Monday 2nd July, 2018 worldCupGameID["1E-2F"] = 53; // 1E vs 2F worldCupGameID["1G-2H"] = 54; // 1G vs 2H gameLocked[53] = 1530540000; gameLocked[54] = 1530554400; // Tuesday 3rd July, 2018 worldCupGameID["1F-2E"] = 55; // 1F vs 2E worldCupGameID["1H-2G"] = 56; // 1H vs 2G gameLocked[55] = 1530626400; gameLocked[56] = 1530640800; // Quarter Finals // Friday 6th July, 2018 worldCupGameID["W49-W50"] = 57; // W49 vs W50 worldCupGameID["W53-W54"] = 58; // W53 vs W54 gameLocked[57] = 1530885600; gameLocked[58] = 1530900000; // Saturday 7th July, 2018 worldCupGameID["W55-W56"] = 59; // W55 vs W56 worldCupGameID["W51-W52"] = 60; // W51 vs W52 gameLocked[59] = 1530972000; gameLocked[60] = 1530986400; // Semi Finals // Tuesday 10th July, 2018 worldCupGameID["W57-W58"] = 61; // W57 vs W58 gameLocked[61] = 1531245600; // Wednesday 11th July, 2018 worldCupGameID["W59-W60"] = 62; // W59 vs W60 gameLocked[62] = 1531332000; // Third Place Playoff // Saturday 14th July, 2018 worldCupGameID["L61-L62"] = 63; // L61 vs L62 gameLocked[63] = 1531576800; // Grand Final // Sunday 15th July, 2018 worldCupGameID["W61-W62"] = 64; // W61 vs W62 gameLocked[64] = 1531666800; // Set initial variables. latestGameFinished = 0; } /* PUBLIC-FACING COMPETITION INTERACTIONS */ // Register to participate in the competition. Apart from gas costs from // making predictions and updating your score if necessary, this is the // only Ether you will need to spend throughout the tournament. function register() public payable { address _customerAddress = msg.sender; require( tx.origin == _customerAddress && !playerRegistered[_customerAddress] && _isCorrectBuyin (msg.value)); registeredPlayers = SafeMath.addint256(registeredPlayers, 1); playerRegistered[_customerAddress] = true; playerGamesScored[_customerAddress] = 0; playerList.push(_customerAddress); uint fivePercent = 0.01009 ether; uint tenPercent = 0.02018 ether; uint prizeEth = (msg.value).sub(tenPercent); require(playerRegistered[_customerAddress]); prizePool = prizePool.add(prizeEth); givethPool = givethPool.add(fivePercent); administrator.send(fivePercent); emit Registration(_customerAddress); } // Make a prediction for a game. An example would be makePrediction(1, "DRAW") // if you anticipate a draw in the game between Russia and Saudi Arabia, // or makePrediction(2, "UY") if you expect Uruguay to beat Egypt. // The "DRAW" option becomes invalid after the group stage games have been played. function makePrediction(int8 _gameID, string _prediction) public { address _customerAddress = msg.sender; uint predictionTime = now; require(playerRegistered[_customerAddress] && !gameFinished[_gameID] && predictionTime < gameLocked[_gameID]); // No draws allowed after the qualification stage. if (_gameID > 48 && equalStrings(_prediction, "DRAW")) { revert(); } else { playerPredictions[_customerAddress][_gameID] = _prediction; playerMadePrediction[_customerAddress][_gameID] = true; emit PlayerLoggedPrediction(_customerAddress, _gameID, _prediction); } } // What is the current score of a given tournament participant? function showPlayerScores(address _participant) view public returns (int8[64]) { return playerPointArray[_participant]; } // What was the last game ID that has had an official score registered for it? function gameResultsLogged() view public returns (int) { return latestGameFinished; } // Sum up the individual scores throughout the tournament and produce a final result. function calculateScore(address _participant) view public returns (int16) { int16 finalScore = 0; for (int8 i = 0; i < latestGameFinished; i++) { uint j = uint(i); int16 gameScore = playerPointArray[_participant][j]; finalScore = SafeMath.addint16(finalScore, gameScore); } return finalScore; } // How many people are taking part in the tournament? function countParticipants() public view returns (int) { return registeredPlayers; } // Keeping this open for anyone to update anyone else so that at the end of // the tournament we can force a score update for everyone using a script. function updateScore(address _participant) public { int8 lastPlayed = latestGameFinished; require(lastPlayed > 0); // Most recent game scored for this participant. int8 lastScored = playerGamesScored[_participant]; // Most recent game played in the tournament (sets bounds for scoring iteration). mapping (int8 => bool) madePrediction = playerMadePrediction[_participant]; mapping (int8 => string) playerGuesses = playerPredictions[_participant]; for (int8 i = lastScored; i < lastPlayed; i++) { uint j = uint(i); uint k = j.add(1); uint streak = playerStreak[_participant]; emit StartScoring(_participant, k); if (!madePrediction[int8(k)]) { playerPointArray[_participant][j] = 0; playerStreak[_participant] = 0; emit DidNotPredict(_participant, k); emit PlayerPointGain(_participant, k, 0, 0); } else { string storage playerResult = playerGuesses[int8(k)]; string storage actualResult = gameResult[int8(k)]; bool correctGuess = equalStrings(playerResult, actualResult); emit Comparison(_participant, k, playerResult, actualResult, correctGuess); if (!correctGuess) { // The guess was wrong. playerPointArray[_participant][j] = 0; playerStreak[_participant] = 0; emit PlayerPointGain(_participant, k, 0, 0); } else { // The guess was right. streak = streak.add(1); playerStreak[_participant] = streak; if (streak >= 5) { // On a long streak - four points. playerPointArray[_participant][j] = 4; emit PlayerPointGain(_participant, k, streak, 4); } else { if (streak >= 3) { // On a short streak - two points. playerPointArray[_participant][j] = 2; emit PlayerPointGain(_participant, k, streak, 2); } // Not yet at a streak - standard one point. else { playerPointArray[_participant][j] = 1; emit PlayerPointGain(_participant, k, streak, 1); } } } } } playerGamesScored[_participant] = lastPlayed; } // Invoke this function to get *everyone* up to date score-wise. // This is probably best used at the end of the tournament, to ensure // that prizes are awarded to the correct addresses. // Note: this is going to be VERY gas-intensive. Use it if you&#39;re desperate // to see how you square up against everyone else if they&#39;re slow to // update their own scores. Alternatively, if there&#39;s just one or two // stragglers, you can just call updateScore for them alone. function updateAllScores() public { uint allPlayers = playerList.length; for (uint i = 0; i < allPlayers; i++) { address _toScore = playerList[i]; emit StartAutoScoring(_toScore); updateScore(_toScore); } } // Which game ID has a player last computed their score up to // using the updateScore function? function playerLastScoredGame(address _player) public view returns (int8) { return playerGamesScored[_player]; } // Is a player registered? function playerIsRegistered(address _player) public view returns (bool) { return playerRegistered[_player]; } // What was the official result of a game? function correctResult(int8 _gameID) public view returns (string) { return gameResult[_gameID]; } // What was the caller&#39;s prediction for a given game? function playerGuess(int8 _gameID) public view returns (string) { return playerPredictions[msg.sender][_gameID]; } /* ADMINISTRATOR FUNCTIONS FOR COMPETITION MAINTENANCE */ modifier isAdministrator() { address _sender = msg.sender; if (_sender == administrator) { _; } else { revert(); } } // As new fixtures become known through progression or elimination, they&#39;re added here. function addNewGame(string _opponents, int8 _gameID) isAdministrator public { worldCupGameID[_opponents] = _gameID; } // When the result of a game is known, enter the result. function logResult(int8 _gameID, string _winner) isAdministrator public { require((int8(0) < _gameID) && (_gameID <= 64) && _gameID == latestGameFinished + 1); // No draws allowed after the qualification stage. if (_gameID > 48 && equalStrings(_winner, "DRAW")) { revert(); } else { require(!gameFinished[_gameID]); gameFinished [_gameID] = true; gameResult [_gameID] = _winner; latestGameFinished = _gameID; assert(gameFinished[_gameID]); } } // Concludes the tournament and issues the prizes, then self-destructs. function concludeTournament(address _first // 40% Ether. , address _second // 30% Ether. , address _third // 20% Ether. , address _fourth) // 10% Ether. isAdministrator public { // Don&#39;t hand out prizes until the final&#39;s... actually been played. require(gameFinished[64] && playerIsRegistered(_first) && playerIsRegistered(_second) && playerIsRegistered(_third) && playerIsRegistered(_fourth)); // Send the money raised for Giveth. givethAddress.send(givethPool); // Determine 10% of the prize pool to distribute to winners. uint tenth = prizePool.div(10); _first.send (tenth.mul(4)); _second.send(tenth.mul(3)); _third.send (tenth.mul(2)); // Since there might be rounding errors, fourth place gets everything else. _fourth.send(address(this).balance); // Thanks for playing, everyone. selfdestruct(administrator); } // The emergency escape hatch in case something has gone wrong. Refunds 95% of purchase Ether // to all registered addresses: the other 0.01009 has been sent directly to the developer who can // handle sending that back to everyone using a script. // Let&#39;s hope this one doesn&#39;t have to get pulled, eh? function pullRipCord() isAdministrator public { uint players = playerList.length; for (uint i = 0; i < players; i++) { address _toRefund = playerList[i]; _toRefund.send(0.19171 ether); emit RipcordRefund(_toRefund); } selfdestruct(administrator); } /* INTERNAL FUNCTIONS */ // Gateway check - did you send exactly the right amount? function _isCorrectBuyin(uint _buyin) private pure returns (bool) { return _buyin == 0.2018 ether; } // Internal comparison between strings, returning 0 if equal, 1 otherwise. function compare(string _a, string _b) private pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } /// Compares two strings and returns true if and only if they are equal. function equalStrings(string _a, string _b) pure private returns (bool) { return compare(_a, _b) == 0; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function addint16(int16 a, int16 b) internal pure returns (int16) { int16 c = a + b; assert(c >= a); return c; } function addint256(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; assert(c >= a); return c; } }
Compares two strings and returns true if and only if they are equal.
function equalStrings(string _a, string _b) pure private returns (bool) { return compare(_a, _b) == 0; }
2,278,743
/** Telegram: https://t.me/pootokenerc Website: https://pootoken.co */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; 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 IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface 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); } contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @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); _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: * * - `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 = _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 Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library 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; } } 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; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. (easter egg from the genius dev @nomessages9.) */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { 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 IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Poo is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public buyBackWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool private gasLimitActive = true; uint256 private gasPriceLimit = 561 * 1 gwei; // do not allow over x gwei for launch // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyBuyBackFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellBuyBackFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForBuyBack; uint256 public tokensForDev; // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event BuyBackTriggered(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); constructor() ERC20("Poo", "Poo") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 10; uint256 _buyLiquidityFee = 2; uint256 _buyBuyBackFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee =22; uint256 _sellLiquidityFee = 2; uint256 _sellBuyBackFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWallet = totalSupply * 2 / 100; // 2% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBuyBackFee = _buyBuyBackFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBuyBackFee = _sellBuyBackFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(buyBackWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(buyBackWallet, true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyBuyBackFee = _buyBackFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; require(buyTotalFees <= 99, "Must keep fees at 99% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellBuyBackFee = _buyBackFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; require(sellTotalFees <= 99, "Must keep fees at 99% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else { require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForBuyBack += fees * sellBuyBackFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForBuyBack += fees * buyBuyBackFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForBuyBack + tokensForDev; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForBuyBack = ethBalance.mul(tokensForBuyBack).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBuyBack; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForBuyBack = 0; tokensForDev = 0; (bool success,) = address(marketingWallet).call{value: ethForMarketing}(""); (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } // keep leftover ETH for buyback only if there is a buyback fee, if not, send the remaining ETH to the marketing wallet if it accumulates if(buyBuyBackFee == 0 && sellBuyBackFee == 0 && address(this).balance >= 1 ether){ (success,) = address(marketingWallet).call{value: address(this).balance}(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } // useful for buybacks or to reclaim any ETH on the contract in a way that helps holders. function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(ethAmountInWei); } }
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); }
1,793
/** // IMPORTANT: Developer should update the ISecurityTokenRegistry.sol (Interface) if there is any change in function signature or addition/removal of the functions from SecurityTokenRegistry & STRGetter contract. // */ pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IOwnable.sol"; import "./interfaces/ISTFactory.sol"; import "./interfaces/ISecurityToken.sol"; import "./interfaces/IPolymathRegistry.sol"; import "./interfaces/IOracle.sol"; import "./storage/EternalStorage.sol"; import "./libraries/Util.sol"; import "./libraries/Encoder.sol"; import "./libraries/VersionUtils.sol"; import "./libraries/DecimalMath.sol"; import "./proxy/Proxy.sol"; /** * @title Registry contract for issuers to register their tickers and security tokens */ contract SecurityTokenRegistry is EternalStorage, Proxy { /** * @notice state variables address public polyToken; uint256 public stLaunchFee; uint256 public tickerRegFee; uint256 public expiryLimit; uint256 public latestProtocolVersion; bool public paused; address public owner; address public polymathRegistry; address[] public activeUsers; mapping(address => bool) public seenUsers; mapping(address => bytes32[]) userToTickers; mapping(string => address) tickerToSecurityToken; mapping(string => uint) tickerIndex; mapping(string => TickerDetails) registeredTickers; mapping(address => SecurityTokenData) securityTokens; mapping(bytes32 => address) protocolVersionST; mapping(uint256 => ProtocolVersion) versionData; struct ProtocolVersion { uint8 major; uint8 minor; uint8 patch; } struct TickerDetails { address owner; uint256 registrationDate; uint256 expiryDate; string tokenName; //Not stored since 3.0.0 bool status; } struct SecurityTokenData { string ticker; string tokenDetails; uint256 deployedAt; } */ using SafeMath for uint256; bytes32 constant INITIALIZE = 0x9ef7257c3339b099aacf96e55122ee78fb65a36bd2a6c19249882be9c98633bf; //keccak256("initialised") bytes32 constant POLYTOKEN = 0xacf8fbd51bb4b83ba426cdb12f63be74db97c412515797993d2a385542e311d7; //keccak256("polyToken") bytes32 constant STLAUNCHFEE = 0xd677304bb45536bb7fdfa6b9e47a3c58fe413f9e8f01474b0a4b9c6e0275baf2; //keccak256("stLaunchFee") bytes32 constant TICKERREGFEE = 0x2fcc69711628630fb5a42566c68bd1092bc4aa26826736293969fddcd11cb2d2; //keccak256("tickerRegFee") bytes32 constant EXPIRYLIMIT = 0x604268e9a73dfd777dcecb8a614493dd65c638bad2f5e7d709d378bd2fb0baee; //keccak256("expiryLimit") bytes32 constant PAUSED = 0xee35723ac350a69d2a92d3703f17439cbaadf2f093a21ba5bf5f1a53eb2a14d9; //keccak256("paused") bytes32 constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; //keccak256("owner") bytes32 constant POLYMATHREGISTRY = 0x90eeab7c36075577c7cc5ff366e389fefa8a18289b949bab3529ab4471139d4d; //keccak256("polymathRegistry") bytes32 constant STRGETTER = 0x982f24b3bd80807ec3cb227ba152e15c07d66855fa8ae6ca536e689205c0e2e9; //keccak256("STRGetter") bytes32 constant IS_FEE_IN_POLY = 0x7152e5426955da44af11ecd67fec5e2a3ba747be974678842afa9394b9a075b6; //keccak256("IS_FEE_IN_POLY") bytes32 constant ACTIVE_USERS = 0x425619ce6ba8e9f80f17c0ef298b6557e321d70d7aeff2e74dd157bd87177a9e; //keccak256("activeUsers") bytes32 constant LATEST_VERSION = 0x4c63b69b9117452b9f11af62077d0cda875fb4e2dbe07ad6f31f728de6926230; //keccak256("latestVersion") string constant POLY_ORACLE = "StablePolyUsdOracle"; // Emit when network becomes paused event Pause(address account); // Emit when network becomes unpaused event Unpause(address account); // Emit when the ticker is removed from the registry event TickerRemoved(string _ticker, address _removedBy); // Emit when the token ticker expiry is changed event ChangeExpiryLimit(uint256 _oldExpiry, uint256 _newExpiry); // Emit when changeSecurityLaunchFee is called event ChangeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee); // Emit when changeTickerRegistrationFee is called event ChangeTickerRegistrationFee(uint256 _oldFee, uint256 _newFee); // Emit when Fee currency is changed event ChangeFeeCurrency(bool _isFeeInPoly); // Emit when ownership gets transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Emit when ownership of the ticker gets changed event ChangeTickerOwnership(string _ticker, address indexed _oldOwner, address indexed _newOwner); // Emit at the time of launching a new security token of version 3.0+ event NewSecurityToken( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, bool _fromAdmin, uint256 _usdFee, uint256 _polyFee, uint256 _protocolVersion ); // Emit at the time of launching a new security token v2.0. // _registrationFee is in poly event NewSecurityToken( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, bool _fromAdmin, uint256 _registrationFee ); // Emit after ticker registration event RegisterTicker( address indexed _owner, string _ticker, uint256 indexed _registrationDate, uint256 indexed _expiryDate, bool _fromAdmin, uint256 _registrationFeePoly, uint256 _registrationFeeUsd ); // For backwards compatibility event RegisterTicker( address indexed _owner, string _ticker, string _name, uint256 indexed _registrationDate, uint256 indexed _expiryDate, bool _fromAdmin, uint256 _registrationFee ); // Emit at when issuer refreshes exisiting token event SecurityTokenRefreshed( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, uint256 _protocolVersion ); event ProtocolFactorySet(address indexed _STFactory, uint8 _major, uint8 _minor, uint8 _patch); event LatestVersionSet(uint8 _major, uint8 _minor, uint8 _patch); event ProtocolFactoryRemoved(address indexed _STFactory, uint8 _major, uint8 _minor, uint8 _patch); ///////////////////////////// // Modifiers ///////////////////////////// /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() internal view { require(msg.sender == owner(), "Only owner"); } modifier onlyOwnerOrSelf() { require(msg.sender == owner() || msg.sender == address(this), "Only owner or self"); _; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPausedOrOwner() { _whenNotPausedOrOwner(); _; } function _whenNotPausedOrOwner() internal view { if (msg.sender != owner()) { require(!isPaused(), "Paused"); } } /** * @notice Modifier to make a function callable only when the contract is not paused and ignore is msg.sender is owner. */ modifier whenNotPaused() { require(!isPaused(), "Paused"); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(isPaused(), "Not paused"); _; } ///////////////////////////// // Initialization ///////////////////////////// // Constructor constructor() public { set(INITIALIZE, true); } /** * @notice Initializes instance of STR * @param _polymathRegistry is the address of the Polymath Registry * @param _stLaunchFee is the fee in USD required to launch a token * @param _tickerRegFee is the fee in USD required to register a ticker * @param _owner is the owner of the STR, * @param _getterContract Contract address of the contract which consists getter functions. */ function initialize( address _polymathRegistry, uint256 _stLaunchFee, uint256 _tickerRegFee, address _owner, address _getterContract ) public { require(!getBoolValue(INITIALIZE),"Initialized"); require( _owner != address(0) && _polymathRegistry != address(0) && _getterContract != address(0), "Invalid address" ); set(STLAUNCHFEE, _stLaunchFee); set(TICKERREGFEE, _tickerRegFee); set(EXPIRYLIMIT, uint256(60 * 1 days)); set(PAUSED, false); set(OWNER, _owner); set(POLYMATHREGISTRY, _polymathRegistry); set(INITIALIZE, true); set(STRGETTER, _getterContract); _updateFromRegistry(); } /** * @notice Used to update the polyToken contract address */ function updateFromRegistry() external onlyOwner { _updateFromRegistry(); } function _updateFromRegistry() internal { address polymathRegistry = getAddressValue(POLYMATHREGISTRY); set(POLYTOKEN, IPolymathRegistry(polymathRegistry).getAddress("PolyToken")); } /** * @notice Converts USD fees into POLY amounts */ function _takeFee(bytes32 _feeType) internal returns (uint256, uint256) { (uint256 usdFee, uint256 polyFee) = getFees(_feeType); if (polyFee > 0) require(IERC20(getAddressValue(POLYTOKEN)).transferFrom(msg.sender, address(this), polyFee), "Insufficent allowance"); return (usdFee, polyFee); } /** * @notice Returns the usd & poly fee for a particular feetype * @param _feeType Key corresponding to fee type */ function getFees(bytes32 _feeType) public returns (uint256 usdFee, uint256 polyFee) { bool isFeesInPoly = getBoolValue(IS_FEE_IN_POLY); uint256 rawFee = getUintValue(_feeType); address polymathRegistry = getAddressValue(POLYMATHREGISTRY); uint256 polyRate = IOracle(IPolymathRegistry(polymathRegistry).getAddress(POLY_ORACLE)).getPrice(); if (!isFeesInPoly) { //Fee is in USD and not poly usdFee = rawFee; polyFee = DecimalMath.div(rawFee, polyRate); } else { usdFee = DecimalMath.mul(rawFee, polyRate); polyFee = rawFee; } } /** * @notice Gets the security token launch fee * @return Fee amount */ function getSecurityTokenLaunchFee() public returns(uint256 polyFee) { (, polyFee) = getFees(STLAUNCHFEE); } /** * @notice Gets the ticker registration fee * @return Fee amount */ function getTickerRegistrationFee() public returns(uint256 polyFee) { (, polyFee) = getFees(TICKERREGFEE); } /** * @notice Set the getter contract address * @param _getterContract Address of the contract */ function setGetterRegistry(address _getterContract) public onlyOwnerOrSelf { require(_getterContract != address(0)); set(STRGETTER, _getterContract); } function _implementation() internal view returns(address) { return getAddressValue(STRGETTER); } ///////////////////////////// // Token Ticker Management ///////////////////////////// /** * @notice Registers the token ticker to the selected owner * @notice Once the token ticker is registered to its owner then no other issuer can claim * @notice its ownership. If the ticker expires and its issuer hasn't used it, then someone else can take it. * @param _owner is address of the owner of the token * @param _ticker is unique token ticker */ function registerNewTicker(address _owner, string memory _ticker) public whenNotPausedOrOwner { require(_owner != address(0), "Bad address"); require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Bad ticker"); // Attempt to charge the reg fee if it is > 0 USD (uint256 usdFee, uint256 polyFee) = _takeFee(TICKERREGFEE); string memory ticker = Util.upper(_ticker); require(tickerAvailable(ticker), "Ticker reserved"); // Check whether ticker was previously registered (and expired) address previousOwner = _tickerOwner(ticker); if (previousOwner != address(0)) { _deleteTickerOwnership(previousOwner, ticker); } /*solium-disable-next-line security/no-block-members*/ _addTicker(_owner, ticker, now, now.add(getUintValue(EXPIRYLIMIT)), false, false, polyFee, usdFee); } /** * @dev This function is just for backwards compatibility */ function registerTicker(address _owner, string calldata _ticker, string calldata _tokenName) external { registerNewTicker(_owner, _ticker); (, uint256 polyFee) = getFees(TICKERREGFEE); emit RegisterTicker(_owner, _ticker, _tokenName, now, now.add(getUintValue(EXPIRYLIMIT)), false, polyFee); } /** * @notice Internal - Sets the details of the ticker */ function _addTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status, bool _fromAdmin, uint256 _polyFee, uint256 _usdFee ) internal { _setTickerOwnership(_owner, _ticker); _storeTickerDetails(_ticker, _owner, _registrationDate, _expiryDate, _status); emit RegisterTicker(_owner, _ticker, _registrationDate, _expiryDate, _fromAdmin, _polyFee, _usdFee); } /** * @notice Modifies the ticker details. Only Polymath has the ability to do so. * @notice Only allowed to modify the tickers which are not yet deployed. * @param _owner is the owner of the token * @param _ticker is the token ticker * @param _registrationDate is the date at which ticker is registered * @param _expiryDate is the expiry date for the ticker * @param _status is the token deployment status */ function modifyExistingTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status ) public onlyOwner { require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Bad ticker"); require(_expiryDate != 0 && _registrationDate != 0, "Bad dates"); require(_registrationDate <= _expiryDate, "Bad dates"); require(_owner != address(0), "Bad address"); string memory ticker = Util.upper(_ticker); _modifyTicker(_owner, ticker, _registrationDate, _expiryDate, _status); } /** * @dev This function is just for backwards compatibility */ function modifyTicker( address _owner, string calldata _ticker, string calldata _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status ) external { modifyExistingTicker(_owner, _ticker, _registrationDate, _expiryDate, _status); emit RegisterTicker(_owner, _ticker, _tokenName, now, now.add(getUintValue(EXPIRYLIMIT)), false, 0); } /** * @notice Internal -- Modifies the ticker details. */ function _modifyTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status ) internal { address currentOwner = _tickerOwner(_ticker); if (currentOwner != address(0)) { _deleteTickerOwnership(currentOwner, _ticker); } if (_tickerStatus(_ticker) && !_status) { set(Encoder.getKey("tickerToSecurityToken", _ticker), address(0)); } // If status is true, there must be a security token linked to the ticker already if (_status) { require(getAddressValue(Encoder.getKey("tickerToSecurityToken", _ticker)) != address(0), "Not registered"); } _addTicker(_owner, _ticker, _registrationDate, _expiryDate, _status, true, uint256(0), uint256(0)); } function _tickerOwner(string memory _ticker) internal view returns(address) { return getAddressValue(Encoder.getKey("registeredTickers_owner", _ticker)); } /** * @notice Removes the ticker details, associated ownership & security token mapping * @param _ticker is the token ticker */ function removeTicker(string memory _ticker) public onlyOwner { string memory ticker = Util.upper(_ticker); address owner = _tickerOwner(ticker); require(owner != address(0), "Bad ticker"); _deleteTickerOwnership(owner, ticker); set(Encoder.getKey("tickerToSecurityToken", ticker), address(0)); _storeTickerDetails(ticker, address(0), 0, 0, false); /*solium-disable-next-line security/no-block-members*/ emit TickerRemoved(ticker, msg.sender); } /** * @notice Checks if the entered ticker is registered and has not expired * @param _ticker is the token ticker * @return bool */ function tickerAvailable(string memory _ticker) public view returns(bool) { if (_tickerOwner(_ticker) != address(0)) { /*solium-disable-next-line security/no-block-members*/ if ((now > getUintValue(Encoder.getKey("registeredTickers_expiryDate", _ticker))) && !_tickerStatus(_ticker)) { return true; } else return false; } return true; } function _tickerStatus(string memory _ticker) internal view returns(bool) { return getBoolValue(Encoder.getKey("registeredTickers_status", _ticker)); } /** * @notice Internal - Sets the ticker owner * @param _owner is the address of the owner of the ticker * @param _ticker is the ticker symbol */ function _setTickerOwnership(address _owner, string memory _ticker) internal { bytes32 _ownerKey = Encoder.getKey("userToTickers", _owner); uint256 length = uint256(getArrayBytes32(_ownerKey).length); pushArray(_ownerKey, Util.stringToBytes32(_ticker)); set(Encoder.getKey("tickerIndex", _ticker), length); bytes32 seenKey = Encoder.getKey("seenUsers", _owner); if (!getBoolValue(seenKey)) { pushArray(ACTIVE_USERS, _owner); set(seenKey, true); } } /** * @notice Internal - Stores the ticker details */ function _storeTickerDetails( string memory _ticker, address _owner, uint256 _registrationDate, uint256 _expiryDate, bool _status ) internal { bytes32 key = Encoder.getKey("registeredTickers_owner", _ticker); set(key, _owner); key = Encoder.getKey("registeredTickers_registrationDate", _ticker); set(key, _registrationDate); key = Encoder.getKey("registeredTickers_expiryDate", _ticker); set(key, _expiryDate); key = Encoder.getKey("registeredTickers_status", _ticker); set(key, _status); } /** * @notice Transfers the ownership of the ticker * @param _newOwner is the address of the new owner of the ticker * @param _ticker is the ticker symbol */ function transferTickerOwnership(address _newOwner, string memory _ticker) public whenNotPausedOrOwner { string memory ticker = Util.upper(_ticker); require(_newOwner != address(0), "Bad address"); bytes32 ownerKey = Encoder.getKey("registeredTickers_owner", ticker); require(getAddressValue(ownerKey) == msg.sender, "Only owner"); if (_tickerStatus(ticker)) require( IOwnable(getAddressValue(Encoder.getKey("tickerToSecurityToken", ticker))).owner() == _newOwner, "Owner mismatch" ); _deleteTickerOwnership(msg.sender, ticker); _setTickerOwnership(_newOwner, ticker); set(ownerKey, _newOwner); emit ChangeTickerOwnership(ticker, msg.sender, _newOwner); } /** * @notice Internal - Removes the owner of a ticker */ function _deleteTickerOwnership(address _owner, string memory _ticker) internal { uint256 index = uint256(getUintValue(Encoder.getKey("tickerIndex", _ticker))); bytes32 ownerKey = Encoder.getKey("userToTickers", _owner); bytes32[] memory tickers = getArrayBytes32(ownerKey); assert(index < tickers.length); assert(_tickerOwner(_ticker) == _owner); deleteArrayBytes32(ownerKey, index); if (getArrayBytes32(ownerKey).length > index) { bytes32 switchedTicker = getArrayBytes32(ownerKey)[index]; set(Encoder.getKey("tickerIndex", Util.bytes32ToString(switchedTicker)), index); } } /** * @notice Changes the expiry time for the token ticker. Only available to Polymath. * @param _newExpiry is the new expiry for newly generated tickers */ function changeExpiryLimit(uint256 _newExpiry) public onlyOwner { require(_newExpiry >= 1 days, "Bad dates"); emit ChangeExpiryLimit(getUintValue(EXPIRYLIMIT), _newExpiry); set(EXPIRYLIMIT, _newExpiry); } ///////////////////////////// // Security Token Management ///////////////////////////// /** * @notice Deploys an instance of a new Security Token of version 2.0 and records it to the registry * @dev this function is for backwards compatibilty with 2.0 dApp. * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible */ function generateSecurityToken( string calldata _name, string calldata _ticker, string calldata _tokenDetails, bool _divisible ) external { generateNewSecurityToken(_name, _ticker, _tokenDetails, _divisible, msg.sender, VersionUtils.pack(2, 0, 0)); } /** * @notice Deploys an instance of a new Security Token and records it to the registry * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible * @param _treasuryWallet Ethereum address which will holds the STs. * @param _protocolVersion Version of securityToken contract * - `_protocolVersion` is the packed value of uin8[3] array (it will be calculated offchain) * - if _protocolVersion == 0 then latest version of securityToken will be generated */ function generateNewSecurityToken( string memory _name, string memory _ticker, string memory _tokenDetails, bool _divisible, address _treasuryWallet, uint256 _protocolVersion ) public whenNotPausedOrOwner { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "Bad ticker"); require(_treasuryWallet != address(0), "0x0 not allowed"); if (_protocolVersion == 0) { _protocolVersion = getUintValue(LATEST_VERSION); } _ticker = Util.upper(_ticker); bytes32 statusKey = Encoder.getKey("registeredTickers_status", _ticker); require(!getBoolValue(statusKey), "Already deployed"); set(statusKey, true); address issuer = msg.sender; require(_tickerOwner(_ticker) == issuer, "Not authorised"); /*solium-disable-next-line security/no-block-members*/ require(getUintValue(Encoder.getKey("registeredTickers_expiryDate", _ticker)) >= now, "Ticker expired"); (uint256 _usdFee, uint256 _polyFee) = _takeFee(STLAUNCHFEE); address newSecurityTokenAddress = _deployToken(_name, _ticker, _tokenDetails, issuer, _divisible, _treasuryWallet, _protocolVersion); if (_protocolVersion == VersionUtils.pack(2, 0, 0)) { // For backwards compatibilty. Should be removed with an update when we disable st 2.0 generation. emit NewSecurityToken( _ticker, _name, newSecurityTokenAddress, issuer, now, issuer, false, _polyFee ); } else { emit NewSecurityToken( _ticker, _name, newSecurityTokenAddress, issuer, now, issuer, false, _usdFee, _polyFee, _protocolVersion ); } } /** * @notice Deploys an instance of a new Security Token and replaces the old one in the registry * This can be used to upgrade from version 2.0 of ST to 3.0 or in case something goes wrong with earlier ST * @dev This function needs to be in STR 3.0. Defined public to avoid stack overflow * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible */ function refreshSecurityToken( string memory _name, string memory _ticker, string memory _tokenDetails, bool _divisible, address _treasuryWallet ) public whenNotPausedOrOwner returns (address) { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "Bad ticker"); require(_treasuryWallet != address(0), "0x0 not allowed"); string memory ticker = Util.upper(_ticker); require(_tickerStatus(ticker), "not deployed"); address st = getAddressValue(Encoder.getKey("tickerToSecurityToken", ticker)); address stOwner = IOwnable(st).owner(); require(msg.sender == stOwner, "Unauthroized"); require(ISecurityToken(st).transfersFrozen(), "Transfers not frozen"); uint256 protocolVersion = getUintValue(LATEST_VERSION); address newSecurityTokenAddress = _deployToken(_name, ticker, _tokenDetails, stOwner, _divisible, _treasuryWallet, protocolVersion); emit SecurityTokenRefreshed( _ticker, _name, newSecurityTokenAddress, stOwner, now, stOwner, protocolVersion ); } function _deployToken( string memory _name, string memory _ticker, string memory _tokenDetails, address _issuer, bool _divisible, address _wallet, uint256 _protocolVersion ) internal returns(address newSecurityTokenAddress) { // In v2.x of STFactory, the final argument to deployToken is the PolymathRegistry. // In v3.x of STFactory, the final argument to deployToken is the Treasury wallet. uint8[] memory upperLimit = new uint8[](3); upperLimit[0] = 2; upperLimit[1] = 99; upperLimit[2] = 99; if (VersionUtils.lessThanOrEqual(VersionUtils.unpack(uint24(_protocolVersion)), upperLimit)) { _wallet = getAddressValue(POLYMATHREGISTRY); } newSecurityTokenAddress = ISTFactory(getAddressValue(Encoder.getKey("protocolVersionST", _protocolVersion))).deployToken( _name, _ticker, 18, _tokenDetails, _issuer, _divisible, _wallet ); /*solium-disable-next-line security/no-block-members*/ _storeSecurityTokenData(newSecurityTokenAddress, _ticker, _tokenDetails, now); set(Encoder.getKey("tickerToSecurityToken", _ticker), newSecurityTokenAddress); } /** * @notice Adds a new custom Security Token and saves it to the registry. (Token should follow the ISecurityToken interface) * @param _ticker is the ticker symbol of the security token * @param _owner is the owner of the token * @param _securityToken is the address of the securityToken * @param _tokenDetails is the off-chain details of the token * @param _deployedAt is the timestamp at which the security token is deployed */ function modifyExistingSecurityToken( string memory _ticker, address _owner, address _securityToken, string memory _tokenDetails, uint256 _deployedAt ) public onlyOwner { require(bytes(_ticker).length <= 10, "Bad ticker"); require(_deployedAt != 0 && _owner != address(0), "Bad data"); string memory ticker = Util.upper(_ticker); require(_securityToken != address(0), "Bad address"); uint256 registrationTime = getUintValue(Encoder.getKey("registeredTickers_registrationDate", ticker)); uint256 expiryTime = getUintValue(Encoder.getKey("registeredTickers_expiryDate", ticker)); if (registrationTime == 0) { /*solium-disable-next-line security/no-block-members*/ registrationTime = now; expiryTime = registrationTime.add(getUintValue(EXPIRYLIMIT)); } set(Encoder.getKey("tickerToSecurityToken", ticker), _securityToken); _modifyTicker(_owner, ticker, registrationTime, expiryTime, true); _storeSecurityTokenData(_securityToken, ticker, _tokenDetails, _deployedAt); emit NewSecurityToken( ticker, ISecurityToken(_securityToken).name(), _securityToken, _owner, _deployedAt, msg.sender, true, uint256(0), uint256(0), 0 ); } /** * @dev This function is just for backwards compatibility */ function modifySecurityToken( string calldata /* */, string calldata _ticker, address _owner, address _securityToken, string calldata _tokenDetails, uint256 _deployedAt ) external { modifyExistingSecurityToken(_ticker, _owner, _securityToken, _tokenDetails, _deployedAt); } /** * @notice Internal - Stores the security token details */ function _storeSecurityTokenData( address _securityToken, string memory _ticker, string memory _tokenDetails, uint256 _deployedAt ) internal { set(Encoder.getKey("securityTokens_ticker", _securityToken), _ticker); set(Encoder.getKey("securityTokens_tokenDetails", _securityToken), _tokenDetails); set(Encoder.getKey("securityTokens_deployedAt", _securityToken), _deployedAt); } /** * @notice Checks that Security Token is registered * @param _securityToken is the address of the security token * @return bool */ function isSecurityToken(address _securityToken) external view returns(bool) { return (keccak256(bytes(getStringValue(Encoder.getKey("securityTokens_ticker", _securityToken)))) != keccak256("")); } ///////////////////////////// // Ownership, lifecycle & Utility ///////////////////////////// /** * @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), "Bad address"); emit OwnershipTransferred(getAddressValue(OWNER), _newOwner); set(OWNER, _newOwner); } /** * @notice Called by the owner to pause, triggers stopped state */ function pause() external whenNotPaused onlyOwner { set(PAUSED, true); /*solium-disable-next-line security/no-block-members*/ emit Pause(msg.sender); } /** * @notice Called by the owner to unpause, returns to normal state */ function unpause() external whenPaused onlyOwner { set(PAUSED, false); /*solium-disable-next-line security/no-block-members*/ emit Unpause(msg.sender); } /** * @notice Sets the ticker registration fee in USD tokens. Only Polymath. * @param _tickerRegFee is the registration fee in USD tokens (base 18 decimals) */ function changeTickerRegistrationFee(uint256 _tickerRegFee) public onlyOwner { uint256 fee = getUintValue(TICKERREGFEE); require(fee != _tickerRegFee, "Bad fee"); _changeTickerRegistrationFee(fee, _tickerRegFee); } function _changeTickerRegistrationFee(uint256 _oldFee, uint256 _newFee) internal { emit ChangeTickerRegistrationFee(_oldFee, _newFee); set(TICKERREGFEE, _newFee); } /** * @notice Sets the ticker registration fee in USD tokens. Only Polymath. * @param _stLaunchFee is the registration fee in USD tokens (base 18 decimals) */ function changeSecurityLaunchFee(uint256 _stLaunchFee) public onlyOwner { uint256 fee = getUintValue(STLAUNCHFEE); require(fee != _stLaunchFee, "Bad fee"); _changeSecurityLaunchFee(fee, _stLaunchFee); } function _changeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee) internal { emit ChangeSecurityLaunchFee(_oldFee, _newFee); set(STLAUNCHFEE, _newFee); } /** * @notice Sets the ticker registration and ST launch fee amount and currency * @param _tickerRegFee is the ticker registration fee (base 18 decimals) * @param _stLaunchFee is the st generation fee (base 18 decimals) * @param _isFeeInPoly defines if the fee is in poly or usd */ function changeFeesAmountAndCurrency(uint256 _tickerRegFee, uint256 _stLaunchFee, bool _isFeeInPoly) public onlyOwner { uint256 tickerFee = getUintValue(TICKERREGFEE); uint256 stFee = getUintValue(STLAUNCHFEE); bool isOldFeesInPoly = getBoolValue(IS_FEE_IN_POLY); require(isOldFeesInPoly != _isFeeInPoly, "Currency unchanged"); _changeTickerRegistrationFee(tickerFee, _tickerRegFee); _changeSecurityLaunchFee(stFee, _stLaunchFee); emit ChangeFeeCurrency(_isFeeInPoly); set(IS_FEE_IN_POLY, _isFeeInPoly); } /** * @notice Reclaims all ERC20Basic compatible tokens * @param _tokenContract is the address of the token contract */ function reclaimERC20(address _tokenContract) public onlyOwner { require(_tokenContract != address(0), "Bad address"); IERC20 token = IERC20(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance), "Transfer failed"); } /** * @notice Changes the SecurityToken contract for a particular factory version * @notice Used only by Polymath to upgrade the SecurityToken contract and add more functionalities to future versions * @notice Changing versions does not affect existing tokens. * @param _STFactoryAddress is the address of the proxy. * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function setProtocolFactory(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { _setProtocolFactory(_STFactoryAddress, _major, _minor, _patch); } function _setProtocolFactory(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) internal { require(_STFactoryAddress != address(0), "Bad address"); uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); address stFactoryAddress = getAddressValue(Encoder.getKey("protocolVersionST", uint256(_packedVersion))); require(stFactoryAddress == address(0), "Already exists"); set(Encoder.getKey("protocolVersionST", uint256(_packedVersion)), _STFactoryAddress); emit ProtocolFactorySet(_STFactoryAddress, _major, _minor, _patch); } /** * @notice Removes a STFactory * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function removeProtocolFactory(uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); require(getUintValue(LATEST_VERSION) != _packedVersion, "Cannot remove latestVersion"); emit ProtocolFactoryRemoved(getAddressValue(Encoder.getKey("protocolVersionST", _packedVersion)), _major, _minor, _patch); set(Encoder.getKey("protocolVersionST", uint256(_packedVersion)), address(0)); } /** * @notice Changes the default protocol version * @notice Used only by Polymath to upgrade the SecurityToken contract and add more functionalities to future versions * @notice Changing versions does not affect existing tokens. * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function setLatestVersion(uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { _setLatestVersion(_major, _minor, _patch); } function _setLatestVersion(uint8 _major, uint8 _minor, uint8 _patch) internal { uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); require(getAddressValue(Encoder.getKey("protocolVersionST", _packedVersion)) != address(0), "No factory"); set(LATEST_VERSION, uint256(_packedVersion)); emit LatestVersionSet(_major, _minor, _patch); } /** * @notice Changes the PolyToken address. Only Polymath. * @param _newAddress is the address of the polytoken. */ function updatePolyTokenAddress(address _newAddress) public onlyOwner { require(_newAddress != address(0), "Bad address"); set(POLYTOKEN, _newAddress); } /** * @notice Check whether the registry is paused or not * @return bool */ function isPaused() public view returns(bool) { return getBoolValue(PAUSED); } /** * @notice Gets the owner of the contract * @return address owner */ function owner() public view returns(address) { return getAddressValue(OWNER); } }
Called by the owner to pause, triggers stopped state/
function pause() external whenNotPaused onlyOwner { set(PAUSED, true); emit Pause(msg.sender); }
12,533,506
./full_match/1/0xC383AAc4B3dC18D9ce08AB7F63B4632716F1e626/sources/src/contracts/AToken.sol
Transfers the aTokens between two users. Validates the transfer (ie checks for valid HF after the transfer) if required from The source address to The destination address amount The amount getting transferred validate True if the transfer needs to be validated, false otherwise/
function _transfer(address from, address to, uint256 amount, bool validate) internal virtual { address underlyingAsset = _underlyingAsset; uint256 index = POOL.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount, index); if (validate) { POOL.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount.rayDiv(index), index); }
3,095,120
./full_match/100/0xF78fc2ce4350aD99eE5C3409D94E8C38F2fAC1b0/sources/contracts/OrbisAlpha.sol
Used by community members (at least Editor role) to react to post shared in their communities _postID: Unique ID of the post to upvote/downvote _reaction: Type of reaction/ Make sure user hasn't voted yetrequire(memberReaction[_postID][msg.sender] > 0, "User already voted for this post"); Make sure the post hasn't been archived Save that the user has reacted Retrieve community ID Finding when the user started to be a memberuint _userBalance = _getReputationBalance(_communityID, msg.sender); We mint reputation token only if the member reacting already was a member when the post was created we mint some reputation If user wasn't member before we save the reaction but don't mint new reputation token for the post creator
) public onlyEditor(posts[_postID].communityID) { require(posts[_postID].archived == false, "You can't upvote/downvote an archived post"); memberReaction[_postID][msg.sender] = _reaction; uint _communityID = posts[_postID].communityID; bool wasMemberBefore = memberships[_getMembership(_communityID, msg.sender)].createdAt < posts[_postID].createdAt; int amount = communityReputationSettings[_communityID][_reaction]; function invite( uint _communityID, address _member } function setModerator( uint _communityID, address _member } function share( uint _communityID, string memory _metadata } function reply( string memory _metadata, uint _parentPostID } function react( uint _postID, uint _reaction if(wasMemberBefore == true) { if(amount < 0) { _burnReputation( _getReputationToken(_communityID), posts[_postID].creator, uint(amount)); _mintReputation( _getReputationToken(_communityID), posts[_postID].creator, uint(amount)); } } function invite( uint _communityID, address _member } function setModerator( uint _communityID, address _member } function share( uint _communityID, string memory _metadata } function reply( string memory _metadata, uint _parentPostID } function react( uint _postID, uint _reaction if(wasMemberBefore == true) { if(amount < 0) { _burnReputation( _getReputationToken(_communityID), posts[_postID].creator, uint(amount)); _mintReputation( _getReputationToken(_communityID), posts[_postID].creator, uint(amount)); } } } else { emit NewReaction(_postID, msg.sender, _reaction, block.timestamp); }
14,269,158
./partial_match/1/0xa5F5F3803f6174C94f71419834ab91dD2eb7963a/sources/FriendsFingersCrowdsale.sol
low level token purchase function calculate token amount to be created update state
function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase( msg.sender, beneficiary, weiAmount, tokens ); forwardFunds(); }
4,412,631
./partial_match/4/0x3a051d8EFA25D3E4490D16Fd01862492e1018Faf/sources/FrogUnionPool.sol
if(accumulateStake[msg.sender] > 0){
function stakeByPID(uint256 _pid, uint256 amount, address invitedBy) public checkOpen checkStartByPID(_pid) checkNotEndByPID(_pid) checkStakeToken updateRewardByPID(_pid, msg.sender){ setInvitedBy(invitedBy); if(firstMinStakeValue > 0 && poolInfo[_pid].accumulateStake[msg.sender] == 0){ require(amount >= firstMinStakeValue, "FROG-POOL: Cannot stake 0"); require(amount > 0 && amount >= minStakeValue, "FROG-POOL: Cannot stake lower than min stake value"); } poolInfo[_pid].totalSupply = poolInfo[_pid].totalSupply.add(amount); poolInfo[_pid].balances[msg.sender] = poolInfo[_pid].balances[msg.sender].add(amount); totalSupplyWrapper = totalSupplyWrapper.add(amount); balancesWrapper[msg.sender] = balancesWrapper[msg.sender].add(amount); accumulateStake[msg.sender] = accumulateStake[msg.sender].add(amount); poolInfo[_pid].accumulateStake[msg.sender] = poolInfo[_pid].accumulateStake[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); if(feeStake > 0){ frog.safeTransferFrom(msg.sender, rewardPool, feeStake); stats.incrIAIStats(STATS_TYPE_REWARD_FEE, address(frog), feeStake); stats.incrIAIStats(STATS_TYPE_REWARD_TOTAL, address(frog), feeStake); } if(stakeBurn > 0){ stakeToken.safeTransfer(rewardPool, amount); stats.incrIAIStats(STATS_TYPE_REWARD_BURN, address(stakeToken), amount); stats.incrIAIStats(STATS_TYPE_REWARD_TOTAL, address(stakeToken), amount); } emit Staked(msg.sender, amount); }
8,607,549
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import { ISuperfluid, ISuperToken } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol"; import { IConstantFlowAgreementV1 } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol"; /** * A simple stream sender contract */ contract StreamSender { event NewClaim(address recipient, int96 flowRate); // Superfluid framework addresses: https://docs.superfluid.finance/superfluid/networks/networks ISuperfluid public immutable host; IConstantFlowAgreementV1 public immutable cfa; // Pick a super token to be used ISuperToken public immutable token; // Fixed flow rate for the participant int96 internal immutable flowRate; // Fixed number of possible participants uint256 public immutable maxParticipants; uint256 public participants; address public owner; mapping(address => bool) private _recipients; constructor( ISuperfluid _host, IConstantFlowAgreementV1 _cfa, ISuperToken _token, int96 _flowRate, uint256 _maxParticipants ) { require(address(_host) != address(0), "SSender: host is empty"); require(address(_cfa) != address(0), "SSender: cfa is empty"); require( address(_token) != address(0), "SSender: superToken is empty" ); host = _host; cfa = _cfa; token = _token; flowRate = _flowRate; maxParticipants = _maxParticipants; owner = msg.sender; } function claim(address payable recipient) external { require(!_recipients[recipient], "StreamSender: Already claimed"); _recipients[recipient] = true; participants++; require(participants <= maxParticipants, "SSender: max out number of participants"); // send some gas token recipient.send( 1e17 /* 0.1 */); // send a flow host.callAgreement( cfa, abi.encodeWithSelector( cfa.createFlow.selector, token, recipient, flowRate, new bytes(0) ), "0x" ); emit NewClaim(recipient, flowRate); } function withdraw() external { require(msg.sender == owner, "SSender: not owner"); payable(msg.sender).send(address(this).balance); } receive() external payable { } }
send some gas token send a flow
function claim(address payable recipient) external { require(!_recipients[recipient], "StreamSender: Already claimed"); _recipients[recipient] = true; participants++; require(participants <= maxParticipants, "SSender: max out number of participants"); recipient.send( 1e17 /* 0.1 */); host.callAgreement( cfa, abi.encodeWithSelector( cfa.createFlow.selector, token, recipient, flowRate, new bytes(0) ), "0x" ); emit NewClaim(recipient, flowRate); }
2,513,878
./partial_match/1/0x96177e14d13888d42661A218851028b166769883/sources/TokenSale.sol
Send tokens back to the sender using predefined exchange rateCommissions
function buyToken(address _recommenderAddress) external payable { uint256 tokens = msg.value.mul(multiplier).div(divisor); require(tokens <= token.balanceOf(address(this)), "Insufficient tokens for you to purchase"); require(msg.sender != _recommenderAddress,"You cannot recommend yourself"); if(_recommenderAddress == address(0)){ token.transfer(msg.sender, tokens); token.transfer(msg.sender, tokens); uint256 commissions = tokens.mul(commissionMultiplier).div(commissionDivisor); token.transfer(_recommenderAddress, commissions); } emit purchaseEvent(msg.sender, _recommenderAddress, tokens); }
15,556,895
pragma solidity ^0.5.1; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address ) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Select * @dev Median Selection Library */ library Select { using SafeMath for uint256; /** * @dev Sorts the input array up to the denoted size, and returns the median. * @param array Input array to compute its median. * @param size Number of elements in array to compute the median for. * @return Median of array. */ function computeMedian(uint256[] memory array, uint256 size) internal view returns (uint256) { require(size > 0 && array.length >= size); for (uint256 i = 1; i < size; i++) { for (uint256 j = i; j > 0 && array[j-1] > array[j]; j--) { uint256 tmp = array[j]; array[j] = array[j-1]; array[j-1] = tmp; } } if (size % 2 == 1) { uint256 ans = array[size / 2]; require(ans > 0, "must be posotive"); return ans; } else { uint256 ans2 = array[size / 2].add(array[size / 2 - 1]) / 2; require(ans2 > 0, "must be posotive"); return ans2; } } } interface IOracle { function getData() external returns (uint256, bool,address[] memory); } /** * @title sap Oracle * * @notice Provides a value onchain that's aggregated from a whitelisted set of * providers. */ contract sapOracle is Ownable, IOracle { using SafeMath for uint256; struct Report { uint256 timestamp; uint256 payload; } // uEquils address hardcoded address public uEquils; // Equilib address hardcoded address public Equilib; // Addresses of providers authorized to push reports. address[] public providers; // Addresses of the main providers. address[] public mainProviders; // Reports indexed by provider address. Report[0].timestamp > 0 // indicates provider existence. mapping (address => Report[2]) public providerReports; event ProviderAdded(address provider); event ProviderRemoved(address provider); event ReportTimestampOutOfRange(address provider); event ProviderReportPushed(address indexed provider, uint256 payload, uint256 timestamp); // The number of seconds after which the report is deemed expired. uint256 public reportExpirationTimeSec; // The number of seconds since reporting that has to pass before a report // is usable. /// Time between reports uint256 public reportDelaySec; // The minimum number of providers with valid reports to consider the // aggregate report valid. uint256 public minimumProviders = 1; // Timestamp of 1 is used to mark uninitialized and invalidated data. // This is needed so that timestamp of 1 is always considered expired. uint256 private constant MAX_REPORT_EXPIRATION_TIME = 520 weeks; /** * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. * @param reportDelaySec_ The number of seconds since reporting that has to * pass before a report is usable * @param minimumProviders_ The minimum number of providers with valid * reports to consider the aggregate report valid. */ constructor(uint256 reportExpirationTimeSec_, uint256 reportDelaySec_, uint256 minimumProviders_) public { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME); require(minimumProviders_ > 0); reportExpirationTimeSec = reportExpirationTimeSec_; reportDelaySec = reportDelaySec_; minimumProviders = minimumProviders_; } /** * @notice Sets the report expiration period. * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. */ function setReportExpirationTimeSec(uint256 reportExpirationTimeSec_) external onlyOwner { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME); reportExpirationTimeSec = reportExpirationTimeSec_; } /** * @notice Sets the time period since reporting that has to pass before a * report is usable. * @param reportDelaySec_ The new delay period in seconds. */ function setReportDelaySec(uint256 reportDelaySec_) external onlyOwner { reportDelaySec = reportDelaySec_; } /** * @notice Sets the minimum number of providers with valid reports to * consider the aggregate report valid. * @param minimumProviders_ The new minimum number of providers. */ function setMinimumProviders(uint256 minimumProviders_) external onlyOwner { require(minimumProviders_ > 0); minimumProviders = minimumProviders_; } /** * @notice Pushes a report for the calling provider. * @param payload is expected to be 18 decimal fixed point number. */ function pushReport(uint256 payload) external { require(payload > 0 ,"price must be positive"); address providerAddress = msg.sender; Report[2] storage reports = providerReports[providerAddress]; uint256[2] memory timestamps = [reports[0].timestamp, reports[1].timestamp]; require(timestamps[0] > 0); uint8 index_recent = timestamps[0] >= timestamps[1] ? 0 : 1; uint8 index_past = 1 - index_recent; // Check that the push is not too soon after the last one. require(timestamps[index_recent].add(reportDelaySec) <= now); reports[index_past].timestamp = now; reports[index_past].payload = payload; emit ProviderReportPushed(providerAddress, payload, now); } /** * @notice Invalidates the reports of the calling provider. */ function purgeReports() external { address providerAddress = msg.sender; require (providerReports[providerAddress][0].timestamp > 0); providerReports[providerAddress][0].timestamp=1; providerReports[providerAddress][1].timestamp=1; } /** * @notice Computes median of provider reports whose timestamps are in the * valid timestamp range. * @return AggregatedValue: Median of providers reported values. * valid: Boolean indicating an aggregated value was computed successfully. */ uint256 public index = 0; uint256 public mainCount =0; uint256 public regularNodes; uint256 public size ; address public nodeAddress; address public MainAddress; address[] public validReportsOwners; uint256 public nodeIndex; uint256[] public validReports; function getData() external returns (uint256, bool,address[] memory) { require(mainProviders.length > 0, "min 1 mainProvider"); require(providers.length > 1, "min 2 Providers (1 main 1 reg)"); size=0; MainAddress=address(0); regularNodes=0; validReports.length = 0; validReportsOwners.length = 0; nodeAddress= address(0); nodeIndex=0; mainCount =0; index=0; uint256 reportsCount = providers.length; uint256 minValidTimestamp = now.sub(reportExpirationTimeSec); uint256 maxValidTimestamp = now.sub(reportDelaySec); for (uint256 i = 0; i < reportsCount; i++) { address providerAddress = providers[i]; Report[2] memory reports = providerReports[providerAddress]; uint8 index_recent = reports[0].timestamp >= reports[1].timestamp ? 0 : 1; uint8 index_past = 1 - index_recent; uint256 reportTimestampRecent = reports[index_recent].timestamp; if (reportTimestampRecent > maxValidTimestamp) { // Recent report is too recent. uint256 reportTimestampPast = providerReports[providerAddress][index_past].timestamp; if (reportTimestampPast < minValidTimestamp) { // Past report is too old. emit ReportTimestampOutOfRange(providerAddress); } else if (reportTimestampPast > maxValidTimestamp) { // Past report is too recent. emit ReportTimestampOutOfRange(providerAddress); } else { // Using past report. validReportsOwners.push(providerAddress); validReports.push(providerReports[providerAddress][index_past].payload); size++; for (uint256 j = 0; j < mainProviders.length; j++) { if(mainProviders[j] == providerAddress){ MainAddress = mainProviders[j]; index = index_past; mainCount++; } if(mainProviders[j] != providerAddress){ nodeAddress = providerAddress; nodeIndex = index_past; } } } } else { // Recent report is not too recent. if (reportTimestampRecent < minValidTimestamp) { // Recent report is too old. emit ReportTimestampOutOfRange(providerAddress); } else { // Using recent report. validReportsOwners.push(providerAddress); validReports.push(providerReports[providerAddress][index_recent].payload); size++; for (uint256 j = 0; j < mainProviders.length; j++) { if(mainProviders[j] == providerAddress){ MainAddress = mainProviders[j]; index = index_recent; mainCount++; } if(mainProviders[j] != providerAddress){ nodeAddress = providerAddress; nodeIndex = index_recent; } } } } } if (size < minimumProviders) { return (0, false,validReportsOwners); } regularNodes = validReports.length - mainCount; if(regularNodes == 0 || mainCount == 0 ) { return (0, false,validReportsOwners); } if((regularNodes - 1) == mainCount){ return (Select.computeMedian(validReports, size), true,validReportsOwners); } if(regularNodes != mainCount){ while((regularNodes - 1) > mainCount){ validReports.push(providerReports[mainProviders[0]][index].payload); size++; mainCount++; } while((regularNodes - 1) < mainCount){ validReports.push(providerReports[nodeAddress][nodeIndex].payload); size++; regularNodes++; } return (Select.computeMedian(validReports, size), true,validReportsOwners); } validReports.push(providerReports[nodeAddress][nodeIndex].payload); size++; return (Select.computeMedian(validReports, size), true,validReportsOwners); } function setEquils(address Equilis_,address EquilibAddress) external onlyOwner { Equilib = EquilibAddress; uEquils = Equilis_; } /** * @notice Authorizes a provider. * @param provider Address of the provider. */ function addProvider(address provider) external { require(msg.sender == Equilib, "Only Equilib can add providers"); require(providerReports[provider][0].timestamp == 0); providers.push(provider); providerReports[provider][0].timestamp = 1; emit ProviderAdded(provider); } function addMainProvider(address provider) external onlyOwner { mainProviders.push(provider); emit ProviderAdded(provider); } /** * @notice Revokes provider authorization. * @param provider Address of the provider. */ function removeProvider(address provider) external onlyOwner { delete providerReports[provider]; for (uint256 i = 0; i < providers.length; i++) { if (providers[i] == provider) { if (i + 1 != providers.length) { providers[i] = providers[providers.length-1]; } providers.length--; emit ProviderRemoved(provider); break; } } } /** * @return The number of authorized providers. */ function providersSize() external view returns (uint256) { return providers.length; } }
Recent report is too recent. Past report is too old. Past report is too recent. Using past report. Recent report is not too recent. Recent report is too old. Using recent report.
function getData() external returns (uint256, bool,address[] memory) { require(mainProviders.length > 0, "min 1 mainProvider"); require(providers.length > 1, "min 2 Providers (1 main 1 reg)"); size=0; MainAddress=address(0); regularNodes=0; validReports.length = 0; validReportsOwners.length = 0; nodeAddress= address(0); nodeIndex=0; mainCount =0; index=0; uint256 reportsCount = providers.length; uint256 minValidTimestamp = now.sub(reportExpirationTimeSec); uint256 maxValidTimestamp = now.sub(reportDelaySec); for (uint256 i = 0; i < reportsCount; i++) { address providerAddress = providers[i]; Report[2] memory reports = providerReports[providerAddress]; uint8 index_recent = reports[0].timestamp >= reports[1].timestamp ? 0 : 1; uint8 index_past = 1 - index_recent; uint256 reportTimestampRecent = reports[index_recent].timestamp; if (reportTimestampRecent > maxValidTimestamp) { uint256 reportTimestampPast = providerReports[providerAddress][index_past].timestamp; if (reportTimestampPast < minValidTimestamp) { emit ReportTimestampOutOfRange(providerAddress); emit ReportTimestampOutOfRange(providerAddress); validReportsOwners.push(providerAddress); validReports.push(providerReports[providerAddress][index_past].payload); size++; for (uint256 j = 0; j < mainProviders.length; j++) { if(mainProviders[j] == providerAddress){ MainAddress = mainProviders[j]; index = index_past; mainCount++; } if(mainProviders[j] != providerAddress){ nodeAddress = providerAddress; nodeIndex = index_past; } } } if (reportTimestampRecent < minValidTimestamp) { emit ReportTimestampOutOfRange(providerAddress); validReportsOwners.push(providerAddress); validReports.push(providerReports[providerAddress][index_recent].payload); size++; for (uint256 j = 0; j < mainProviders.length; j++) { if(mainProviders[j] == providerAddress){ MainAddress = mainProviders[j]; index = index_recent; mainCount++; } if(mainProviders[j] != providerAddress){ nodeAddress = providerAddress; nodeIndex = index_recent; } } } } } if (size < minimumProviders) { return (0, false,validReportsOwners); } regularNodes = validReports.length - mainCount; if(regularNodes == 0 || mainCount == 0 ) { return (0, false,validReportsOwners); } if((regularNodes - 1) == mainCount){ return (Select.computeMedian(validReports, size), true,validReportsOwners); } if(regularNodes != mainCount){ while((regularNodes - 1) > mainCount){ validReports.push(providerReports[mainProviders[0]][index].payload); size++; mainCount++; } while((regularNodes - 1) < mainCount){ validReports.push(providerReports[nodeAddress][nodeIndex].payload); size++; regularNodes++; } return (Select.computeMedian(validReports, size), true,validReportsOwners); } validReports.push(providerReports[nodeAddress][nodeIndex].payload); size++; return (Select.computeMedian(validReports, size), true,validReportsOwners); }
6,482,460
./full_match/97/0xfD77CC4b5f5A745481747e93167C9B114dA5d539/sources/project_/contracts/ForzaPresale.sol
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; } }
3,284,197
./full_match/80001/0x57a7e3773A66331427C0f2901ac1992906B2F3eF/sources/contracts/CrowdFunding.sol
check fees were sent to campaign
function donateToCampaign(uint256 _id, string memory note, string memory symbol) public payable { Campaign storage campaign = campaigns[_id]; require(campaign.deadline > block.timestamp, "The deadline for this campaign has passed."); uint256 amount = msg.value; require((msg.sender.balance) > amount, "Insufficient balance"); uint256 fees = amount / 100; require(feesSent, "Error transferring fees."); require(sentOther, "Error transferring funds to campaign owner."); campaign.amountCollected = campaign.amountCollected + (amount - fees); campaign.donators.push(msg.sender); campaign.donatorsNotes.push(note); campaign.donations.push(amount - fees); campaign.donationsCoins.push(symbol); }
9,453,942
// SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../interfaces/IBaseExchange.sol"; import "../interfaces/ITokenFactory.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IDividendPayingERC20.sol"; import "./ReentrancyGuardInitializable.sol"; import "../libraries/Signature.sol"; import "../interfaces/IERC2981.sol"; abstract contract BaseExchange is ReentrancyGuardInitializable, IBaseExchange { using SafeERC20 for IERC20; using Orders for Orders.Ask; using Orders for Orders.Bid; struct BestBid { address bidder; uint256 amount; uint256 price; address recipient; address referrer; uint256 timestamp; } mapping(address => mapping(bytes32 => mapping(address => bytes32))) internal _bidHashes; mapping(bytes32 => BestBid) public override bestBid; mapping(bytes32 => bool) public override isCancelledOrClaimed; mapping(bytes32 => uint256) public override amountFilled; function __BaseNFTExchange_init() internal initializer { __ReentrancyGuard_init(); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32); function factory() public view virtual override returns (address); function canTrade(address token) public view virtual override returns (bool) { return token == address(this); } function approvedBidHash( address proxy, bytes32 askHash, address bidder ) external view override returns (bytes32 bidHash) { return _bidHashes[proxy][askHash][bidder]; } function _transfer( address token, address from, address to, uint256 tokenId, uint256 amount ) internal virtual; function cancel(Orders.Ask memory order) external override { require(order.signer == msg.sender || order.proxy == msg.sender, "SHOYU: FORBIDDEN"); bytes32 hash = order.hash(); require(bestBid[hash].bidder == address(0), "SHOYU: BID_EXISTS"); isCancelledOrClaimed[hash] = true; emit Cancel(hash); } function updateApprovedBidHash( bytes32 askHash, address bidder, bytes32 bidHash ) external override { _bidHashes[msg.sender][askHash][bidder] = bidHash; emit UpdateApprovedBidHash(msg.sender, askHash, bidder, bidHash); } function bid(Orders.Ask memory askOrder, Orders.Bid memory bidOrder) external override nonReentrant returns (bool executed) { bytes32 askHash = askOrder.hash(); require(askHash == bidOrder.askHash, "SHOYU: UNMATCHED_HASH"); require(bidOrder.signer != address(0), "SHOYU: INVALID_SIGNER"); bytes32 bidHash = bidOrder.hash(); if (askOrder.proxy != address(0)) { require( askOrder.proxy == msg.sender || _bidHashes[askOrder.proxy][askHash][bidOrder.signer] == bidHash, "SHOYU: FORBIDDEN" ); delete _bidHashes[askOrder.proxy][askHash][bidOrder.signer]; emit UpdateApprovedBidHash(askOrder.proxy, askHash, bidOrder.signer, bytes32(0)); } Signature.verify(bidHash, bidOrder.signer, bidOrder.v, bidOrder.r, bidOrder.s, DOMAIN_SEPARATOR()); return _bid( askOrder, askHash, bidOrder.signer, bidOrder.amount, bidOrder.price, bidOrder.recipient, bidOrder.referrer ); } function bid( Orders.Ask memory askOrder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) external override nonReentrant returns (bool executed) { require(askOrder.proxy == address(0), "SHOYU: FORBIDDEN"); return _bid(askOrder, askOrder.hash(), msg.sender, bidAmount, bidPrice, bidRecipient, bidReferrer); } function _bid( Orders.Ask memory askOrder, bytes32 askHash, address bidder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) internal returns (bool executed) { require(canTrade(askOrder.token), "SHOYU: INVALID_EXCHANGE"); require(bidAmount > 0, "SHOYU: INVALID_AMOUNT"); uint256 _amountFilled = amountFilled[askHash]; require(_amountFilled + bidAmount <= askOrder.amount, "SHOYU: SOLD_OUT"); _validate(askOrder, askHash); Signature.verify(askHash, askOrder.signer, askOrder.v, askOrder.r, askOrder.s, DOMAIN_SEPARATOR()); BestBid storage best = bestBid[askHash]; if ( IStrategy(askOrder.strategy).canClaim( askOrder.proxy, askOrder.deadline, askOrder.params, bidder, bidPrice, best.bidder, best.price, best.timestamp ) ) { amountFilled[askHash] = _amountFilled + bidAmount; if (_amountFilled + bidAmount == askOrder.amount) isCancelledOrClaimed[askHash] = true; address recipient = askOrder.recipient; if (recipient == address(0)) recipient = askOrder.signer; require( _transferFeesAndFunds( askOrder.token, askOrder.tokenId, askOrder.currency, bidder, recipient, bidPrice * bidAmount ), "SHOYU: FAILED_TO_TRANSFER_FUNDS" ); if (bidRecipient == address(0)) bidRecipient = bidder; _transfer(askOrder.token, askOrder.signer, bidRecipient, askOrder.tokenId, bidAmount); emit Claim(askHash, bidder, bidAmount, bidPrice, bidRecipient, bidReferrer); return true; } else { if ( IStrategy(askOrder.strategy).canBid( askOrder.proxy, askOrder.deadline, askOrder.params, bidder, bidPrice, best.bidder, best.price, best.timestamp ) ) { best.bidder = bidder; best.amount = bidAmount; best.price = bidPrice; best.recipient = bidRecipient; best.referrer = bidReferrer; best.timestamp = block.timestamp; emit Bid(askHash, bidder, bidAmount, bidPrice, bidRecipient, bidReferrer); return false; } } revert("SHOYU: FAILURE"); } function claim(Orders.Ask memory askOrder) external override nonReentrant { require(canTrade(askOrder.token), "SHOYU: INVALID_EXCHANGE"); bytes32 askHash = askOrder.hash(); _validate(askOrder, askHash); Signature.verify(askHash, askOrder.signer, askOrder.v, askOrder.r, askOrder.s, DOMAIN_SEPARATOR()); BestBid memory best = bestBid[askHash]; require( IStrategy(askOrder.strategy).canClaim( askOrder.proxy, askOrder.deadline, askOrder.params, best.bidder, best.price, best.bidder, best.price, best.timestamp ), "SHOYU: FAILURE" ); address recipient = askOrder.recipient; if (recipient == address(0)) recipient = askOrder.signer; isCancelledOrClaimed[askHash] = true; require( _transferFeesAndFunds( askOrder.token, askOrder.tokenId, askOrder.currency, best.bidder, recipient, best.price * best.amount ), "SHOYU: FAILED_TO_TRANSFER_FUNDS" ); amountFilled[askHash] = amountFilled[askHash] + best.amount; address bidRecipient = best.recipient; if (bidRecipient == address(0)) bidRecipient = best.bidder; _transfer(askOrder.token, askOrder.signer, bidRecipient, askOrder.tokenId, best.amount); delete bestBid[askHash]; emit Claim(askHash, best.bidder, best.amount, best.price, bidRecipient, best.referrer); } function _validate(Orders.Ask memory askOrder, bytes32 askHash) internal view { require(!isCancelledOrClaimed[askHash], "SHOYU: CANCELLED_OR_CLAIMED"); require(askOrder.signer != address(0), "SHOYU: INVALID_MAKER"); require(askOrder.token != address(0), "SHOYU: INVALID_NFT"); require(askOrder.amount > 0, "SHOYU: INVALID_AMOUNT"); require(askOrder.strategy != address(0), "SHOYU: INVALID_STRATEGY"); require(askOrder.currency != address(0), "SHOYU: INVALID_CURRENCY"); require(ITokenFactory(factory()).isStrategyWhitelisted(askOrder.strategy), "SHOYU: STRATEGY_NOT_WHITELISTED"); } function _transferFeesAndFunds( address token, uint256 tokenId, address currency, address from, address to, uint256 amount ) internal returns (bool) { if (!_safeTransferFrom(currency, from, address(this), amount)) { return false; } address _factory = factory(); uint256 remainder = amount; { (address protocolFeeRecipient, uint8 protocolFeePermil) = ITokenFactory(_factory).protocolFeeInfo(); uint256 protocolFeeAmount = (amount * protocolFeePermil) / 1000; IERC20(currency).safeTransfer(protocolFeeRecipient, protocolFeeAmount); remainder -= protocolFeeAmount; } { (address operationalFeeRecipient, uint8 operationalFeePermil) = ITokenFactory(_factory).operationalFeeInfo(); uint256 operationalFeeAmount = (amount * operationalFeePermil) / 1000; IERC20(currency).safeTransfer(operationalFeeRecipient, operationalFeeAmount); remainder -= operationalFeeAmount; } try IERC2981(token).royaltyInfo(tokenId, amount) returns ( address royaltyFeeRecipient, uint256 royaltyFeeAmount ) { if (royaltyFeeAmount > 0) { remainder -= royaltyFeeAmount; _transferRoyaltyFee(currency, royaltyFeeRecipient, royaltyFeeAmount); } } catch {} IERC20(currency).safeTransfer(to, remainder); return true; } function _safeTransferFrom( address token, address from, address to, uint256 value ) private returns (bool) { (bool success, bytes memory returndata) = token.call(abi.encodeWithSelector(IERC20(token).transferFrom.selector, from, to, value)); return success && (returndata.length == 0 || abi.decode(returndata, (bool))); } function _transferRoyaltyFee( address currency, address to, uint256 amount ) internal { IERC20(currency).safeTransfer(to, amount); if (Address.isContract(to)) { try IDividendPayingERC20(to).sync() returns (uint256) {} catch {} } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../libraries/Orders.sol"; interface IBaseExchange { event Cancel(bytes32 indexed hash); event Claim( bytes32 indexed hash, address bidder, uint256 amount, uint256 price, address recipient, address referrer ); event Bid(bytes32 indexed hash, address bidder, uint256 amount, uint256 price, address recipient, address referrer); event UpdateApprovedBidHash( address indexed proxy, bytes32 indexed askHash, address indexed bidder, bytes32 bidHash ); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function canTrade(address token) external view returns (bool); function bestBid(bytes32 hash) external view returns ( address bidder, uint256 amount, uint256 price, address recipient, address referrer, uint256 blockNumber ); function isCancelledOrClaimed(bytes32 hash) external view returns (bool); function amountFilled(bytes32 hash) external view returns (uint256); function approvedBidHash( address proxy, bytes32 askHash, address bidder ) external view returns (bytes32 bidHash); function cancel(Orders.Ask memory order) external; function updateApprovedBidHash( bytes32 askHash, address bidder, bytes32 bidHash ) external; function bid(Orders.Ask memory askOrder, Orders.Bid memory bidOrder) external returns (bool executed); function bid( Orders.Ask memory askOrder, uint256 bidAmount, uint256 bidPrice, address bidRecipient, address bidReferrer ) external returns (bool executed); function claim(Orders.Ask memory order) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface ITokenFactory { event SetBaseURI721(string uri); event SetBaseURI1155(string uri); event SetProtocolFeeRecipient(address recipient); event SetOperationalFee(uint8 fee); event SetOperationalFeeRecipient(address recipient); event SetDeployerWhitelisted(address deployer, bool whitelisted); event SetStrategyWhitelisted(address strategy, bool whitelisted); event UpgradeNFT721(address newTarget); event UpgradeNFT1155(address newTarget); event UpgradeSocialToken(address newTarget); event UpgradeERC721Exchange(address exchange); event UpgradeERC1155Exchange(address exchange); event DeployNFT721AndMintBatch( address indexed proxy, address indexed owner, string name, string symbol, uint256[] tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ); event DeployNFT721AndPark( address indexed proxy, address indexed owner, string name, string symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ); event DeployNFT1155AndMintBatch( address indexed proxy, address indexed owner, uint256[] tokenIds, uint256[] amounts, address royaltyFeeRecipient, uint8 royaltyFee ); event DeploySocialToken( address indexed proxy, address indexed owner, string name, string symbol, address indexed dividendToken, uint256 initialSupply ); function MAX_ROYALTY_FEE() external view returns (uint8); function MAX_OPERATIONAL_FEE() external view returns (uint8); function PARK_TOKEN_IDS_721_TYPEHASH() external view returns (bytes32); function MINT_BATCH_721_TYPEHASH() external view returns (bytes32); function MINT_BATCH_1155_TYPEHASH() external view returns (bytes32); function MINT_SOCIAL_TOKEN_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address account) external view returns (uint256); function baseURI721() external view returns (string memory); function baseURI1155() external view returns (string memory); function erc721Exchange() external view returns (address); function erc1155Exchange() external view returns (address); function protocolFeeInfo() external view returns (address recipient, uint8 permil); function operationalFeeInfo() external view returns (address recipient, uint8 permil); function isStrategyWhitelisted(address strategy) external view returns (bool); function isDeployerWhitelisted(address strategy) external view returns (bool); function setBaseURI721(string memory uri) external; function setBaseURI1155(string memory uri) external; function setProtocolFeeRecipient(address protocolFeeRecipient) external; function setOperationalFeeRecipient(address operationalFeeRecipient) external; function setOperationalFee(uint8 operationalFee) external; function setDeployerWhitelisted(address deployer, bool whitelisted) external; function setStrategyWhitelisted(address strategy, bool whitelisted) external; function upgradeNFT721(address newTarget) external; function upgradeNFT1155(address newTarget) external; function upgradeSocialToken(address newTarget) external; function upgradeERC721Exchange(address exchange) external; function upgradeERC1155Exchange(address exchange) external; function deployNFT721AndMintBatch( address owner, string calldata name, string calldata symbol, uint256[] calldata tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function deployNFT721AndPark( address owner, string calldata name, string calldata symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function isNFT721(address query) external view returns (bool result); function deployNFT1155AndMintBatch( address owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external returns (address nft); function isNFT1155(address query) external view returns (bool result); function deploySocialToken( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external returns (address proxy); function isSocialToken(address query) external view returns (bool result); function parkTokenIds721( address nft, uint256 toTokenId, uint8 v, bytes32 r, bytes32 s ) external; function mintBatch721( address nft, address to, uint256[] calldata tokenIds, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external; function mintBatch1155( address nft, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external; function mintSocialToken( address token, address to, uint256 amount, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../libraries/Orders.sol"; interface IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 bestBidTimestamp ) external view returns (bool); function canBid( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 bestBidTimestamp ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IDividendPayingERC20 is IERC20, IERC20Metadata { /// @dev This event MUST emit when erc20/ether dividend is synced. /// @param increased The amount of increased erc20/ether in wei. event Sync(uint256 increased); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws erc20/ether from this contract. /// @param amount The amount of withdrawn erc20/ether in wei. event DividendWithdrawn(address indexed to, uint256 amount); function MAGNITUDE() external view returns (uint256); function dividendToken() external view returns (address); function totalDividend() external view returns (uint256); function sync() external payable returns (uint256 increased); function withdrawDividend() external; /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function dividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function withdrawableDividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has withdrawn. function withdrawnDividendOf(address account) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account) /// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has earned in total. function accumulativeDividendOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.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 ReentrancyGuardInitializable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. bool private constant _NOT_ENTERED = false; bool private constant _ENTERED = true; bool private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "SHOYU: REENTRANT"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IERC1271.sol"; import "@openzeppelin/contracts/utils/Address.sol"; library Signature { function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "SHOYU: INVALID_SIGNATURE_S_VALUE" ); require(v == 27 || v == 28, "SHOYU: INVALID_SIGNATURE_V_VALUE"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "SHOYU: INVALID_SIGNATURE"); return signer; } function verify( bytes32 hash, address signer, uint8 v, bytes32 r, bytes32 s, bytes32 domainSeparator ) internal view { bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hash)); if (Address.isContract(signer)) { require( IERC1271(signer).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, "SHOYU: UNAUTHORIZED" ); } else { require(recover(digest, v, r, s) == signer, "SHOYU: UNAUTHORIZED"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 is IERC165 { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } // 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; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; library Orders { // keccak256("Ask(address signer,address proxy,address token,uint256 tokenId,uint256 amount,address strategy,address currency,address recipient,uint256 deadline,bytes params)") bytes32 internal constant ASK_TYPEHASH = 0x5fbc9a24e1532fa5245d1ec2dc5592849ae97ac5475f361b1a1f7a6e2ac9b2fd; // keccak256("Bid(bytes32 askHash,address signer,uint256 amount,uint256 price,address recipient,address referrer)") bytes32 internal constant BID_TYPEHASH = 0xb98e1dc48988064e6dfb813618609d7da80a8841e5f277039788ac4b50d497b2; struct Ask { address signer; address proxy; address token; uint256 tokenId; uint256 amount; address strategy; address currency; address recipient; uint256 deadline; bytes params; uint8 v; bytes32 r; bytes32 s; } struct Bid { bytes32 askHash; address signer; uint256 amount; uint256 price; address recipient; address referrer; uint8 v; bytes32 r; bytes32 s; } function hash(Ask memory ask) internal pure returns (bytes32) { return keccak256( abi.encode( ASK_TYPEHASH, ask.signer, ask.proxy, ask.token, ask.tokenId, ask.amount, ask.strategy, ask.currency, ask.recipient, ask.deadline, keccak256(ask.params) ) ); } function hash(Bid memory bid) internal pure returns (bytes32) { return keccak256( abi.encode(BID_TYPEHASH, bid.askHash, bid.signer, bid.amount, bid.price, bid.recipient, bid.referrer) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title Interface for verifying contract-based account signatures /// @notice Interface that verifies provided signature for the data /// @dev Interface defined by EIP-1271 interface IERC1271 { /// @notice Returns whether the provided signature is valid for the provided data /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes. /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5). /// MUST allow external calls. /// @param hash Hash of the data to be signed /// @param signature Signature byte array associated with _data /// @return magicValue The bytes4 magic value 0x1626ba7e function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // 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.3; import "./interfaces/INFT721.sol"; import "./base/BaseNFT721.sol"; import "./base/BaseExchange.sol"; contract NFT721V0 is BaseNFT721, BaseExchange, IERC2981, INFT721 { uint8 internal _MAX_ROYALTY_FEE; address internal _royaltyFeeRecipient; uint8 internal _royaltyFee; // out of 1000 function initialize( address _owner, string memory _name, string memory _symbol, uint256[] memory tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_name, _symbol, _owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); for (uint256 i = 0; i < tokenIds.length; i++) { _safeMint(_owner, tokenIds[i]); } _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function initialize( address _owner, string memory _name, string memory _symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_name, _symbol, _owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); _parkTokenIds(toTokenId); emit ParkTokenIds(toTokenId); _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Initializable, IERC165) returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function DOMAIN_SEPARATOR() public view override(BaseNFT721, BaseExchange, INFT721) returns (bytes32) { return BaseNFT721.DOMAIN_SEPARATOR(); } function factory() public view override(BaseNFT721, BaseExchange, INFT721) returns (address) { return _factory; } function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) { uint256 royaltyAmount; if (_royaltyFee != type(uint8).max) royaltyAmount = (_salePrice * _royaltyFee) / 1000; return (_royaltyFeeRecipient, royaltyAmount); } function _transfer( address, address from, address to, uint256 tokenId, uint256 ) internal override { if (from == owner() && _parked(tokenId)) { _safeMint(to, tokenId); } else { _transfer(from, to, tokenId); } } function setRoyaltyFeeRecipient(address royaltyFeeRecipient) public override onlyOwner { _setRoyaltyFeeRecipient(royaltyFeeRecipient); } function setRoyaltyFee(uint8 royaltyFee) public override onlyOwner { _setRoyaltyFee(royaltyFee); } function _setRoyaltyFeeRecipient(address royaltyFeeRecipient) internal { require(royaltyFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _royaltyFeeRecipient = royaltyFeeRecipient; emit SetRoyaltyFeeRecipient(royaltyFeeRecipient); } function _setRoyaltyFee(uint8 royaltyFee) internal { if (_royaltyFee == type(uint8).max) { require(royaltyFee <= _MAX_ROYALTY_FEE, "SHOYU: INVALID_FEE"); } else { require(royaltyFee < _royaltyFee, "SHOYU: INVALID_FEE"); } _royaltyFee = royaltyFee; emit SetRoyaltyFee(royaltyFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IBaseNFT721.sol"; import "./IBaseExchange.sol"; interface INFT721 is IBaseNFT721, IBaseExchange { event SetRoyaltyFeeRecipient(address recipient); event SetRoyaltyFee(uint8 fee); function initialize( address _owner, string calldata _name, string calldata _symbol, uint256[] calldata tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external; function initialize( address _owner, string calldata _name, string calldata _symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external; function DOMAIN_SEPARATOR() external view override(IBaseNFT721, IBaseExchange) returns (bytes32); function factory() external view override(IBaseNFT721, IBaseExchange) returns (address); function setRoyaltyFeeRecipient(address _royaltyFeeRecipient) external; function setRoyaltyFee(uint8 _royaltyFee) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IBaseNFT721.sol"; import "../interfaces/IERC1271.sol"; import "../interfaces/ITokenFactory.sol"; import "../base/ERC721Initializable.sol"; import "../base/OwnableInitializable.sol"; import "../libraries/Signature.sol"; abstract contract BaseNFT721 is ERC721Initializable, OwnableInitializable, IBaseNFT721 { // keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad; // keccak256("Permit(address owner,address spender,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_ALL_TYPEHASH = 0xdaab21af31ece73a508939fedd476a5ee5129a5ed4bb091f3236ffb45394df62; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; address internal _factory; string internal __baseURI; mapping(uint256 => string) internal _uris; mapping(uint256 => uint256) public override nonces; mapping(address => uint256) public override noncesForAll; function initialize( string memory _name, string memory _symbol, address _owner ) public override initializer { __ERC721_init(_name, _symbol); __Ownable_init(_owner); _factory = msg.sender; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view virtual override returns (address) { return _factory; } function tokenURI(uint256 tokenId) public view override(ERC721Initializable, IERC721Metadata) returns (string memory) { require(_exists(tokenId) || _parked(tokenId), "SHOYU: INVALID_TOKEN_ID"); string memory _uri = _uris[tokenId]; if (bytes(_uri).length > 0) { return _uri; } else { string memory baseURI = __baseURI; if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json")); } else { baseURI = ITokenFactory(_factory).baseURI721(); string memory addy = Strings.toHexString(uint160(address(this)), 20); return string(abi.encodePacked(baseURI, addy, "/", Strings.toString(tokenId), ".json")); } } } function parked(uint256 tokenId) external view override returns (bool) { return _parked(tokenId); } function setTokenURI(uint256 id, string memory newURI) external override onlyOwner { _uris[id] = newURI; emit SetTokenURI(id, newURI); } function setBaseURI(string memory uri) external override onlyOwner { __baseURI = uri; emit SetBaseURI(uri); } function parkTokenIds(uint256 toTokenId) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _parkTokenIds(toTokenId); emit ParkTokenIds(toTokenId); } function mint( address to, uint256 tokenId, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _safeMint(to, tokenId, data); } function mintBatch( address to, uint256[] memory tokenIds, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); for (uint256 i = 0; i < tokenIds.length; i++) { _safeMint(to, tokenIds[i], data); } } function burn( uint256 tokenId, uint256 label, bytes32 data ) external override { require(ownerOf(tokenId) == msg.sender, "SHOYU: FORBIDDEN"); _burn(tokenId); emit Burn(tokenId, label, data); } function burnBatch(uint256[] memory tokenIds) external override { for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(ownerOf(tokenId) == msg.sender, "SHOYU: FORBIDDEN"); _burn(tokenId); } } function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); address owner = ownerOf(tokenId); require(owner != address(0), "SHOYU: INVALID_TOKENID"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, spender, tokenId, nonces[tokenId]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _approve(spender, tokenId); } function permitAll( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_ALL_TYPEHASH, owner, spender, noncesForAll[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _setApprovalForAll(owner, spender, true); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "./IOwnable.sol"; interface IBaseNFT721 is IERC721, IERC721Metadata, IOwnable { event SetTokenURI(uint256 indexed tokenId, string uri); event SetBaseURI(string uri); event ParkTokenIds(uint256 toTokenId); event Burn(uint256 indexed tokenId, uint256 indexed label, bytes32 data); function PERMIT_TYPEHASH() external view returns (bytes32); function PERMIT_ALL_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(uint256 tokenId) external view returns (uint256); function noncesForAll(address account) external view returns (uint256); function parked(uint256 tokenId) external view returns (bool); function initialize( string calldata name, string calldata symbol, address _owner ) external; function setTokenURI(uint256 id, string memory uri) external; function setBaseURI(string memory uri) external; function parkTokenIds(uint256 toTokenId) external; function mint( address to, uint256 tokenId, bytes calldata data ) external; function mintBatch( address to, uint256[] calldata tokenIds, bytes calldata data ) external; function burn( uint256 tokenId, uint256 label, bytes32 data ) external; function burnBatch(uint256[] calldata tokenIds) external; function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function permitAll( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IOwnable { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owner() external view returns (address); function renounceOwnership() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Initializable is Initializable, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Upper bound of tokenId parked uint256 private _toTokenIdParked; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(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), "SHOYU: INVALID_OWNER"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _owners[tokenId]; } /** * @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), "SHOYU: INVALID_TOKEN_ID"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. 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 = ERC721Initializable.ownerOf(tokenId); require(to != owner, "SHOYU: INVALID_TO"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "SHOYU: FORBIDDEN"); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "SHOYU: INVALID_TOKEN_ID"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(msg.sender, 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(msg.sender, tokenId), "SHOYU: NOT_APPROVED_NOR_OWNER"); _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(msg.sender, tokenId), "SHOYU: FORBIDDEN"); _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), "SHOYU: INVALID_RECEIVER"); } /** * @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), "SHOYU: INVALID_TOKEN_ID"); address owner = ERC721Initializable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _setApprovalForAll( address owner, address operator, bool approved ) internal { require(operator != owner, "SHOYU: INVALID_OPERATOR"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } function _parked(uint256 tokenId) internal view virtual returns (bool) { address owner = ERC721Initializable.ownerOf(tokenId); return owner == address(0) && tokenId < _toTokenIdParked; } function _parkTokenIds(uint256 toTokenId) internal virtual { uint256 fromTokenId = _toTokenIdParked; require(toTokenId > fromTokenId, "SHOYU: INVALID_TO_TOKEN_ID"); _toTokenIdParked = toTokenId; } /** * @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), "SHOYU: INVALID_RECEIVER"); } /** * @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), "SHOYU: INVALID_TO"); require(!_exists(tokenId), "SHOYU: 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 = ERC721Initializable.ownerOf(tokenId); require(owner != address(0), "SHOYU: INVALID_TOKEN_ID"); _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(ERC721Initializable.ownerOf(tokenId) == from, "SHOYU: TRANSFER_FORBIDDEN"); require(to != address(0), "SHOYU: INVALID_RECIPIENT"); _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(ERC721Initializable.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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("SHOYU: INVALID_RECEIVER"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 {} } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../interfaces/IOwnable.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 OwnableInitializable is Initializable, IOwnable { address private _owner; /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init(address __owner) internal initializer { __Ownable_init_unchained(__owner); } function __Ownable_init_unchained(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual override returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "SHOYU: FORBIDDEN"); _; } /** * @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 override 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 override onlyOwner { require(newOwner != address(0), "SHOYU: INVALID_NEW_OWNER"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // 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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/ITokenFactory.sol"; import "./interfaces/IBaseNFT721.sol"; import "./interfaces/IBaseNFT1155.sol"; import "./interfaces/ISocialToken.sol"; import "./base/ProxyFactory.sol"; import "./libraries/Signature.sol"; contract TokenFactory is ProxyFactory, Ownable, ITokenFactory { uint8 public constant override MAX_ROYALTY_FEE = 250; // 25% uint8 public constant override MAX_OPERATIONAL_FEE = 50; // 5% // keccak256("ParkTokenIds721(address nft,uint256 toTokenId,uint256 nonce)"); bytes32 public constant override PARK_TOKEN_IDS_721_TYPEHASH = 0x3fddacac0a7d8b05f741f01ff6becadd9986be8631a2af41a675f365dd74090d; // keccak256("MintBatch721(address nft,address to,uint256[] tokenIds,bytes data,uint256 nonce)"); bytes32 public constant override MINT_BATCH_721_TYPEHASH = 0x884adba7f4e17962aed36c871036adea39c6d9f81fb25407a78db239e9731e86; // keccak256("MintBatch1155(address nft,address to,uint256[] tokenIds,uint256[] amounts,bytes data,uint256 nonce)"); bytes32 public constant override MINT_BATCH_1155_TYPEHASH = 0xb47ce0f6456fcc2f16b7d6e7b0255eb73822b401248e672a4543c2b3d7183043; // keccak256("MintSocialToken(address token,address to,uint256 amount,uint256 nonce)"); bytes32 public constant override MINT_SOCIAL_TOKEN_TYPEHASH = 0x8f4bf92e5271f5ec2f59dc3fc74368af0064fb84b40a3de9150dd26c08cda104; bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address[] internal _targets721; address[] internal _targets1155; address[] internal _targetsSocialToken; address internal _protocolFeeRecipient; uint8 internal _protocolFee; // out of 1000 address internal _operationalFeeRecipient; uint8 internal _operationalFee; // out of 1000 mapping(address => uint256) public override nonces; string public override baseURI721; string public override baseURI1155; address public override erc721Exchange; address public override erc1155Exchange; // any account can deploy proxies if isDeployerWhitelisted[0x0000000000000000000000000000000000000000] == true mapping(address => bool) public override isDeployerWhitelisted; mapping(address => bool) public override isStrategyWhitelisted; modifier onlyDeployer { require(isDeployerWhitelisted[address(0)] || isDeployerWhitelisted[msg.sender], "SHOYU: FORBIDDEN"); _; } constructor( address protocolFeeRecipient, uint8 protocolFee, address operationalFeeRecipient, uint8 operationalFee, string memory _baseURI721, string memory _baseURI1155 ) { _protocolFeeRecipient = protocolFeeRecipient; _protocolFee = protocolFee; _operationalFeeRecipient = operationalFeeRecipient; _operationalFee = operationalFee; baseURI721 = _baseURI721; baseURI1155 = _baseURI1155; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function protocolFeeInfo() external view override returns (address recipient, uint8 permil) { return (_protocolFeeRecipient, _protocolFee); } function operationalFeeInfo() external view override returns (address recipient, uint8 permil) { return (_operationalFeeRecipient, _operationalFee); } // This function should be called with a proper param by a multi-sig `owner` function setBaseURI721(string memory uri) external override onlyOwner { baseURI721 = uri; emit SetBaseURI721(uri); } // This function should be called with a proper param by a multi-sig `owner` function setBaseURI1155(string memory uri) external override onlyOwner { baseURI1155 = uri; emit SetBaseURI1155(uri); } // This function should be called by a multi-sig `owner`, not an EOA function setProtocolFeeRecipient(address protocolFeeRecipient) external override onlyOwner { require(protocolFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _protocolFeeRecipient = protocolFeeRecipient; emit SetProtocolFeeRecipient(protocolFeeRecipient); } // This function should be called by a multi-sig `owner`, not an EOA function setOperationalFeeRecipient(address operationalFeeRecipient) external override onlyOwner { require(operationalFeeRecipient != address(0), "SHOYU: INVALID_RECIPIENT"); _operationalFeeRecipient = operationalFeeRecipient; emit SetOperationalFeeRecipient(operationalFeeRecipient); } // This function should be called by a multi-sig `owner`, not an EOA function setOperationalFee(uint8 operationalFee) external override onlyOwner { require(operationalFee <= MAX_OPERATIONAL_FEE, "SHOYU: INVALID_FEE"); _operationalFee = operationalFee; emit SetOperationalFee(operationalFee); } // This function should be called by a multi-sig `owner`, not an EOA function setDeployerWhitelisted(address deployer, bool whitelisted) external override onlyOwner { isDeployerWhitelisted[deployer] = whitelisted; emit SetDeployerWhitelisted(deployer, whitelisted); } // This function should be called by a multi-sig `owner`, not an EOA function setStrategyWhitelisted(address strategy, bool whitelisted) external override onlyOwner { require(strategy != address(0), "SHOYU: INVALID_ADDRESS"); isStrategyWhitelisted[strategy] = whitelisted; emit SetStrategyWhitelisted(strategy, whitelisted); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeNFT721(address newTarget) external override onlyOwner { _targets721.push(newTarget); emit UpgradeNFT721(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeNFT1155(address newTarget) external override onlyOwner { _targets1155.push(newTarget); emit UpgradeNFT1155(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeSocialToken(address newTarget) external override onlyOwner { _targetsSocialToken.push(newTarget); emit UpgradeSocialToken(newTarget); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeERC721Exchange(address exchange) external override onlyOwner { erc721Exchange = exchange; emit UpgradeERC721Exchange(exchange); } // This function should be called by a multi-sig `owner`, not an EOA function upgradeERC1155Exchange(address exchange) external override onlyOwner { erc1155Exchange = exchange; emit UpgradeERC1155Exchange(exchange); } function deployNFT721AndMintBatch( address owner, string calldata name, string calldata symbol, uint256[] memory tokenIds, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); nft = _createProxy( _targets721[_targets721.length - 1], abi.encodeWithSignature( "initialize(address,string,string,uint256[],address,uint8)", owner, name, symbol, tokenIds, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT721AndMintBatch(nft, owner, name, symbol, tokenIds, royaltyFeeRecipient, royaltyFee); } function deployNFT721AndPark( address owner, string calldata name, string calldata symbol, uint256 toTokenId, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); nft = _createProxy( _targets721[_targets721.length - 1], abi.encodeWithSignature( "initialize(address,string,string,uint256,address,uint8)", owner, name, symbol, toTokenId, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT721AndPark(nft, owner, name, symbol, toTokenId, royaltyFeeRecipient, royaltyFee); } function isNFT721(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targets721.length; i >= 1; i--) { if (_isProxy(_targets721[i - 1], query)) { return true; } } return false; } function deployNFT1155AndMintBatch( address owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external override onlyDeployer returns (address nft) { require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(tokenIds.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); nft = _createProxy( _targets1155[_targets1155.length - 1], abi.encodeWithSignature( "initialize(address,uint256[],uint256[],address,uint8)", owner, tokenIds, amounts, royaltyFeeRecipient, royaltyFee ) ); emit DeployNFT1155AndMintBatch(nft, owner, tokenIds, amounts, royaltyFeeRecipient, royaltyFee); } function isNFT1155(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targets1155.length; i >= 1; i--) { if (_isProxy(_targets1155[i - 1], query)) { return true; } } return false; } function deploySocialToken( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external override onlyDeployer returns (address proxy) { require(bytes(name).length > 0, "SHOYU: INVALID_NAME"); require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); bytes memory initData = abi.encodeWithSignature( "initialize(address,string,string,address,uint256)", owner, name, symbol, dividendToken, initialSupply ); proxy = _createProxy(_targetsSocialToken[_targetsSocialToken.length - 1], initData); emit DeploySocialToken(proxy, owner, name, symbol, dividendToken, initialSupply); } function isSocialToken(address query) external view override returns (bool result) { if (query == address(0)) return false; for (uint256 i = _targetsSocialToken.length; i >= 1; i--) { if (_isProxy(_targetsSocialToken[i - 1], query)) { return true; } } return false; } function parkTokenIds721( address nft, uint256 toTokenId, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT721(nft).owner(); bytes32 hash = keccak256(abi.encode(PARK_TOKEN_IDS_721_TYPEHASH, nft, toTokenId, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT721(nft).parkTokenIds(toTokenId); } function mintBatch721( address nft, address to, uint256[] calldata tokenIds, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT721(nft).owner(); bytes32 hash = keccak256(abi.encode(MINT_BATCH_721_TYPEHASH, nft, to, tokenIds, data, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT721(nft).mintBatch(to, tokenIds, data); } function mintBatch1155( address nft, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data, uint8 v, bytes32 r, bytes32 s ) external override { address owner = IBaseNFT1155(nft).owner(); bytes32 hash = keccak256(abi.encode(MINT_BATCH_1155_TYPEHASH, nft, to, tokenIds, amounts, data, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); IBaseNFT1155(nft).mintBatch(to, tokenIds, amounts, data); } function mintSocialToken( address token, address to, uint256 amount, uint8 v, bytes32 r, bytes32 s ) external override { address owner = ISocialToken(token).owner(); bytes32 hash = keccak256(abi.encode(MINT_SOCIAL_TOKEN_TYPEHASH, token, to, amount, nonces[owner]++)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); ISocialToken(token).mint(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "./IOwnable.sol"; interface IBaseNFT1155 is IERC1155, IERC1155MetadataURI, IOwnable { event SetURI(uint256 indexed id, string uri); event SetBaseURI(string uri); event Burn(uint256 indexed tokenId, uint256 amount, uint256 indexed label, bytes32 data); function PERMIT_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(address account) external view returns (uint256); function initialize(address _owner) external; function setURI(uint256 id, string memory uri) external; function setBaseURI(string memory baseURI) external; function mint( address to, uint256 tokenId, uint256 amount, bytes calldata data ) external; function mintBatch( address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) external; function burn( uint256 tokenId, uint256 amount, uint256 label, bytes32 data ) external; function burnBatch(uint256[] calldata tokenIds, uint256[] calldata amounts) external; function permit( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IDividendPayingERC20.sol"; import "./IOwnable.sol"; interface ISocialToken is IDividendPayingERC20, IOwnable { event Burn(uint256 amount, uint256 indexed label, bytes32 data); function initialize( address owner, string memory name, string memory symbol, address dividendToken, uint256 initialSupply ) external; function PERMIT_TYPEHASH() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function factory() external view returns (address); function nonces(address owner) external view returns (uint256); function mint(address account, uint256 value) external; function burn( uint256 value, uint256 id, bytes32 data ) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; // Reference: https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol contract ProxyFactory { function _createProxy(address target, bytes memory initData) internal returns (address proxy) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } if (initData.length > 0) { (bool success, ) = proxy.call(initData); require(success, "SHOYU: CALL_FAILURE"); } } function _isProxy(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../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 "../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.3; import "./interfaces/IPaymentSplitterFactory.sol"; import "./base/ProxyFactory.sol"; import "./PaymentSplitter.sol"; contract PaymentSplitterFactory is ProxyFactory, IPaymentSplitterFactory { address internal _target; constructor() { PaymentSplitter target = new PaymentSplitter(); address[] memory payees = new address[](1); payees[0] = msg.sender; uint256[] memory shares = new uint256[](1); shares[0] = 1; target.initialize("", payees, shares); _target = address(target); } function deployPaymentSplitter( address owner, string calldata title, address[] calldata payees, uint256[] calldata shares ) external override returns (address splitter) { splitter = _createProxy( _target, abi.encodeWithSignature("initialize(string,address[],uint256[])", title, payees, shares) ); emit DeployPaymentSplitter(owner, title, payees, shares, splitter); } function isPaymentSplitter(address query) external view override returns (bool result) { return _isProxy(_target, query); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IPaymentSplitterFactory { event DeployPaymentSplitter( address indexed owner, string title, address[] payees, uint256[] shares, address splitter ); function deployPaymentSplitter( address owner, string calldata title, address[] calldata payees, uint256[] calldata shares ) external returns (address splitter); function isPaymentSplitter(address query) external view returns (bool result); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./interfaces/IPaymentSplitter.sol"; import "./libraries/TokenHelper.sol"; // Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/finance/PaymentSplitter.sol contract PaymentSplitter is Initializable, IPaymentSplitter { using TokenHelper for address; string public override title; /** * @dev Getter for the total shares held by payees. */ uint256 public override totalShares; /** * @dev Getter for the total amount of token already released. */ mapping(address => uint256) public override totalReleased; /** * @dev Getter for the amount of shares held by an account. */ mapping(address => uint256) public override shares; /** * @dev Getter for the amount of token already released to a payee. */ mapping(address => mapping(address => uint256)) public override released; /** * @dev Getter for the address of the payee number `index`. */ address[] public override payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function initialize( string calldata _title, address[] calldata _payees, uint256[] calldata _shares ) external override initializer { require(_payees.length == _shares.length, "SHOYU: LENGTHS_NOT_EQUAL"); require(_payees.length > 0, "SHOYU: LENGTH_TOO_SHORT"); title = _title; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** * @dev Triggers a transfer to `account` of the amount of token they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address token, address account) external virtual override { require(shares[account] > 0, "SHOYU: FORBIDDEN"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased[token]; uint256 payment = (totalReceived * shares[account]) / totalShares - released[token][account]; require(payment != 0, "SHOYU: NO_PAYMENT"); released[token][account] += payment; totalReleased[token] += payment; token.safeTransfer(account, payment); emit PaymentReleased(token, account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param _shares The number of shares owned by the payee. */ function _addPayee(address account, uint256 _shares) private { require(account != address(0), "SHOYU: INVALID_ADDRESS"); require(_shares > 0, "SHOYU: INVALID_SHARES"); require(shares[account] == 0, "SHOYU: ALREADY_ADDED"); payees.push(account); shares[account] = _shares; totalShares = totalShares + _shares; emit PayeeAdded(account, _shares); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IPaymentSplitter { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address token, address to, uint256 amount); function initialize( string calldata _title, address[] calldata _payees, uint256[] calldata _shares ) external; function title() external view returns (string memory); function totalShares() external view returns (uint256); function totalReleased(address account) external view returns (uint256); function shares(address account) external view returns (uint256); function released(address token, address account) external view returns (uint256); function payees(uint256 index) external view returns (address); function release(address token, address account) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; library TokenHelper { using SafeERC20 for IERC20; address public constant ETH = 0x0000000000000000000000000000000000000000; function balanceOf(address token, address account) internal view returns (uint256) { if (token == ETH) { return account.balance; } else { return IERC20(token).balanceOf(account); } } function safeTransfer( address token, address to, uint256 amount ) internal { if (token == ETH) { (bool success, ) = to.call{value: amount}(""); require(success, "SHOYU: TRANSFER_FAILURE"); } else { IERC20(token).safeTransfer(to, amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev 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 { } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "../interfaces/IERC2981.sol"; contract ERC721RoyaltyMock is ERC721("Mock", "MOCK") { address public owner; constructor() { owner = msg.sender; } function safeMint( address to, uint256 tokenId, bytes memory data ) external { _safeMint(to, tokenId, data); } function safeMintBatch0( address[] calldata to, uint256[] calldata tokenId, bytes memory data ) external { require(to.length == tokenId.length); for (uint256 i = 0; i < to.length; i++) { _safeMint(to[i], tokenId[i], data); } } function safeMintBatch1( address to, uint256[] calldata tokenId, bytes memory data ) external { for (uint256 i = 0; i < tokenId.length; i++) { _safeMint(to, tokenId[i], data); } } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) { uint256 fee = 100; if (_tokenId < 10) fee = 10; return (owner, (_salePrice * fee) / 1000); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "./interfaces/INFT1155.sol"; import "./interfaces/IERC2981.sol"; import "./base/BaseNFT1155.sol"; import "./base/BaseExchange.sol"; contract NFT1155V0 is BaseNFT1155, BaseExchange, IERC2981, INFT1155 { uint8 internal _MAX_ROYALTY_FEE; address internal _royaltyFeeRecipient; uint8 internal _royaltyFee; // out of 1000 function initialize( address _owner, uint256[] memory tokenIds, uint256[] memory amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external override initializer { __BaseNFTExchange_init(); initialize(_owner); _MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE(); if (tokenIds.length > 0) { _mintBatch(_owner, tokenIds, amounts, ""); } _setRoyaltyFeeRecipient(royaltyFeeRecipient); _royaltyFee = type(uint8).max; if (royaltyFee != 0) _setRoyaltyFee(royaltyFee); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Initializable, IERC165) returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function DOMAIN_SEPARATOR() public view override(BaseNFT1155, BaseExchange, INFT1155) returns (bytes32) { return BaseNFT1155.DOMAIN_SEPARATOR(); } function factory() public view override(BaseNFT1155, BaseExchange, INFT1155) returns (address) { return _factory; } function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) { uint256 royaltyAmount; if (_royaltyFee != type(uint8).max) royaltyAmount = (_salePrice * _royaltyFee) / 1000; return (_royaltyFeeRecipient, royaltyAmount); } function _transfer( address, address from, address to, uint256 tokenId, uint256 amount ) internal override { _transfer(from, to, tokenId, amount); emit TransferSingle(msg.sender, from, to, tokenId, amount); } function setRoyaltyFeeRecipient(address royaltyFeeRecipient) public override onlyOwner { _setRoyaltyFeeRecipient(royaltyFeeRecipient); } function setRoyaltyFee(uint8 royaltyFee) public override onlyOwner { _setRoyaltyFee(royaltyFee); } function _setRoyaltyFeeRecipient(address royaltyFeeRecipient) internal { require(royaltyFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT"); _royaltyFeeRecipient = royaltyFeeRecipient; emit SetRoyaltyFeeRecipient(royaltyFeeRecipient); } function _setRoyaltyFee(uint8 royaltyFee) internal { if (_royaltyFee == type(uint8).max) { require(royaltyFee <= _MAX_ROYALTY_FEE, "SHOYU: INVALID_FEE"); } else { require(royaltyFee < _royaltyFee, "SHOYU: INVALID_FEE"); } _royaltyFee = royaltyFee; emit SetRoyaltyFee(royaltyFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IBaseNFT1155.sol"; import "./IBaseExchange.sol"; interface INFT1155 is IBaseNFT1155, IBaseExchange { event SetRoyaltyFeeRecipient(address recipient); event SetRoyaltyFee(uint8 fee); function initialize( address _owner, uint256[] calldata tokenIds, uint256[] calldata amounts, address royaltyFeeRecipient, uint8 royaltyFee ) external; function DOMAIN_SEPARATOR() external view override(IBaseNFT1155, IBaseExchange) returns (bytes32); function factory() external view override(IBaseNFT1155, IBaseExchange) returns (address); function setRoyaltyFeeRecipient(address _royaltyFeeRecipient) external; function setRoyaltyFee(uint8 _royaltyFee) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IBaseNFT1155.sol"; import "../interfaces/IERC1271.sol"; import "../interfaces/ITokenFactory.sol"; import "../base/ERC1155Initializable.sol"; import "../base/OwnableInitializable.sol"; import "../libraries/Signature.sol"; abstract contract BaseNFT1155 is ERC1155Initializable, OwnableInitializable, IBaseNFT1155 { using Strings for uint256; // keccak256("Permit(address owner,address spender,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0xdaab21af31ece73a508939fedd476a5ee5129a5ed4bb091f3236ffb45394df62; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; uint8 internal MAX_ROYALTY_FEE; address internal _factory; string internal _baseURI; mapping(uint256 => string) internal _uris; mapping(address => uint256) public override nonces; function initialize(address _owner) public override initializer { __ERC1155_init(""); __Ownable_init(_owner); _factory = msg.sender; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view virtual override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view virtual override returns (address) { return _factory; } function uri(uint256 id) public view virtual override(ERC1155Initializable, IERC1155MetadataURI) returns (string memory) { string memory _uri = _uris[id]; if (bytes(_uri).length > 0) { return _uri; } else { string memory baseURI = _baseURI; if (bytes(baseURI).length > 0) { return string(abi.encodePacked(baseURI, "{id}.json")); } else { baseURI = ITokenFactory(_factory).baseURI1155(); string memory addy = Strings.toHexString(uint160(address(this)), 20); return string(abi.encodePacked(baseURI, addy, "/{id}.json")); } } } function setURI(uint256 id, string memory newURI) external override onlyOwner { _uris[id] = newURI; emit SetURI(id, newURI); } function setBaseURI(string memory baseURI) external override onlyOwner { _baseURI = baseURI; emit SetBaseURI(baseURI); } function mint( address to, uint256 tokenId, uint256 amount, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mint(to, tokenId, amount, data); } function mintBatch( address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mintBatch(to, tokenIds, amounts, data); } function burn( uint256 tokenId, uint256 amount, uint256 label, bytes32 data ) external override { _burn(msg.sender, tokenId, amount); emit Burn(tokenId, amount, label, data); } function burnBatch(uint256[] calldata tokenIds, uint256[] calldata amounts) external override { _burnBatch(msg.sender, tokenIds, amounts); } function permit( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, nonces[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _setApprovalForAll(owner, spender, true); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/utils/Address.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 ERC1155Initializable is Initializable, 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}. */ function __ERC1155_init(string memory uri_) internal initializer { __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _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), "SHOYU: INVALID_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, "SHOYU: LENGTHS_NOT_EQUAL"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(msg.sender, 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(to != address(0), "SHOYU: INVALID_ADDRESS"); require(from == msg.sender || isApprovedForAll(from, msg.sender), "SHOYU: FORBIDDEN"); address operator = msg.sender; _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _transfer(from, to, id, amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } function _transfer( address from, address to, uint256 id, uint256 amount ) internal { uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); require(to != address(0), "SHOYU: INVALID_ADDRESS"); require(from == msg.sender || isApprovedForAll(from, msg.sender), "SHOYU: FORBIDDEN"); address operator = msg.sender; _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, "SHOYU: INSUFFICIENT_BALANCE"); _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; } function _setApprovalForAll( address account, address operator, bool approved ) internal { require(account != operator, "SHOYU: NOT_ALLOWED"); _operatorApprovals[account][operator] = approved; emit ApprovalForAll(account, operator, approved); } /** * @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), "SHOYU: INVALID_ADDRESS"); address operator = msg.sender; _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), "SHOYU: INVALID_ADDRESS"); require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); address operator = msg.sender; _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), "SHOYU: INVALID_ADDRESS"); address operator = msg.sender; _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _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), "SHOYU: INVALID_ADDRESS"); require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL"); address operator = msg.sender; _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, "SHOYU: INSUFFICIENT_BALANCE"); _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(to).onERC1155Received.selector) { revert("SHOYU: INVALID_RECEIVER"); } } catch Error(string memory reason) { revert(reason); } catch { revert("SHOYU: NO_RECEIVER"); } } } 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(to).onERC1155BatchReceived.selector) { revert("SHOYU: INVALID_RECEIVER"); } } catch Error(string memory reason) { revert(reason); } catch { revert("SHOYU: NO_RECEIVER"); } } } 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/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.3; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/DividendPayingERC20.sol"; import "./base/OwnableInitializable.sol"; import "./interfaces/ISocialToken.sol"; import "./libraries/Signature.sol"; contract SocialTokenV0 is DividendPayingERC20, OwnableInitializable, ISocialToken { // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 internal _DOMAIN_SEPARATOR; uint256 internal _CACHED_CHAIN_ID; address internal _factory; mapping(address => uint256) public override nonces; function initialize( address _owner, string memory _name, string memory _symbol, address _dividendToken, uint256 initialSupply ) external override initializer { __Ownable_init(_owner); __DividendPayingERC20_init(_name, _symbol, _dividendToken); _factory = msg.sender; _mint(_owner, initialSupply); _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function mint(address account, uint256 value) external override { require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN"); _mint(account, value); } function burn( uint256 value, uint256 label, bytes32 data ) external override { _burn(msg.sender, value); emit Burn(value, label, data); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "SHOYU: EXPIRED"); require(owner != address(0), "SHOYU: INVALID_ADDRESS"); require(spender != owner, "SHOYU: NOT_NECESSARY"); bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR()); _approve(owner, spender, value); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./ERC20Initializable.sol"; import "../libraries/TokenHelper.sol"; import "../interfaces/IDividendPayingERC20.sol"; /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether/erc20 /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: https://github.com/Roger-Wu/erc1726-dividend-paying-token/blob/master/contracts/DividendPayingToken.sol abstract contract DividendPayingERC20 is ERC20Initializable, IDividendPayingERC20 { using SafeCast for uint256; using SafeCast for int256; using TokenHelper for address; // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 public constant override MAGNITUDE = 2**128; address public override dividendToken; uint256 public override totalDividend; uint256 internal magnifiedDividendPerShare; function __DividendPayingERC20_init( string memory _name, string memory _symbol, address _dividendToken ) internal initializer { __ERC20_init(_name, _symbol); dividendToken = _dividendToken; } // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; /// @dev Syncs dividends whenever ether is paid to this contract. receive() external payable { if (msg.value > 0) { require(dividendToken == TokenHelper.ETH, "SHOYU: UNABLE_TO_RECEIVE_ETH"); sync(); } } /// @notice Syncs the amount of ether/erc20 increased to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// @return increased The amount of total dividend increased /// It emits the `Sync` event if the amount of received ether/erc20 is greater than 0. /// About undistributed ether/erc20: /// In each distribution, there is a small amount of ether/erc20 not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether/erc20 /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether/erc20 in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether/erc20, so we don't do that. function sync() public payable override returns (uint256 increased) { uint256 _totalSupply = totalSupply(); require(_totalSupply > 0, "SHOYU: NO_SUPPLY"); uint256 balance = dividendToken.balanceOf(address(this)); increased = balance - totalDividend; require(increased > 0, "SHOYU: INSUFFICIENT_AMOUNT"); magnifiedDividendPerShare += (increased * MAGNITUDE) / _totalSupply; totalDividend = balance; emit Sync(increased); } /// @notice Withdraws the ether/erc20 distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether/erc20 is greater than 0. function withdrawDividend() public override { uint256 _withdrawableDividend = withdrawableDividendOf(msg.sender); if (_withdrawableDividend > 0) { withdrawnDividends[msg.sender] += _withdrawableDividend; emit DividendWithdrawn(msg.sender, _withdrawableDividend); totalDividend -= _withdrawableDividend; dividendToken.safeTransfer(msg.sender, _withdrawableDividend); } } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function dividendOf(address account) public view override returns (uint256) { return withdrawableDividendOf(account); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` can withdraw. function withdrawableDividendOf(address account) public view override returns (uint256) { return accumulativeDividendOf(account) - withdrawnDividends[account]; } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has withdrawn. function withdrawnDividendOf(address account) public view override returns (uint256) { return withdrawnDividends[account]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account) /// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude /// @param account The address of a token holder. /// @return The amount of dividend in wei that `account` has earned in total. function accumulativeDividendOf(address account) public view override returns (uint256) { return ((magnifiedDividendPerShare * balanceOf(account)).toInt256() + magnifiedDividendCorrections[account]) .toUint256() / MAGNITUDE; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer( address from, address to, uint256 value ) internal override { super._transfer(from, to, value); int256 _magCorrection = (magnifiedDividendPerShare * value).toInt256(); magnifiedDividendCorrections[from] += _magCorrection; magnifiedDividendCorrections[to] -= _magCorrection; } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] -= (magnifiedDividendPerShare * value).toInt256(); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] += (magnifiedDividendPerShare * value).toInt256(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.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 ERC20Initializable is Initializable, 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 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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(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); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "SHOYU: INSUFFICIENT_ALLOWANCE"); _approve(sender, msg.sender, currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "SHOYU: ALLOWANCE_UNDERFLOW"); _approve(msg.sender, 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), "SHOYU: INVALID_SENDER"); require(recipient != address(0), "SHOYU: INVALID_RECIPIENT"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "SHOYU: INSUFFICIENT_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), "SHOYU: INVALID_ACCOUNT"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "SHOYU: INVALID_ACCOUNT"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "SHOYU: INVALID_OWNER"); require(spender != address(0), "SHOYU: INVALID_SPENDER"); _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 {} } // 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(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); 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"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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"); _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 (uint 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"); _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 (uint 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"); _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(to).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(to).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.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "../interfaces/IERC2981.sol"; contract ERC1155RoyaltyMock is ERC1155("MOCK") { address public owner; constructor() { owner = msg.sender; } function mint( address account, uint256 id, uint256 amount, bytes memory data ) external { _mint(account, id, amount, data); } function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external { _mintBatch(to, ids, amounts, data); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) { uint256 fee = 100; if (_tokenId < 10) fee = 10; return (owner, (_salePrice * fee) / 1000); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; contract ERC1155Mock is ERC1155("MOCK") { function mint( address account, uint256 id, uint256 amount, bytes memory data ) external { _mint(account, id, amount, data); } function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external { _mintBatch(to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/BaseExchange.sol"; contract ERC1155ExchangeV0 is BaseExchange { bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address internal immutable _factory; constructor(address factory_) { __BaseNFTExchange_init(); _factory = factory_; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function canTrade(address nft) public view override returns (bool) { return !ITokenFactory(_factory).isNFT1155(nft); } function _transfer( address nft, address from, address to, uint256 tokenId, uint256 amount ) internal override { IERC1155(nft).safeTransferFrom(from, to, tokenId, amount, ""); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./base/BaseExchange.sol"; contract ERC721ExchangeV0 is BaseExchange { bytes32 internal immutable _DOMAIN_SEPARATOR; uint256 internal immutable _CACHED_CHAIN_ID; address internal immutable _factory; constructor(address factory_) { __BaseNFTExchange_init(); _factory = factory_; _CACHED_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view override returns (bytes32) { bytes32 domainSeparator; if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR; else { domainSeparator = keccak256( abi.encode( // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(Strings.toHexString(uint160(address(this))))), 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) block.chainid, address(this) ) ); } return domainSeparator; } function factory() public view override returns (address) { return _factory; } function canTrade(address nft) public view override returns (bool) { return !ITokenFactory(_factory).isNFT721(nft); } function _transfer( address nft, address from, address to, uint256 tokenId, uint256 ) internal override { IERC721(nft).safeTransferFrom(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract ERC721Mock is ERC721("Mock", "MOCK") { function safeMint( address to, uint256 tokenId, bytes memory data ) external { _safeMint(to, tokenId, data); } function safeMintBatch0( address[] calldata to, uint256[] calldata tokenId, bytes memory data ) external { require(to.length == tokenId.length); for (uint256 i = 0; i < to.length; i++) { _safeMint(to[i], tokenId[i], data); } } function safeMintBatch1( address to, uint256[] calldata tokenId, bytes memory data ) external { for (uint256 i = 0; i < tokenId.length; i++) { _safeMint(to, tokenId[i], data); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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, 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 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 (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"); _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"); _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), "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"); _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), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal 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"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal 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 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.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20("Mock", "MOCK") { function mint(address to, uint256 amount) external { _mint(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IERC20Snapshot is IERC20, IERC20Metadata { function balanceOfAt(address account, uint256 snapshotId) external view returns (uint256); function totalSupplyAt(uint256 snapshotId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract FixedPriceSale is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256, uint256 ) external view override returns (bool) { uint256 price = abi.decode(params, (uint256)); require(price > 0, "SHOYU: INVALID_PRICE"); return (proxy != address(0) || block.timestamp <= deadline) && bidPrice == price; } function canBid( address, uint256, bytes memory, address, uint256, address, uint256, uint256 ) external pure override returns (bool) { return false; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract EnglishAuction is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address bidder, uint256 bidPrice, address bestBidder, uint256 bestBidPrice, uint256 ) external view override returns (bool) { if (proxy == address(0)) { return bidder == bestBidder && bidPrice == bestBidPrice && deadline < block.timestamp; } else { uint256 startPrice = abi.decode(params, (uint256)); require(startPrice > 0, "SHOYU: INVALID_START_PRICE"); return bidPrice >= startPrice && deadline < block.timestamp; } } function canBid( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256 bestBidPrice, uint256 ) external view override returns (bool) { if (proxy == address(0)) { uint256 startPrice = abi.decode(params, (uint256)); require(startPrice > 0, "SHOYU: INVALID_START_PRICE"); return block.timestamp <= deadline && bidPrice >= startPrice && bidPrice > bestBidPrice; } else { return false; } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "../interfaces/IStrategy.sol"; contract DutchAuction is IStrategy { function canClaim( address proxy, uint256 deadline, bytes memory params, address, uint256 bidPrice, address, uint256, uint256 ) external view override returns (bool) { (uint256 startPrice, uint256 endPrice, uint256 startedAt) = abi.decode(params, (uint256, uint256, uint256)); require(startPrice > endPrice, "SHOYU: INVALID_PRICE_RANGE"); require(startedAt < deadline, "SHOYU: INVALID_STARTED_AT"); uint256 tickPerBlock = (startPrice - endPrice) / (deadline - startedAt); uint256 currentPrice = block.timestamp >= deadline ? endPrice : startPrice - ((block.timestamp - startedAt) * tickPerBlock); return (proxy != address(0) || block.timestamp <= deadline) && bidPrice >= currentPrice; } function canBid( address, uint256, bytes memory, address, uint256, address, uint256, uint256 ) external pure override returns (bool) { return false; } }
This function should be called by a multi-sig `owner`, not an EOA
function setOperationalFeeRecipient(address operationalFeeRecipient) external override onlyOwner { require(operationalFeeRecipient != address(0), "SHOYU: INVALID_RECIPIENT"); _operationalFeeRecipient = operationalFeeRecipient; emit SetOperationalFeeRecipient(operationalFeeRecipient); }
96,695
./partial_match/97/0xe0A1453c23Df8B6CdB5233d50d1BEb666F57cc37/sources/FACDOGEPool.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'FACDOGEPool: Cannot stake 0'); uint256 newDeposit = deposits[msg.sender].add(amount); require( newDeposit <= 20000e18, 'FACDOGEPool: deposit amount exceeds maximum 20000' ); deposits[msg.sender] = newDeposit; super.stake(amount); emit Staked(msg.sender, amount); }
11,344,066